1
votes

Few ansible tasks should be run only once instead of multiple times

I am still learning the ansible and I wrote an ansible playbook which contains a task like echo username to a log file but it is echoing the output everything when it run on remote hosts. Any help is appreciated.

- name: user
shell: echo "$LOGNAME user"  >> /tmp/audit_list
delegate_to: localhost

- name: remote hosts 
action: shell  echo "remote host is {{ansible_fqdn}}" >> /tmp/audit_list
delegate_to: localhost

The /tmp/audit_list looks like below:

 tommy user
 tommy user
remote host is apache1

Since i am running the above playbook on 3 servers, it is printing the user name three times but i want to print it only one time followed by all remote hosts where the playbook was executed.

Below is the desired output i am looking for

tommy user
remote host is apache1 
remote host is apache2
remote hoost is apache3
1
so what's wrong with run_once: yes? Also, be careful of using >> unless you have --forks 1 because that can can execute concurrently and cause unexpected behavior (there's no locking for that file). Also, action: shell is some seriously old syntax that you should definitely avoid - mdaniel

1 Answers

0
votes

You need run_once. See example below

- hosts: all
  gather_facts: yes
  tasks:
    - name: user
      shell: echo "$LOGNAME user"  >> /tmp/audit_list
      delegate_to: localhost
      run_once: true
    - name: remote hosts 
      shell:  echo "remote host is {{ansible_fqdn}}" >> /tmp/audit_list
      delegate_to: localhost


> cat /tmp/audit_list 
root user
remote host is test_01
remote host is test_02
remote host is test_03