List comprehension to dynamically populate attribute of object

144 Views Asked by At

What’s the correct way to dynamically populate the list given to the attribute Value? At the moment its its fixed to 3 (0-2), but would be more useful if it was based on INSTANCE_PARAMS[i]["instances"].

I was thinking along the lines of list comprehension but unsure how to write it into the code.

for i in INSTANCE_PARAMS:
output = template.add_output([
    Output(
        str(INSTANCE_PARAMS[i]["name"]).capitalize() + "Ips",
        Description="IPs for " + str(INSTANCE_PARAMS[i]["name"]),
        Value=Join(",", [
            GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "0"), "PrivateIp"), 
            GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "1"), "PrivateIp"), 
            GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "2"), "PrivateIp"), 
        ],
        ),
    )
],
)


INSTANCE_PARAMS = {
    "masters": {
        "name": "master",
        "instances": 3,
        "image_id": "ami-xxxxxxxxxx",
        "instance_type": "t1.micro",
        "security_group_id": [
                              "MasterSG", 
                              "ClusterSG"
                              ], 
    },
}
1

There are 1 best solutions below

0
On BEST ANSWER

Achieved it with the following:

template = Template()
for i in INSTANCE_PARAMS:
    # declared a new list
    tag_value = []
    # got the counter
    for r in range(INSTANCE_PARAMS[i]["instances"]):
        # added each one to the new list
        tag_value.append(GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + str(r)), "PrivateIP")) 
    output = template.add_output([
        Output(
            str(INSTANCE_PARAMS[i]["name"]).capitalize() + "Ips",
            Description="IPs for " + str(INSTANCE_PARAMS[i]["name"]),
            # passed in the list
            Value=Join(",", tag_value,
            ),
        )
    ],
    )
print(template.to_yaml())