【问题标题】:specific tasks should be only for single server特定任务应该只针对单个服务器
【发布时间】:2019-01-15 00:08:50
【问题描述】:

很少有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

【问题讨论】:

  • 那么run_once: yes 有什么问题?此外,请小心使用>>,除非您有--forks 1,因为它可以同时执行并导致意外行为(该文件没有锁定)。此外,action: shell 是一些您绝对应该避免使用的非常古老的语法

标签: ansible ansible-2.x


【解决方案1】:

你需要 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

【讨论】:

    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2021-01-20
    • 2023-04-05
    • 1970-01-01
    • 2020-08-22
    相关资源
    最近更新 更多