I have several roles that create various numbers of security groups.
I have another role that creates an instance.
I want the second role to be re-usable, and to be usable with the roles that create security groups.
So I want the second role to attach a list of security groups to the instance it creates.
The role that creates security groups thus has to be able to somehow return a list of security groups.
My role creates security groups and registers eg sg_1, sg_2, sg_3 and so on.
How can I create a list variable? Something like sgs: [sg_1.group_id, sg_2.group_id, sg_3.group_id] ?
The variable cannot be created inside the role that creates the instance, as that would bind it too closely to the role that creates the security groups. It has to be created inside the role that creates the security groups.
Further to this: I have no problem collecting the various groups into a list using ec2_group_facts.
What I can’t figure out how to do is get the group IDs from that list of group facts into a single variable that can be used in the ec2 module, which takes a list of group IDs in its “group_id” attribute.
Sorry - I’ve done it again; figured out a solution to my own problem AFTER posting a question.
Anyway, the answer is the set_facts: task. This lets you build a variable from other variables.
In the role that creates security groups, the last task is a set_fact: task that builds a list of the security group IDs. That fact (variable) is then available to the role that creates the instance, which can use it in the instance’s group_id attribute.
For an instance that I had already created, I found a workaround by googling. The workaround was to use set_fact: after creating the security groups to create a space-delimited string of group IDs. The playbook itself (not the server role) then has an extra task, after the instance has already been built, of running an AWS CLI command to modify the instance (“aws ec2 modify-instance-attributes …”)