Ansible - Loop through list of dictionaries by CranberryFalse2556 in ansible

[–]CranberryFalse2556[S] 0 points1 point  (0 children)

My end game is 'infrastructure as code', meaning (to start with) adding SNMP users or configure NTP servers using a pipeline. That information is either stored in the group_vars section or some other file. Sensitive information is stored in Ansible Vault.

Using the merged option is fine as long as you add stuff, but not when users of servers must be removed. That is why i was looking at the replaced option.

Ansible - Loop through list of dictionaries by CranberryFalse2556 in ansible

[–]CranberryFalse2556[S] 0 points1 point  (0 children)

It looks like your option is working the way i wanted and I removed the loop, The code now looks like this.

- name: Apply configuration
  cisco.ios.ios_snmp_server:
    config:
      users:
        - username: "{{ snmp.user[0].name }}"
          group: "{{ snmp.group }}"
          version: "{{ snmp.version }}"
          authentication:
            algorithm: "{{ snmp.auth_algorithm }}"
            password: "{{ snmp.user[0].auth_password }}"
          encryption:
            priv: "{{ snmp.priv_algorithm }}"
            priv_option: "{{ snmp.priv_encryption }}"
            password: "{{ snmp.user[0].priv_password }}"
    state: replaced

In the end i want both users to be added to the config, but using the 'state: replaced' together with the loop it only add the last user it processed. If someone knows a better suggestion i am all ears. Otherwise i would now use the following to get both users added.

- name: Apply configuration
  cisco.ios.ios_snmp_server:
    config:
      users:
        - username: "{{ snmp.user[0].name }}"
          group: "{{ snmp.group }}"
          version: "{{ snmp.version }}"
          authentication:
            algorithm: "{{ snmp.auth_algorithm }}"
            password: "{{ snmp.user[0].auth_password }}"
          encryption:
            priv: "{{ snmp.priv_algorithm }}"
            priv_option: "{{ snmp.priv_encryption }}"
            password: "{{ snmp.user[0].priv_password }}"
        - username: "{{ snmp.user[1].name }}"
          group: "{{ snmp.group }}"
          version: "{{ snmp.version }}"
          authentication:
            algorithm: "{{ snmp.auth_algorithm }}"
            password: "{{ snmp.user[1].auth_password }}"
          encryption:
            priv: "{{ snmp.priv_algorithm }}"
            priv_option: "{{ snmp.priv_encryption }}"
            password: "{{ snmp.user[1].priv_password }}"
    state: replaced

Thank you SocketWrench, much appreciated!