json - How to set templated key name in ansible also on second level? -
assuming have following variable definition in ansible:
users: - username: root password: "changeme" services: - mariadbroot - username: mediawikiadmin password: "changeme" services: - mediawikiadmin - username: hanshuber password: "changeme" services: - mediawikiuser
this data not perfect accessing specific user. want rewrite data different format. rewriting users list, dictionary access user directly. illustrate this, example set only! root password above format:
- name: set root passwd shell: echo "root:{{ item.password }}" | chpasswd with_items: - "{{ users }}" when: "{{ item.username }} == 'root'"
this not nice , gets more complicated when handling services list. purpose want rewrite users list dictionary, access root user directly follows:
- name: set root passwd shell: echo "root:{{ users_byusername['root'] }}" | chpasswd
this lot easier , easier understand.
the following not work:
- name: copy users users_byusername, access them directly username dict instead of list set_fact: { "users_byusername": { "{{ item.username }}": { password: "{{ item.password }}", username: "{{ item.username }}", services: [ "{{ item.services|list}}"] } } } with_items: - "{{ users }}" - name: debugprint users_byusername ignore_errors: true debug: msg: "{{ users_byusername }}"
results in:
task [orderusersvars : debugprint users_byusername] ****************************** ok: [wiki.meinesuperdomain.de] => { "msg": { "{{ item.username }}": { "password": "changeme", "services": [ [ "mediawikiuser" ] ], "username": "hanshuber" } } }
as can see item.username not replaced properly.
on other hand, following work
without first hirachy seems work perfectly:
- name: copy users users_byusername, access them directly username dict instead of list set_fact: { "{{ item.username }}": { password: "{{ item.password }}", username: "{{ item.username }}", services: [ "{{ item.services|list}}"] } } with_items: - "{{ users }}" - name: debugprint root ignore_errors: true debug: msg: "{{ root }}" - name: debugprint mediawikiadmin ignore_errors: true debug: msg: "{{ mediawikiadmin }}"
and results in following:
task [orderusersvars : debugprint root] **************************************** ok: [wiki.meinesuperdomain.de] => { "msg": { "password": "changeme", "services": [ [ "mariadbroot" ] ], "username": "root" } } task [orderusersvars : debugprint mediawikiadmin] ****************************** ok: [wiki.meinesuperdomain.de] => { "msg": { "password": "changeme", "services": [ [ "mediawikiadmin" ] ], "username": "mediawikiadmin" } }
it feels missing tiny little bit of puzzle solve this. maybe can help?
i'm still not sure question about, seems want this:
- debug: msg: "{{ users | selectattr('username', 'equalto', 'root') | map(attribute='password') | first }}"
Comments
Post a Comment