Creating an aws target group with ansible

What Im trying to accomplish is to create a network load balancer target group from dynamically generated list of instances.

brokerInstancesList is a list of instance ids. I need to iterate over this list and add them as targets to this target group.

- name: "Create 9092 target group"
  elb_target_group:
    name: "tg-{{ ClusterName }}"
    protocol: tcp
    port: 9092
    vpc_id: "{{ VPCID }}"
    targets:
      - Id: "{{ item }}"
        Port: 9092
    state: present
  loop: "{{ brokerInstancesList }}"

The issue with my attempt above is that only the last entry in the brokerInstancesList is kept. Something like the below is what I need.

- name: "Create 9092 target group"
  elb_target_group:
    name: "tg-{{ ClusterName }}"
    protocol: tcp
    port: 9092
    vpc_id: "{{ VPCID }}"
    targets:
      {% for item in {{ brokerInstancesList }} -%}
      - Id: "{{ apple }}"
        Port: 9092
      {%- endfor %}
    state: present

The elb_target_group interface maps very easily to the AWS API, but it’s a bit clunky to use.

`

targets: “{{ brokerInstancesList | map(‘json_query’, ‘{Id: @}’) | map(‘combine’, { ‘Port’: 9092 }) | list }}”

`

(It might be possible to do this in fewer operations with a more complex JMESPath expression, but this way works and is almost readable.)

I suggest for readability that you build a list using set_fact:, then pass the list to the targets: parameter.

Regards, K.