首页 > 解决方案 > Ansible - 使用 with_items 访问 shell 命令的输出

问题描述

我编写了一个 python 脚本,它通过我的 ansible playbook 执行,并通过 stdout 返回以下输出:

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

然后输出应该保存在变量“users”中并使用“with_items”(或更新的“循环”条件)我想遍历变量以便分别为每个用户分配正确的权限:

- 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}}

然而,当启动剧本时,它说变量“用户”没有属性“用户名”。

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

标签: python-3.xansibleansible-tower

解决方案


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

为了满足您的要求,您需要将该字符串解析为 yaml 并注册结果。幸运的是,为此目的有一个from_yaml过滤器

您只需set_fact按以下方式修改您的任务,一切都应该按预期工作:

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

推荐阅读