作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须向从 csv 文件读取到变量的列表中添加一个键和一个值。
为了更好地解释它。首先,我从一个 csv 文件加载一个列表:
- name: Load user list from csv
community.general.read_csv:
path: ../files/example-prod.csv
delimiter: ','
register: users
delegate_to: localhost
当我查看“用户”变量时,我得到以下输出:
"list": [
{
"firstName": "Max",
"gid": "2002",
"homedir": "example",
"lastName": "Mustermann",
"uid": "m.example"
},
{
"firstName": "Martin",
"gid": "2002",
"homedir": "staff",
"lastName": "Muster",
"uid": "martin.muster"
}
]
现在我需要为列表中的所有用户生成密码。所以我想遍历项目并为列表中的每个项目添加一个新的键值对。
密码创建循环后我想要的输出是:
"list": [
{
"firstName": "Max",
"gid": "2002",
"homedir": "example",
"lastName": "Mustermann",
"uid": "m.example",
"password": "examplepassword"
},
{
"firstName": "Martin",
"gid": "2002",
"homedir": "staff",
"lastName": "Muster",
"uid": "martin.muster",
"password": "examplepassword"
}
]
...这样我可以稍后读出变量。
如何实现?我读过很多关于如何使用字典执行此操作的内容,但由于我在这里使用的是列表,所以我找不到它。
最佳答案
您实际上是从 read_csv
中获取字典列表模块。 "list"
的内容是一个列表,但是这个列表中的元素是字典。
你要做的是在每个字典中添加一个键值对。
这是生成随 secret 码的示例。查看password-lookup documentation关于它如何生成密码的详细信息:
- set_fact:
users: |
{{ users.list | map('combine', { "password": "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=8') }}"}) }}
# this resolves the template added above and is required to avoid changing passwords on each resolve of users
- set_fact:
users: "{{ users }}"
- debug:
msg: "{{ users }}"
解释:
users.list
包含您的用户列表map('combine', <dict>)
运行 combine
过滤输入列表中的每个字典(在本例中为 users.list
)并添加 <dict>
的内容对它{ "password": "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=8') }}"}
是我们将每个输入字典与"password"
是键,值是生成密码的查找备注:
我使用 yaml 的多行字符串文字来避免引用 hell 。
关于csv - 如何将键值对添加到列表中的每个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67431252/
我是一名优秀的程序员,十分优秀!