Ansible - 使用 with_items 访问 shell 命令的输出

Ansible - Access output of a shell command with with_items

我写了一个 python 脚本,它通过我的 ansible 剧本执行,returns 通过 stdout 输出以下内容:

- { username: ansible, admin: yes}
- { username: test, admin: no }

然后输出应该保存在变量 "users" 和 "with_items" (或更新的 "loop" 条件)我想遍历变量以便分配每个用户单独的权限:

- name: execute python script
  command: "python3 /tmp/parse_string.py --user_permissions={{ user_permissions }}"
  register: output

- name: register
  set_fact:
    users: "{{ output.stdout }}"

- name: output
  debug: msg="{{ users }}"

- name: Add user to group -admin
  user:
    name={{ item.username }}
    groups=admin
    append=yes
    state=present
  when: "item.admin == yes"
  with_items: '{{users}}

然而,当启动剧本时,它说变量 "users" 没有属性 "username"。

TASK [create_users : output] ***************************************************
ok: [ansible] => {
    "msg": "- { username: ansible, admin: yes }\n- { username: test, admin: no }\n- { username: test2, admin: no }"
}
TASK [create_users : Add user to group -admin ***************
fatal: [ansible]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'username'\n\nThe error appears to be in '***': line 29, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: \n  ^ here\n"}

谁能帮我解决这个问题?

BR

您正在将 users 变量设置为字符串。碰巧这个字符串是数据结构的 yaml 表示,但 ansible 对此一无所知。

为了达到您的要求,您需要将该字符串解析为yaml 并注册结果。幸运的是,有一个 from_yaml filter 用于此目的

您只需按如下方式修改您的 set_fact 任务,一切都会按预期进行:

- name: register
  set_fact:
    users: "{{ output.stdout | from_yaml }}"