Is it possible to use a variable as a key in a key:value pair?

I’m trying to populate a file based on some default vars and I’m wondering if the following is possible (and if so, how?) because I’ve been unable to get it to work.

given:

ansible 2.3.0.0

python version = 2.7.13 (default, May 10 2017, 20:04:28) [GCC 6.3.1 20161221 (Red Hat 6.3.1-1)]

…/defaults/main.yml

hosts:

  • {name: “{{inventory_hostname}}”, ‘{{ansible_ec2_placement_region}}’: true, “{{ansible_ec2_placement_availability_zone}}”: true, test: true, group1: true}

host_groups:

  • name: ‘{{ansible_ec2_placement_region}}’

  • name: ‘{{ansible_ec2_placement_availability_zone}}’

  • name: ‘group1’
  • name: ‘test’

…/templates/groups.cfg

{% for group in host_groups %}

group_name {{group.name}};

members {{hosts|selectattr(group.name, ‘defined’)|map(attribute=‘name’)|join(‘,’)}}

{% endfor %}

…/tasks/groups.yml

  • name: Generate groups
    become: true
    template:
    src: groups.cfg
    dest: “{{object_dir}}/groups.cfg”
    mode: 0644
    with_items:
  • “{{host_groups}}”

I would like for the template to be converted to:

group_name test;
members my.host.name;

group_name us-west-2;
members my.host.name;

group_name us-west-2a
members my.host.name;

group_name group1;
members my.host.name;

but what I get is: