使用 Boto3 添加安全组列表会产生错误"The security group does not exist"



我有一个安全组列表,我想使用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) --

它说groups是一个列表,然后说指定一个字符串。如果我尝试给它一个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实例?

您没有显示第二个错误的代码(给出一个列表(,但似乎您提供了一个列表作为列表的第一个元素。

例如,如果sg_list是一个字符串列表,则显示您使用的是:

Groups = [sg_list]

这将创建一个列表的列表。

相反,使用:

Groups = sg_list

相关内容

最新更新