验证任务:检查模式和差异模式
Ansible 提供两种验证任务的执行模式:检查模式和差异模式。这些模式可以单独或一起使用。当您创建或编辑剧本或角色时,如果您想知道它将做什么,这些模式很有用。在检查模式下,Ansible 运行而不对远程系统进行任何更改。支持检查模式的模块会报告它们将进行的更改。不支持检查模式的模块不会报告任何内容,也不会执行任何操作。在差异模式下,Ansible 提供前后比较。支持差异模式的模块将显示详细信息。您可以将检查模式和差异模式结合使用,以详细验证您的剧本或角色。
使用检查模式
检查模式只是一个模拟。它不会为使用 基于注册变量的条件(先前任务的结果)的任务生成输出。但是,它非常适合验证一次在一个节点上运行的配置管理剧本。要以检查模式运行剧本
ansible-playbook foo.yml --check
在任务中强制执行或阻止检查模式
版本 2.2 中的新增功能。
如果您希望某些任务始终或从不以检查模式运行,无论您是否使用或不使用 --check
运行剧本,您都可以将 check_mode
选项添加到这些任务中
要强制任务以检查模式运行,即使在不使用
--check
调用剧本时,也要设置check_mode: true
。要强制任务以正常模式运行并对系统进行更改,即使在使用
--check
调用剧本时,也要设置check_mode: false
。
例如
tasks:
- name: This task will always make changes to the system
ansible.builtin.command: /something/to/run --even-in-check-mode
check_mode: false
- name: This task will never make changes to the system
ansible.builtin.lineinfile:
line: "important config"
dest: /path/to/myconfig.conf
state: present
check_mode: true
register: changes_to_important_config
使用 check_mode: true
运行单个任务对于测试 Ansible 模块很有用,无论是测试模块本身还是测试模块进行更改的条件。您可以在这些任务上注册变量(参见 条件),以获取有关潜在更改的更多详细信息。
注意
在 2.2 版本之前,只存在等效于 check_mode: false
的内容。它的表示法是 always_run: true
。
跳过任务或忽略检查模式中的错误
版本 2.1 中的新增功能。
如果您希望在以检查模式运行 Ansible 时跳过任务或忽略任务上的错误,您可以使用一个布尔魔术变量 ansible_check_mode
,它在 Ansible 以检查模式运行时设置为 True
。例如
tasks:
- name: This task will be skipped in check mode
ansible.builtin.git:
repo: ssh://git@github.com/mylogin/hello.git
dest: /home/mylogin/hello
when: not ansible_check_mode
- name: This task will ignore errors in check mode
ansible.builtin.git:
repo: ssh://git@github.com/mylogin/hello.git
dest: /home/mylogin/hello
ignore_errors: "{{ ansible_check_mode }}"
使用差异模式
ansible-playbook 的 --diff
选项可以单独使用或与 --check
一起使用。当您以差异模式运行时,任何支持差异模式的模块都会报告所做的更改,或者,如果与 --check
一起使用,则会报告将进行的更改。差异模式在操作文件的模块中最常见(例如,模板模块),但其他模块也可能会显示“前后”信息(例如,用户模块)。
差异模式会生成大量输出,因此最好在检查单个主机时使用它。例如
ansible-playbook foo.yml --check --diff --limit foo.example.com
版本 2.4 中的新增功能。
在任务中强制执行或阻止差异模式
由于 --diff
选项可能会泄露敏感信息,因此您可以通过指定 diff: false
来禁用任务的差异模式。例如
tasks:
- name: This task will not report a diff when the file changes
ansible.builtin.template:
src: secret.conf.j2
dest: /etc/secret.conf
owner: root
group: root
mode: '0600'
diff: false