boto3: create_tags on an ec2 instance gives TypeError

14,873

First, you CANNOT use boto3.resource("ec2") like that. The boto3.resource is a high level layer that associate with particular resources. Thus following already return the particular instances resources. The collection document always looks like this

# resource will inherit associate instances/services resource.
tag = resource.create_tags(
          DryRun=True|False,
          Tags=[
              {
                  'Key': 'string',
                  'Value': 'string'
              },
          ]
      )

So in your code,you JUST reference it directly on the resource collection :

for instance in instances:
  instance.create_tags(Tags={'TagName': 'TagValue'}) 

Next, is the tag format, follow the documentation. You get the filter format correct, but not the create tag dict

response = client.create_tags(
    DryRun=True|False,
    Resources=[
        'string',
    ],
    Tags=[
        {
            'Key': 'string',
            'Value': 'string'
        },
    ]
)

On the other hand, boto3.client()are low level client that require an explicit resources ID .

import boto3
ec2 = boto3.client("ec2")
reservations =   ec2.describe_instances(
    Filters=[{'Name': 'instance-state-name', 
              'Values': ['running']}])["Reservations"]
mytags = [{
    "Key" : "TagName", 
       "Value" : "TagValue"
    }, 
    {
       "Key" : "APP",
       "Value" : "webapp"
    },
    {
       "Key" : "Team", 
       "Value" : "xteam"
    }]
for reservation in reservations :
    for each_instance in reservation["Instances"]:
        ec2.create_tags(
            Resources = [each_instance["InstanceId"] ],
            Tags= mytags
           )

(update) A reason to use resources is code reuse for universal object, i.e., following wrapper let you create tags for any resources.

def make_resource_tag(resource , tags_dictionary):
   response = resource.create_tags(
        Tags = tags_dictionary)
Share:
14,873
Admin
Author by

Admin

Updated on August 22, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to add a tag to existing ec2 instances using create_tags.

    ec2 = boto3.resource('ec2', region_name=region)
    instances =   ec2.instances.filter(Filters=[{'Name': 'instance-state-name',
                                                 'Values': ['running']}])
    for instance in instances:
      ec2.create_tags([instance.id], {"TagName": "TagValue"})
    

    This is giving me this error:

    TypeError: create_tags() takes exactly 1 argument (3 given)