【发布时间】:2020-02-21 04:26:53
【问题描述】:
我有一个安全组列表,我想使用 boto3 客户端 modify_instance_attribute 方法添加到某些实例中。
使用以下代码:
def attach_sg_list(ec2_client, sg_list, instance_id):
sg_list = str(sg_list).replace(' ', '').replace('[','').replace(']','').replace('\'','')
print(f"SG List: {sg_list}")
try:
attach_sg_response = ec2_client.modify_instance_attribute(
InstanceId=instance_id,
Groups=[
sg_list,
]
)
except Exception as e:
print(f"An error has occurred: {e}")
我得到以下输出:
SG List: sg-0d0ddf3117d23cadb,sg-0e4b5fc1d40185fc3,sg-031ac185d029cd5fd,sg-0afa867f9029bb468,sg-2cad407c
An error has occurred: An error occurred (InvalidGroup.NotFound) when calling the ModifyInstanceAttribute operation: The security group 'sg-0d0ddf3117d23cadb,sg-0e4b5fc1d40185fc3,sg-031ac185d029cd5fd,sg-0afa867f9029bb468,sg-2cad407c' does not exist
modify_instance_attribute 的 Group 描述如下:
Groups (list) --
[EC2-VPC] Changes the security groups of the instance. You must specify at least one security group, even if it's just the default security group for the VPC. You must specify the security group ID, not the security group name.
(string) --
它说组是一个列表,然后说指定一个字符串。如果我尝试给它一个list,我会收到一个错误,说它想要一个string。如果我这样做,这是我得到的错误:
Parameter validation failed:
Invalid type for parameter Groups[0], value: [' sg-031ac185d029cd5fd', ' sg-0d0ddf3117d23cadb', ' sg-05ef09508245e56bc', ' sg-0e4b5fc1d40185fc3', ' sg-2cad407c'], type: <class 'list'>, valid types: <class 'str'>
它还说您可以添加“至少一个安全组”。
如何使用 boto3 将安全组 ID 列表分配给 ec2 实例?
【问题讨论】:
标签: python amazon-web-services amazon-ec2 boto3