0

i have an ansible as below which simply connects to a given server and runs a script on that server.

name: framework
  hosts: target_hosts
  vars:
    base_dir: /tmp
    log_file: "{{ base_dir }}/update_oem_{{ db_unique_name }}_{{ ansible_date_time.iso8601_basic_short }}.log"
  become_user: oracle
  become: yes
  tasks:
    - name: Execute module
      block:
        - name: "Run Update OEM against {{ db_unique_name }} and redirect all output to {{ log_file }}"
          shell: "/local/oracle/myapp/workflows/run_update_oracle_home.sh {{ db_unique_name }} > {{ log_file }} 2>&1"

      rescue:
        - debug:
            msg: "Update failed, please engage Support team."
      always:
        - name: "Now cat the contents {{ log_file }} so that standard out is displayed"
          shell: "cat {{ log_file }}"

I now need to add some code in the same code where we can check the log_file for a string 'Error' or 'Traceback',and if the string is found return a failure of the ansible code.

  - name: "Searching for an error in log_file"
    become: yes
    become_user: oracle
    register: presence
    shell: " egrep -w 'Error|Traceback' {{ log_file }}"

  - name: "task in case the error is present in the file"
    debug: msg="Script failure"
    when: presence is changed

The code is now checking the strings as specified,but is not failing even when they are found.please advise as i am new to ansible.Thanks.

svk
  • 3
  • 3
  • 2
    Always avoid using shell commands in Ansible. Use [lineinfile module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html) in check_mode, checkout this [answer](https://stackoverflow.com/questions/38461920/ansible-check-if-string-exists-in-file#answer-46454251) – Khaled Oct 13 '22 at 21:21
  • 2
    What did not work as expected with your code? Please read [ask] and pay attention to the [mre] section. And yes: avoid using shell when you don't have to. – Zeitounator Oct 13 '22 at 21:34
  • 1
    @Khaled, indeed, looks like a duplicate. Also of [Only check whether a line present in a file (Ansible)](https://stackoverflow.com/questions/30786263/). – U880D Oct 14 '22 at 05:25
  • The code is running as expected,but is not throwing an error when the given strings are found. @Zeitounator – svk Oct 14 '22 at 14:14

1 Answers1

0

Used the below and it works fine now.Thanks.

- name: "Check for an error in log_file"
  become: yes
  become_user: oracle
  command: egrep -w 'Error|Traceback' {{ log_file }}
  register: shell_out
  failed_when: "'Error' in shell_out.stdout"
svk
  • 3
  • 3