我正在尝试在 Ansible 中构建 JSON 对象数组/列表。我的剧本通过指定来调用--extra-vars "userids=123456,654321"
。
然后,我尝试使用以下内容构建列表。“TBD”只是一个占位符。我将在剧本的后面使用从 SQL 查询中检索到的数据填充这些值。
- name: Initiate User List
set_fact:
all_users: []
- name: Add new JSON Objects to List
set_fact:
all_users: "{{ all_users+ [{ 'UserID': '{{ item }}', 'UserType': 'TBD', 'UserName': 'TBD' }] }}"
loop: "{{ userids.split(',') }}"
- name: Debug
debug:
var: all_users
列表已构建,但它跳过了列表中的第一个项目。这是结果输出:
TASK [Initiate User List] *************************************************************************************************************************************************************
ok: [localhost]
TASK [Add new JSON Objects to List] ******************************************************************************************************************************************************
ok: [localhost] => (item=123456)
ok: [localhost] => (item=654321)
TASK [Debug] *****************************************************************************************************************************************************************************
ok: [localhost] => {
"all_users": [
{
"UserID": "654321",
"UserType": "TBD",
"UserName": "TBD"
},
{
"UserID": "{{ item }}",
"UserType": "TBD",
"UserName": "TBD"
}
]
}
我不确定我遗漏了什么。我尝试在循环任务之前执行“set_fact”以先执行 split(),但这没有帮助。我还尝试使用“with_items”代替循环,但没有成功
答案1
不要使用嵌套花括号"{{ ... {{ item }} ... }}"
。正确的语法是
all_users: "{{ all_users+ [{ 'UserID': item,
'UserType': 'TBD',
'UserName': 'TBD' }] }}"
接下来,提交列表会更方便userids
。然后split
过滤器就没有必要了。例如剧本
shell> cat playbook.yml
- hosts: localhost
tasks:
- name: Initiate User List
set_fact:
all_users: []
- name: Add new JSON Objects to List
set_fact:
all_users: "{{ all_users +
[{ 'UserID': item,
'UserType': 'TBD',
'UserName': 'TBD' }] }}"
loop: "{{ userids }}"
- name: Debug
debug:
var: all_users
给出
shell> ansible-playbook -e "userids=['123456','654321']" playbook.yml
...
"all_users": [
{
"UserID": "123456",
"UserName": "TBD",
"UserType": "TBD"
},
{
"UserID": "654321",
"UserName": "TBD",
"UserType": "TBD"
}
]
userids
如果属性UserID
应存储为integer
类型而不是, 请从列表中的项目中删除单引号string
。例如
shell> ansible-playbook -e "userids=[123456,654321]" playbook.yml
给出( 的值周围没有引号UserID
)
"all_users": [
{
"UserID": 123456,
"UserName": "TBD",
"UserType": "TBD"
},
{
"UserID": 654321,
"UserName": "TBD",
"UserType": "TBD"
}
]
然后使用字典创建用户列表。例如,
shell> cat playbook.yml
- hosts: localhost
vars:
my_users:
123456:
name: Alice Admin
type: admin
654321:
name: Bob Business
type: sales
tasks:
- name: Initiate User List
set_fact:
all_users: []
- name: Add new JSON Objects to List
set_fact:
all_users: "{{ all_users +
[{ 'UserID': item,
'UserType': my_users[item].type,
'UserName': my_users[item].name }] }}"
loop: "{{ userids }}"
- name: Debug
debug:
var: all_users
给出
shell> ansible-playbook -e "userids=[123456,654321]" playbook.yml
...
"all_users": [
{
"UserID": 123456,
"UserName": "Alice Admin",
"UserType": "admin"
},
{
"UserID": 654321,
"UserName": "Bob Business",
"UserType": "sales"
}
]