Ansible:如何避免在“when"出现时注册变量条件*不*满足? [英] Ansible: How do I avoid registering a variable when a "when" condition is *not* met?
问题描述
我有以下 Ansible Playbook 代码:
I have the following Ansible Playbook code:
- name: Users | Generate password for user (Debian/Ubuntu)
shell: makepasswd --chars=20
register: make_password
when: ansible_distribution in ['Debian', 'Ubuntu']
- name: Users | Generate password for user (Fedora)
shell: makepasswd -m 20 -M 20
register: make_password
when: ansible_distribution in ['Fedora', 'Amazon']
- name: Users | Generate password for user (CentOS)
shell: mkpasswd -l 20
register: make_password
when: ansible_distribution in ['CentOS']
- name: debug
debug: var=make_password
输出:
TASK: [users | debug]
ok: [127.0.0.1] => {
"var": {
"make_password": {
"changed": false,
"skipped": true
}
}
}
... 因为无论 when
条件如何,每个 register
块都会被执行.
... Because every register
block gets executed regardless of the when
condition.
如果不满足 when
条件,我将如何解决这个问题,以便 make_password
不会被覆盖?
How would I fix this so make_password
doesn't get overwritten when the when
condition isn't met?
或者,如果对于您所看到的我正在努力实现的目标来说,这是错误的方法,请告诉我更好的方法.
Or if this is the wrong approach for what you can see that I'm trying to accomplish, let me know of a better one.
推荐答案
不幸的是,这是预期的行为.来自 Ansible 变量
Unfortunately, this is the expected behavior. From Ansible Variables
注意如果任务失败或被跳过,变量仍然被注册失败或跳过状态,避免注册一个的唯一方法变量正在使用标签.
Note If a task fails or is skipped, the variable still is registered with a failure or skipped status, the only way to avoid registering a variable is using tags.
我不知道如何使用标签来解决您的问题.
I do not know how to use tags to solve your issue.
我找到了一种方法,尽管这是一个粗略的解决方案.存储结果以免被覆盖
I found a way albeit a crude solution. Store the results so that it is not overwritten
- set_fact: mypwd="{{make_password}}"
when: make_password.changed
所以你的代码看起来像:
So your code will look like:
- name: Users | Generate password for user (Debian/Ubuntu)
shell: makepasswd --chars=20
register: make_password
when: ansible_distribution in ['Debian', 'Ubuntu']
- set_fact: mypwd="{{make_password}}"
when: make_password.changed
- name: Users | Generate password for user (Fedora)
shell: makepasswd -m 20 -M 20
register: make_password
when: ansible_distribution in ['Fedora', 'Amazon']
- set_fact: mypwd="{{make_password}}"
when: make_password.changed
- name: Users | Generate password for user (CentOS)
shell: mkpasswd -l 20
register: make_password
when: ansible_distribution in ['CentOS']
- set_fact: mypwd="{{make_password}}"
when: make_password.changed
- name: debug
debug: var=mypwd
这篇关于Ansible:如何避免在“when"出现时注册变量条件*不*满足?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!