Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible overwrite variable depending on result

Tags:

ansible

I am running several shell commands in an ansible playbook that may or may not modify a configuration file.

One of the items in the playbook is to restart the service. But I only want to do this if a variable is set.

I am planning on registering a result in each of the shell tasks, but I do not want to overwrite the variable if it is already set to 'restart_needed' or something like that.

The idea is the restart should be the last thing to go, and if any of the commands set the restart variable, it will go, and if none of them did, the service will not be restarted. Here is an example of what I have so far...

tasks:
  - name: Make a backup copy of file
    copy: src={{ file_path }} dest={{ file_path }}.{{ date }} remote_src=true owner=root group=root mode=644 backup=yes

  - name: get list of items
    shell: |
      grep <file>
    register: result

  - name: output will be 'restart_needed'
    shell: |
      NUM=14"s"; if [ "${NUM}" != "s" ]; then sed -i "${NUM}/no/yes/g" {{ file_path }}; echo "restart_needed"; else echo "nothing_changed" ; fi
    with_items: "{{ result.stdout_lines }}"
    register: output

  - name: output will be 'nothing_changed'
    shell: |
      NUM="s"; if [ "${NUM}" != "s" ]; then sed -i "${NUM}/no/yes/g" {{ file_path }}; echo "restart_needed"; else echo "nothing_changed" ;; fi 
    with_items: "{{ result.stdout_lines }}"
    register: output

  - name: Restart  service
    service: name=myservice enabled=yes state=restarted

In the above example, the variable output will be set to restart_needed after the first task but then will be changed to 'nothing_changed' in the second task.

I want to keep the variable at 'restart_needed' if it is already there and then kick off the restart service task only if the variable is set to restart_needed.

Thanks!

like image 885
user1601716 Avatar asked May 31 '26 07:05

user1601716


1 Answers

For triggering restarts, you have two options: the when statement or handlers.

When statement example:

tasks:
  - name: check if string "foo" exists in somefile
    shell: grep -q foo somefile
    register: result

  - name: restart service
    service:
      name: myservice
      enabled: yes
      state: restarted
    when: result.rc == 0

Handlers example:

tasks:
  - name: check if string "foo" exists in somefile
    shell: grep -q foo somefile
    register: result
    changed_when: "result.rc == 0"
    notify: restart service

handlers:
  - name: restart service
    service:
      name: myservice
      enabled: yes
      state: restarted
like image 149
Garrett Hyde Avatar answered Jun 03 '26 06:06

Garrett Hyde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!