有一种方法可以获取 JSON 文件列表,每个文件代表 Ansible 中 vars.yml 文件中的一个特定用户。
示例:
-users:
- username: jsmith
project_role: administrators
full_name: John Smith
email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59333631372a34302d311934383035773a3634" rel="noreferrer noopener nofollow">[email protected]</a>
- username: pmorrison
project_role: developer
full_name: Paul Morrison
email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="334352465f5e5c41415a405c5d735e525a5f1d505c5e" rel="noreferrer noopener nofollow">[email protected]</a>
例如,我特别想将单个用户设计为单个 json 文件。约翰·史密斯 (John smith) 的一个 json 文件包含他的所有信息,保罗·莫里森 (paul morrison) 的一个 json 文件包含他的所有信息,依此类推。
谢谢
最佳答案
这个问题可以通过字典中的数据轻松解决。例如
shell> cat user.d/jsmith.yml
jsmith:
project_role: administrators
full_name: John Smith
email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee4e1e6e0fde3e7fae6cee3efe7e2a0ede1e3" rel="noreferrer noopener nofollow">[email protected]</a>
shell> cat user.d/pmorrison.yml
pmorrison:
project_role: developer
full_name: Paul Morrison
email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aadacbdfc6c7c5d8d8c3d9c5c4eac7cbc3c684c9c5c7" rel="noreferrer noopener nofollow">[email protected]</a>
剧本
shell> cat pb.yml
- hosts: localhost
tasks:
- include_vars:
dir: user.d
name: users
- debug:
var: users
给出
"users": {
"jsmith": {
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52383d3a3c213f3b263a123f333b3e7c313d3f" rel="noreferrer noopener nofollow">[email protected]</a>",
"full_name": "John Smith",
"project_role": "administrators"
},
"pmorrison": {
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9b9a8bca5a4a6bbbba0baa6a789a4a8a0a5e7aaa6a4" rel="noreferrer noopener nofollow">[email protected]</a>",
"full_name": "Paul Morrison",
"project_role": "developer"
}
}
如果需要,可以创建该列表。例如
- set_fact:
users_list: "{{ users_list|d([]) +
[{'username': item.0}|combine(item.1)] }}"
with_together:
- "{{ users.keys()|list }}"
- "{{ users.values()|list }}"
- debug:
var: users_list
给出
"users_list": [
{
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543e3b3c3a27393d203c1439353d387a373b39" rel="noreferrer noopener nofollow">[email protected]</a>",
"full_name": "John Smith",
"project_role": "administrators",
"username": "jsmith"
},
{
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="502031253c3d3f222239233f3e103d31393c7e333f3d" rel="noreferrer noopener nofollow">[email protected]</a>",
"full_name": "Paul Morrison",
"project_role": "developer",
"username": "pmorrison"
}
]
关于ansible - ansible 中的 JSON 文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61709817/