Felixrobin antony
Felixrobin antony

Reputation: 11

Update Security Group tags using boto3

I am trying the update security group tags using boto3. I have several security groups to update. This script filters based on a common tag and then adds other tags. I am using the following script:

import boto3
import sys

ec2 = boto3.client('ec2')

sgs = ec2.describe_security_groups(Filters=[{'Name': 'tag:type', 'Values': ['test']}])

ids = []

for reservation in sgs['SecurityGroups']:
        ids.append(reservation['GroupName'])

print ("Changing tags for %d sgs" % len(ids))

ec2.create_tags(
    Resources=ids,
    Tags=[
        {
            'Key': 'bu',
            'Value': 'HR'
        },
        {
            'Key': 'product',
            'Value': 'shared'
        },
                {
            'Key': 'environment',
            'Value': 'dev'
        },
        {
            'Key': 'acc-no',
            'Value': '883356'
        },
        {
            'Key': 'type',
            'Value': 'client'
        },  
        {
            'Key': 'app-id',
            'Value': 'ae1'
        },  
        {
            'Key': 'name',
            'Value': 'all-enterprise'
        },  
        {
            'Key': 'owner',
            'Value': 'enterprise'
        },
        {
            'Key': 'role',
            'Value': 'enterprise'
        }
                                                              
    ]
)

I get the following error:

Changing tags for 1 sgs
Traceback (most recent call last):
  File "C:\Users\charl\scv\boto\sgtest.py", line 18, in <module>
    ec2.create_tags(
  File "C:\python390\lib\site-packages\botocore\client.py", line 391, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\python390\lib\site-packages\botocore\client.py", line 719, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidID) when calling the CreateTags operation: The ID 'packersg' is not valid

Can you tell me what I am doing wrong please?

Upvotes: 0

Views: 769

Answers (1)

Kaustubh Khavnekar
Kaustubh Khavnekar

Reputation: 2923

for reservation in sgs['SecurityGroups']:
        ids.append(reservation['GroupName'])

This should be changed to

for reservation in sgs['SecurityGroups']:
        ids.append(reservation['GroupIds'])

This is because the create_tags function expects Security Group IDs (IDs for the security groups are in the format sg-xxxxxxxx) and not Security Group names.

Upvotes: 2

Related Questions