How to set tags for AWS EC2 instance in boto3

2019-06-07 09:10发布

问题:

I am new to Boto3, and wanted to create a VPC, subnets, and some ec2 instances. The basic architecture is having a VPC, 2 subnets within 2 different availability zones (us-east-1a and b), and applying a security group which allows SSH and ping.

My problem is how to specify additional options for each resources. The Python SDK (unlike how Javadoc works) doesn't show the required arguments and example options, so I'm confused.

How can I specify tags for resources? (e.g. ec2 instance). I need to set name, owner, etc.

instances2 = ec2.create_instances(ImageId='ami-095575c1a372d21db', InstanceType='t2.micro', MaxCount=1, MinCount=1, NetworkInterfaces=[{'SubnetId': subnet2.id, 'DeviceIndex': 0, 'AssociatePublicIpAddress': True, 'Groups': [sec_group.group_id]}])
instances2[0].wait_until_running()
print(instances1[0].id)

回答1:

You need the TagSpecifications argument with 'ResourceType' set to 'instance':

TagSpecifications=[
    {
      'ResourceType': 'instance',
      'Tags': [
        {
          'Key': 'name',
          'Value': 'foobar'
        },
        {
          'Key': 'owner',
          'Value': 'me'
        },
      ]
    },
  ],

It is in the docs but you do need to know what you're looking for...