首页 > 解决方案 > 特定任务应该只针对单个服务器

问题描述

很少有ansible任务应该只运行一次而不是多次

我仍在学习 ansible,并且我编写了一个 ansible 剧本,其中包含一个任务,例如将用户名回显到日志文件,但是当它在远程主机上运行时,它会回显输出的所有内容。任何帮助表示赞赏。

- 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

/tmp/audit_list 如下所示:

 tommy user
 tommy user
remote host is apache1

由于我在 3 台服务器上运行上述 playbook,它打印了 3 次用户名,但我只想打印一次,然后是执行 playbook 的所有远程主机。

以下是我正在寻找的所需输出

tommy user
remote host is apache1 
remote host is apache2
remote hoost is apache3

标签: ansibleansible-2.x

解决方案


你需要run_once。请参阅下面的示例

- 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

推荐阅读