Changing the dictionary key names but not values of items in a loop

JethCalark
Mon, 22 Jan 2024 19:18:24 +0000
Get Help

I have a role for Adguard Home with a task to add DHCP reservations. That task requires a list variable where each item has the same dictionary keys:

- name: Add static leases on AdGuard Home
  ansible.builtin.uri:
    method: POST
    return_content: true
    url: 'http://192.168.1.1/control/dhcp/add_static_lease'
    body_format: json
    body: |
      {
        "mac": "{{ item.mac }}",
        "ip": "{{ item.ip }}",
        "hostname": "{{ item.hostname }}"
      }
    url_username: "{{ adguard_home_user.name }}"
    url_password: "{{ adguard_home_user.password }}"
    force_basic_auth: true
  loop: "{{ static_leases }}"

This information is already stored in another list variable with different names for the dictionary keys while being used by other roles/playbooks.

dhcp_reservations:
  - mac_address: 52:54:00:1a:2b:3c
    number: 192.168.1.11
    name: laptop
  - mac_address: 52:54:00:4d:5e:6f
    number: 192.168.1.12
    name: desktop

I wish I could just put static_leases: "{{ dhcp_reservations }}" in the host’s variables and call it a day, but that won’t work obviously.
I’m not at liberty to alter or edit one of these roles, so I have at least one case where I can’t change the task that uses these variables to fit the dictionary keys being used already.

How can I/should I transform the name of these dictionary keys on each item in the list while preserving the value? Alternatively, how can I add a new dictionary key with the needed name and the same value?

# Example desired outcome
dhcp_reservations:
  - mac: 52:54:00:1a:2b:3c
    ip: 192.168.1.11
    hostnamename: laptop
  - mac: 52:54:00:4d:5e:6f
    ip: 192.168.1.12
    hostname: desktop

# Example alternative desired outcome
dhcp_reservations:
  - mac: 52:54:00:1a:2b:3c
    ip: 192.168.1.11
    hostnamename: laptop
    mac_address: 52:54:00:1a:2b:3c
    number: 192.168.1.11
    name: laptop
  - mac: 52:54:00:4d:5e:6f
    ip: 192.168.1.12
    hostname: desktop
    mac_address: 52:54:00:4d:5e:6f
    number: 192.168.1.12
    name: desktop

I tried going through Ansible documentation, filters, etc, but couldn’t seem to find a solution that worked with dictionary keys on list items.
I apologize for not giving more concrete examples of what I tried, but I haven’t touched it over the weekend, and it became all a blur.
Can’t shake the feeling that the answer is simple, and I’m just overlooking something obvious.
I appreciate any solutions people might have.

10 posts - 4 participants