bluethundr
bluethundr

Reputation: 1335

Unable to add tag to instance python

I'm creating an ec2 instance in python boto3 with this code:

image_id = input("Enter the image id: ")
max_count = input("Enter the number of instances you want: ")
instance_type = input("Enter the instance type: ")
key_name = input("Enter the key name you want to use: ")
name_tag = input("Enter the host name: ")
instance = ec2_resource.create_instances(
    ImageId=image_id,
    MinCount=1,
    MaxCount=max_count,
    InstanceType=instance_type,
    KeyName=key_name
)

But when I try to apply a name tag with this code:

instance.add_tag('Name', name_tag)

I get an error that says:

Traceback (most recent call last):
  File ".\aws_create_ec2_simple.py", line 134, in <module>
    main()
  File ".\aws_create_ec2_simple.py", line 130, in main
    create_instances()
  File ".\aws_create_ec2_simple.py", line 125, in create_instances
    instance.add_tag('Name', name_tag)
AttributeError: 'list' object has no attribute 'add_tag'

How can I do this correctly?

Upvotes: 0

Views: 85

Answers (1)

jarmod
jarmod

Reputation: 78713

The boto3 Instance class does not have an add_tags() method.

You should use create_tags(). For example:

instances = ec2_resource.create_instances(
    ImageId=image_id,
    MinCount=1,
    MaxCount=max_count,
    InstanceType=instance_type,
    KeyName=key_name
)

for instance in instances:
    tag = instance.create_tags(
        Tags=[
            {
                'Key': 'Environment',
                'Value': 'QA'
            },
            {
                'Key': 'Owner',
                'Value': 'Jason'
            }
        ]
    )

Also, note that create_instances() returns a list of instances, not a single instance.

Upvotes: 1

Related Questions