仅在发生更改时才执行复制和设置

Nic*_*mer 7 ubuntu deployment provisioning timezone ansible

对于 Ansible,我有一个角色来设置时区并填充 (Ubuntu) 基本系统的设置,

- name: set timezone
  copy: content='Europe/Berlin'
        dest=/etc/timezone
        owner=root
        group=root
        mode=0644
        backup=yes

- name: update timezone
  command: dpkg-reconfigure --frontend noninteractive tzdata
Run Code Online (Sandbox Code Playgroud)

这两个命令无论如何都会执行。这意味着当 Ansible 为同一个目标运行两次时,changed=2结果摘要中仍然会得到一个,

default                    : ok=41   changed=2    unreachable=0    failed=0
Run Code Online (Sandbox Code Playgroud)

理想情况下,一切都应该ok在第二次运行中。

虽然我猜测update timezone应该对 有某种依赖set timezone,但我不太确定如何最好地实现这一点。

Hen*_*gel 12

您可以通过使用register和来做到这一点when changed

通过使用registercopy命令的结果被保存到一个变量中。然后可以利用此变量when更新时区任务中创建条件。

另外,请确保\n在时区内容的末尾添加换行符,否则 Ansible 将始终执行 copy

- name: set timezone
  copy: content='Europe/Berlin\n'
        dest=/etc/timezone
        owner=root
        group=root
        mode=0644
        backup=yes
  register: timezone

- name: update timezone
  command: dpkg-reconfigure --frontend noninteractive tzdata
  when: timezone.changed
Run Code Online (Sandbox Code Playgroud)

但是您也可以通过为此处handler所述的dpkg-reconfigure命令创建一个来解决此问题:

tasks:
  - name: Set timezone variables
    copy: content='Europe/Berlin\n'
          dest=/etc/timezone
          owner=root
          group=root
          mode=0644
          backup=yes
    notify:
      - update timezone
handlers:
 - name: update timezone
   command: dpkg-reconfigure --frontend noninteractive tzdata
Run Code Online (Sandbox Code Playgroud)