0

I'm attempting to transform a 1d list of AWS EC2 IDs into a list of dictionaries suitable for usage as the targets param to the Ansible elb_target_group module.

Sample input:

TASK [debug]
ok: [localhost] => {
    "instance_ids": [
        "i-1111",
        "i-2222",
        "i-3333"
    ]
}

Desired output:

TASK [debug]
ok: [localhost] => {
    "targets": [
        {"Id": "i-1111", "Port": 6443},
        {"Id": "i-2222", "Port": 6443},
        {"Id": "i-3333", "Port": 6443},
    ]
}

What I've tried: a json_query / JMESPath expression which confusingly returns null values:

---

- name: test
  hosts: localhost
  connection: local
  vars:
    instance_ids:
      - i-1111
      - i-2222
      - i-3333
    keys_list:
      - Id
      - Port
  tasks:
    - debug: var=instance_ids
    - debug:
        msg: "{{ instance_ids | zip_longest([6443], fillvalue=6443) | list }}" # Halfway there...
    - debug:
        msg: "{{ instance_ids | zip_longest([6443], fillvalue=6443) | list | map('json_query', '{Id: [0], Port: [1]}') | list }}"

Output:

TASK [debug]
ok: [localhost] => {
    "msg": [
        [
            "i-1111",
            6443
        ],
        [
            "i-2222",
            6443
        ],
        [
            "i-3333",
            6443
        ]
    ]
}

TASK [debug]
ok: [localhost] => {
    "msg": [
        {
            "Id": null,
            "Port": null
        },
        {
            "Id": null,
            "Port": null
        },
        {
            "Id": null,
            "Port": null
        }
    ]
}

How should I adjust the '{Id: [0], Port: [1]}' part ?

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235

1 Answers1

0

Stumbled my way to a working solution with json_query and a JMESPath int literal:

"{{ instance_ids | json_query('[*].{Id: @, Port: `6443`}') }}"

Example:

- name: test
  hosts: localhost
  connection: local
  vars:
    instance_ids:
      - i-1111
      - i-2222
      - i-3333
  tasks:
    - debug:
        msg: "{{ instance_ids | json_query('[*].{Id: @, Port: `6443`}') }}"

Output:

TASK [debug]
ok: [localhost] => {
    "msg": [
        {
            "Id": "i-1111",
            "Port": 6443
        },
        {
            "Id": "i-2222",
            "Port": 6443
        },
        {
            "Id": "i-3333",
            "Port": 6443
        }
    ]
}
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235