Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cognitiaclaeves/5ac8698c6bfb57a86d12a7458dc569ea to your computer and use it in GitHub Desktop.
Save cognitiaclaeves/5ac8698c6bfb57a86d12a7458dc569ea to your computer and use it in GitHub Desktop.
How to get contents of generator do_map in ansible?
Would like to be able to check contents of json.items.*.labels[*] and json.items.*.labels[*].value from json below:
I'm unsure how to get the contents of the generator from ansible / jinja2.
- name: Test json
debug: "msg={{ json.items|map(attribute='metadata.labels') }}"
$ ansible-playbook -i inv/dev k8s-redis.yml --extra-vars "@test-var.json"
Gives me:
TASK [k8s-redis : Test json] ***************************************************
ok: [aus-ared-dev-00] => {
"msg": "<generator object do_map at 0x224de60>"
}
This is the json:
{"json": {
"apiVersion": "v1",
"items": [
{
"metadata": {
"creationTimestamp": "2016-03-22T18:18:48Z",
"labels": {
"kubernetes.io/hostname": "aus-akn-dev-00.q2dc.local"
},
"name": "aus-akn-dev-00.q2dc.local",
"resourceVersion": "557645",
"selfLink": "/api/v1/nodes/aus-akn-dev-00.q2dc.local",
"uid": "85b7ae17-f05a-11e5-b8a3-005056bc5b54"
}
},
{
"metadata": {
"creationTimestamp": "2016-03-23T19:49:22Z",
"labels": {
"kubernetes.io/hostname": "aus-akn-dev-01.q2dc.local"
},
"name": "aus-akn-dev-01.q2dc.local",
"resourceVersion": "557644",
"selfLink": "/api/v1/nodes/aus-akn-dev-01.q2dc.local",
"uid": "57306016-f130-11e5-975f-005056bc5b54"
}
}
]
}}
@cognitiaclaeves
Copy link
Author

This ended up being the solution:
set_fact: "node_label_dict={{ k8s_nodes.json['items']|map(attribute='metadata.labels')|list }}"

Turns out that .item is a reserved keyword. Jinja2 defaulted to item() rather than ['item']:

https://asciinema.org/a/66i1f38o7b5mde7eym13vjt48

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment