在检查模式下运行时跳过Ansible任务?

aug*_*rar 45 ansible ansible-playbook

我正在编写一本Ansible剧本,并且有一项任务在检查模式下总是会失败:

hosts: ...
tasks:
    - set_fact: filename="{{ansible_date_time.iso8601}}"
    - file: state=touch name={{filename}}
    - file: state=link src={{filename}} dest=latest
Run Code Online (Sandbox Code Playgroud)

在检查模式下,将不会创建该文件,因此link任务将始终失败.有没有办法在检查模式下运行时标记要跳过的任务?就像是:

- file: state=link src={{filename}} dest=latest
  when: not check_mode
Run Code Online (Sandbox Code Playgroud)

Str*_*dic 49

Ansible 2.1支持在检查模式(官方文档)中ansible_check_mode设置的魔术变量.这意味着您将能够这样做:True

- file:
    state: link
    src: '{{ filename }}'
    dest: latest
  when: not ansible_check_mode
Run Code Online (Sandbox Code Playgroud)

要么

- file:
    state: link
    src: '{{ filename }}'
    dest: latest
  ignore_errors: '{{ ansible_check_mode }}'
Run Code Online (Sandbox Code Playgroud)

无论你喜欢什么.

  • 我想指出,了解所使用的模块如何处理检查模式很重要,请确保您了解在测试剧本时忽略的内容。此外,当使用 `ignore_errors` 时,如果任务中未定义变量,playbook 运行不会失败,当使用 `when: not ansible_check_mode` 跳过任务时,它会失败。因此,在检查模式下修改任务行为时,再次了解您要测试的内容很重要。 (2认同)

aug*_*rar 11

这是一种hacky解决方案:

hosts: ...
tasks:
  - command: /bin/true
    register: noop_result
  - set_fact: check_mode={{ noop_result|skipped }}

  - set_fact: filename="{{ansible_date_time.iso_8601}}"
  - file: state=touch name={{filename}}
  - file: state=link src={{filename}} dest=latest
    when: not check_mode
Run Code Online (Sandbox Code Playgroud)

在检查模式下,command将跳过任务,因此check_mode将设置为true.不处于检查模式时,任务应始终成功并将check_mode设置为false.

  • 他们终于做到了:https://github.com/ansible/ansible/pull/14028可能会在下一个ansible版本中. (2认同)