英文:
Loop with conditional in ansible
问题
我有一个Ansible中的Keycloak领域模板,想要从该模板加载值数组。
我的模板文件大致如下:
{
// 这里是一些 JSON
"roles": {
"client": {
"demo-app": [
{
"name": "Administrator",
"composite": true,
"composites": {
"client": {
"realm-management": [
"view-users",
"manage-identity-providers",
"query-clients",
"query-users"
]
}
},
"clientRole": true
},
{
"name": "Developer",
"composite": false,
"clientRole": true
},
{
"name": "Operator",
"composite": false,
"clientRole": true
}
]
}
}
}
现在,我想从模板中读取realm-management
数组的值。为此,我在Ansible中编写了以下任务:
- name: 'Ensure realm-management roles are added to demo-app "Administrator" role'
debug:
msg: "{{ item }}"
loop: "{{ lookup('template', 'realm/DemoRealm-realm.json.j2').roles.client['demo-app'] | subelements('composites.client.realm-management') }}"
when:
- item.name == 'Administrator'
- item.composite == true
- item.composites is defined
我的期望是打印realm-management
数组中的值。但是,我添加的任务也在循环遍历 Developer
和 Operator
对象,忽略了条件,并且由于它们没有composites
键,任务失败了。我尝试了很多方法,但没有一个有效。请建议我该怎么做。
英文:
I have a keycloak realm template in ansible and want to load array of values from that template.
My template file looks something like this:
{
// Some json here
"roles": {
"client": {
"demo-app": [
{
"name": "Administrator",
"composite": true,
"composites": {
"client": {
"realm-management": [
"view-users",
"manage-identity-providers",
"query-clients",
"query-users",
]
}
},
"clientRole": true,
},
{
"name": "Developer",
"composite": false,
"clientRole": true,
},
{
"name": "Operator",
"composite": false,
"clientRole": true,
}
],
}
}
}
Now I want to read realm-management array values from the template. For that, I have written task in ansible. It goes as below:
- name: 'Ensure realm-management roles are added to demo-app "Administrator" role'
debug:
msg: "{{ item }}"
loop: "{{ lookup('template', 'realm/DemoRealm-realm.json.j2').roles.client['demo-app'] }} | subelements('composites.client.realm-management') }}"
when:
- item.name == 'Administrator'
- item.composite == true
- item.composites is defined
My expectation is to print values from realm-management
array. But the task I have added is also looping through Developer
and Operator
objects ignoring conditional and as they don't have composites
key in them, task is failing. I have tried numerous approaches but none worked. Please suggest me what to do.
答案1
得分: 1
你可以使用 json_query
来验证对象属性,如下所示:
loop: "{{ lookup('template', 'realm/DemoRealm-realm.json.j2').roles.client['demo-app'] | json_query('[?name==`Administrator` && composite==`true` && composites]') }}"
when: item.composites is defined
英文:
You can use json_query
to validate object properties like so:
loop: "{{ lookup('template', 'realm/DemoRealm-realm.json.j2').roles.client['demo-app'] | json_query('[?name==`Administrator` && composite==`true` && composites]') }}"
when: item.composites is defined"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论