在ansible中将一个字典列表映射到另一个列表
Mapping one list of dicts to another in ansible
我有一个这样定义的客户变量:
clients:
- name: 'acme'
production: False
db_pwd: '123'
- name: 'example'
production: True
db_pwd: '456'
我需要处理这个列表并为 mongo 数据库中的用户提供另一个列表
users:
- database: 'client_acme',
name: 'client_acme',
password: '123'
roles: ['readWrite', 'dbAdmin']
- database: 'client_example',
name: 'client_example',
password: '456'
roles: ['readWrite', 'dbAdmin']
我该怎么做?
此任务完成工作:
- name: "Test1"
hosts: localhost
vars:
clients:
- name: 'acme'
production: False
db_pwd: '123'
- name: 'example'
production: True
db_pwd: '456'
tasks:
- name: set_fact
set_fact:
users: "{{ users | default([]) + [ ({ 'database': newname, 'name': newname, 'password': password, 'roles': ['readWrite', 'dbAdmin'] })] }}"
loop: "{{ clients }}"
vars:
newname: client_{{ item.name }}
password: "{{ item.db_pwd }}"
- name: debug users
debug:
var: users
结果:
ok: [localhost] =>
users:
- database: client_acme
name: client_acme
password: '123'
roles:
- readWrite
- dbAdmin
- database: client_example
name: client_example
password: '456'
roles:
- readWrite
- dbAdmin
我有一个这样定义的客户变量:
clients:
- name: 'acme'
production: False
db_pwd: '123'
- name: 'example'
production: True
db_pwd: '456'
我需要处理这个列表并为 mongo 数据库中的用户提供另一个列表
users:
- database: 'client_acme',
name: 'client_acme',
password: '123'
roles: ['readWrite', 'dbAdmin']
- database: 'client_example',
name: 'client_example',
password: '456'
roles: ['readWrite', 'dbAdmin']
我该怎么做?
此任务完成工作:
- name: "Test1"
hosts: localhost
vars:
clients:
- name: 'acme'
production: False
db_pwd: '123'
- name: 'example'
production: True
db_pwd: '456'
tasks:
- name: set_fact
set_fact:
users: "{{ users | default([]) + [ ({ 'database': newname, 'name': newname, 'password': password, 'roles': ['readWrite', 'dbAdmin'] })] }}"
loop: "{{ clients }}"
vars:
newname: client_{{ item.name }}
password: "{{ item.db_pwd }}"
- name: debug users
debug:
var: users
结果:
ok: [localhost] =>
users:
- database: client_acme
name: client_acme
password: '123'
roles:
- readWrite
- dbAdmin
- database: client_example
name: client_example
password: '456'
roles:
- readWrite
- dbAdmin