python-3.x - 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
解决方案
您正在将users
var 设置为字符串。碰巧这个字符串是数据结构的 yaml 表示,但 ansible 目前对此一无所知。
为了满足您的要求,您需要将该字符串解析为 yaml 并注册结果。幸运的是,为此目的有一个from_yaml
过滤器
您只需set_fact
按以下方式修改您的任务,一切都应该按预期工作:
- name: register
set_fact:
users: "{{ output.stdout | from_yaml }}"
推荐阅读
- django - Django 在 BASE_DIR 路径之前抓取
- html - HTML 中的缩进,没有不需要的空格
- android - java.lang.ArrayIndexOutOfBoundsException:长度=5;指数=5
- c# - 图片框的大小与初始化为的大小不同
- php - 如何完全禁用 WooCommerce 产品类型的运输?
- java - 查找两个字符串的交集,其中返回两个字符串中出现的字符(与第一个字符串的序列顺序相同)
- android - 迁移到androidX后约束布局视图向右跳转
- node.js - 为什么不能得到查询结果
- mysql - 为什么 max() 只给我该列中的最大值
- php - 如何从 codegnitor 中的数组“data”键获取数据?