Reputation: 1345
I have a list of security groups that I want to add to some instances using the boto3 client modify_instance_attribute
method.
Using the following code:
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}")
I get the following output:
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
The description of Group for modify_instance_attribute is this:
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) --
It says groups is a list and then says to specify a string. If I try giving it a list
I get an error saying that it wants a string
. This is the error I get if I do that:
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'>
It also says you can add 'at least one security group'.
How can I can assign a list of security group IDs to an ec2 instance using boto3?
Upvotes: 0
Views: 683
Reputation: 270144
You did not show your code for the second error (giving a list), but it appears you are supplying a list as the first element of a list.
For example, if sg_list
is a list of strings, it would appear you were using:
Groups = [sg_list]
This would create a list of a list.
Instead, use:
Groups = sg_list
Upvotes: 1