0

动态填充赋予属性值的列表的正确方法是什么?目前它固定为 3 (0-2),但如果它基于 INSTANCE_PARAMS[i]["instances"] 会更有用。

我在考虑列表理解的思路,但不确定如何将其写入代码。

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"
                              ], 
    },
}
4

1 回答 1

0

通过以下方式实现了它:

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())
于 2019-08-22T15:26:27.240 回答