【问题标题】:Adding a list of security groups using Boto3 gives error "The security group does not exist"使用 Boto3 添加安全组列表会出现错误“安全组不存在”
【发布时间】: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


    【解决方案1】:

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

    例如,如果sg_list 是一个字符串列表,那么看起来您正在使用:

    Groups = [sg_list]
    

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

    改为:

    Groups = sg_list
    

    【讨论】:

    • 谢谢。那行得通!仅供参考,我已经添加了稍后将列表提供给帖子的错误。如果你重新加载你会看到它。使用您的解决方案有效!再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 2021-08-08
    • 2020-02-06
    • 2018-10-13
    • 2017-03-08
    • 2021-05-29
    • 2017-11-26
    • 2017-04-29
    相关资源
    最近更新 更多