我有以下Ansible Playbook代码:
- 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 } } }
...因为register
无论when
条件如何,每个块都会被执行.
我如何解决这个问题,以免make_password
在when
条件不满足时被覆盖?
或者如果这是你可以看到的我想要完成的错误方法,请告诉我一个更好的方法.
不幸的是,这是预期的行为.来自Ansible变量
注意 如果任务失败或被跳过,变量仍然会注册失败或跳过状态,避免注册变量的唯一方法是使用标记.
我不知道如何使用标签来解决您的问题.
编辑:我找到了一种方法,虽然原油解决方案.存储结果,以便不会覆盖它
- set_fact: mypwd="{{make_password}}" when: make_password.changed
所以你的代码看起来像:
- 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