How to interate through this dictionary? If vrf is default than print proc name. If vrf is other than defaul than print proc name and vrf name
proc-vrf: [{'proc': 'T1', 'vrf': 'default'}, {'proc': 'T2', 'vrf': 'vrf_T2'},, {'proc': 'T3', 'vrf': 'default'}, {'proc': 'T3', 'vrf': 'vrf_T3'}]
I tried following:
- name: Display output...
debug:
msg: "{{ item.key }} - {{ item.value }}"
loop: "{{ proc-vrf | dict2items }}"
I am getting following error:
ERROR! 'item' is undefined
CodePudding user response:
Thank you for the additional information, the question looks better.
As in this case the variable is a list of dictionaries, replace the loop: with
- name: Display output...
debug:
msg: "{{ item.proc }} - {{ item.vrf }}"
with_items: "{{ proc-vrf }}"
CodePudding user response:
After addressing the variable name because of
ERROR! Invalid variable name in vars specified for Play: 'proc-vrf' is not a valid variable name
and its content
diff <( echo 'proc-vrf: [{'proc': 'T1', 'vrf': 'default'}, {'proc': 'T2', 'vrf': 'vrf_T2'},, {'proc': 'T3', 'vrf': 'default'}, {'proc': 'T3', 'vrf': 'vrf_T3'}]' ) <( echo 'proc_vrf: [{'proc': 'T1', 'vrf': 'default'}, {'proc': 'T2', 'vrf': 'vrf_T2'}, {'proc': 'T3', 'vrf': 'default'}, {'proc': 'T3', 'vrf': 'vrf_T3'}]' )
1c1
< proc-vrf: [{proc: T1, vrf: default}, {proc: T2, vrf: vrf_T2},, {proc: T3, vrf: default}, {proc: T3, vrf: vrf_T3}]
---
> proc_vrf: [{proc: T1, vrf: default}, {proc: T2, vrf: vrf_T2}, {proc: T3, vrf: default}, {proc: T3, vrf: vrf_T3}]
a sample playbook like
---
- hosts: localhost
become: false
gather_facts: false
vars:
proc_vrf: [{'proc': 'T1', 'vrf': 'default'}, {'proc': 'T2', 'vrf': 'vrf_T2'}, {'proc': 'T3', 'vrf': 'default'}, {'proc': 'T3', 'vrf': 'vrf_T3'}]
tasks:
- name: Display output...
debug:
msg: "{{ item.proc }} - {{ item.vrf }}"
loop: "{{ proc_vrf }}"
will result into an output of
TASK [Display output...] ****************************************
ok: [localhost] => (item={u'proc': u'T1', u'vrf': u'default'}) =>
msg: T1 - default
ok: [localhost] => (item={u'proc': u'T2', u'vrf': u'vrf_T2'}) =>
msg: T2 - vrf_T2
ok: [localhost] => (item={u'proc': u'T3', u'vrf': u'default'}) =>
msg: T3 - default
ok: [localhost] => (item={u'proc': u'T3', u'vrf': u'vrf_T3'}) =>
msg: T3 - vrf_T3
Further Documentation
- Creating valid variable names
Not all strings are valid Ansible variable names. A variable name can only include letters, numbers, and underscores.
CodePudding user response:
- name: Display output... debug: msg: "{{ item.proc }} - {{ item.vrf }}" loop: "{{ proc_vrf }}"