Creating name of inventory group from a variable

I have a task where I am updating a line in a file with a comma separated list of inventory hosts, this works for the hard coded case:

  • name: Set host list
    lineinfile: dest=/home/project/pom.xml regexp=‘.*’ line='{{ groups.tag_Type_targettype | intersect(‘groups.key_mykey) | join(’, ‘) }}’

key_mykey is a group generated from ec2 properties in a dynamic inventory using:

  • name: Create groups based on ec2 access key
    group_by: key=key_{{ ec2_key_name }}

The issue I’m facing is that I need to be able to generate the intersection ‘key_’ from a variable so that I can generate different intersections at playbook runtime.

I have tried different ways to use a variable for , most give a runtime error, the following does not, but it also generates an empty hosts list.

vars:
ec2keyname: mykey

intersect(‘groups.key_’ + ec2keyname)

Is there a way to use a variable in the intersection groups name?

Andy

The solution turned out to be simply to use variable bracket notation instead of dot notation, the value in the brackets can be formed from the concatenation of a string and a variable

line=‘{{ groups.tag_Type_syncgateway | intersect(groups[key_’ + ec2keyname]) | join(‘,’) }}’