gpt4 book ai didi

linux - 在 Ansible 中使用带有循环的寄存器

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:57 24 4
gpt4 key购买 nike

我想编写一个剧本,如果用户存在,则更改它的密码。该剧本应该能够接受 n 个用户并更改这些用户的密码。

目前我遇到的问题是,由于循环,when 为空,我尝试使用 with_items: {{ user_exists.results }} 但这在某种程度上不起作用。( http://docs.ansible.com/ansible/playbooks_loops.html#using-register-with-a-loop )

我做错了什么吗?

兄弟,纳 bool 六号

---
-
become: true
become_method: sudo
hosts: xetest
name: "Updates the password of given User if exists"
tasks:
-
ignore_errors: true
name: "Check if User exists"
register: user_exists
shell: "grep -q {{ item.key }} /etc/passwd &>/dev/null"
with_dict: "{{ users }}"
-
debug:
var: user_exists
-
debug:
msg: "User name is {{ item.key }} and hash is {{ item.value.passwd}} and return code is: "
with_dict: "{{ users }}"
-
debug:
var: user_exists
with_items: "{{user_exists.results }}"
-
name: "updating password for given User"
user: "name={{ item.key }} update_password=always password={{ item.value.passwd}} createhome=no"
when: user_exists.rc == 0
with_dict: "{{ users }}"
with_items: "{{ user_exists.results }}"
vars:
users:
foo:
passwd: $6$random_salt$12A.ar9eNDsgmds3leKoCDZPmq7OHLvhBtQg/Q3K2G/3yeEa/r8Ou4DxJpN6vzccewugvZt7IkfCbHFF2i.QU.

结果有错误!

 duplicate loop in task: items

没有 with_items: "{{ user_exists.results }}"我收到此错误

"failed": true, "msg": "The conditional check 'user_exists.rc == 0' failed. 
The error was: error while evaluating conditional (user_exists.rc == 0):
'dict object' has no attribute 'rc'

最佳答案

对于我的测试,我使用 ansible 2.1.4.0。

运行脚本时,您可以在 user_exists.results 的调试中看到它包含传入的输入值以及返回码:

    "results": [
{
"_ansible_item_result": true,
"_ansible_no_log": false,
"_ansible_parsed": true,
"changed": true,
"cmd": "grep -q foo /etc/passwd",
"delta": "0:00:00.009034",
"end": "2017-05-02 17:42:57.835871",
"failed": true,
"invocation": {
"module_args": {
"_raw_params": "grep -q foo /etc/passwd",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"item": {
"key": "foo",
"value": {
"passwd": "foobar"
}
},
"rc": 1,
"start": "2017-05-02 17:42:57.826837",
"stderr": "",
"stdout": "",
"stdout_lines": [],
"warnings": []
},

因此,您可以用一个循环完成所有操作,而不是执行两个循环(这将使用 with_nested 和两个列表完成):

- name: "updating password for given User"
debug:
msg: "name={{ item.item.key }} update_password=always password={{ item.item.value.passwd}} createhome=no"
when: item.rc == 0
with_items: "{{ user_exists.results }}"

注意:在我的测试 shell 中:“grep -q {{ item.key }}/etc/passwd &>/dev/null”始终返回 0 返回代码。我必须删除“&>/dev/null”部分才能获得正确的返回代码。

关于linux - 在 Ansible 中使用带有循环的寄存器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com