简体   繁体   English

如何在 boto3 中为 AWS EC2 实例设置标签

[英]How to set tags for AWS EC2 instance in boto3

I am new to Boto3 , and wanted to create a VPC, subnets, and some ec2 instances.我是Boto3 ,想创建一个 VPC、子网和一些 ec2 实例。 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 .基本架构是拥有一个 VPC、2 个不同可用区(us-east-1a 和 b)内的 2 个子网,并应用一个允许SSHping的安全组。

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. Python SDK(与Javadoc工作方式不同)没有显示所需的参数和示例选项,所以我很困惑。

How can I specify tags for resources?如何为资源指定tags (eg ec2 instance). (例如 ec2 实例)。 I need to set name , owner , etc.我需要设置nameowner等。

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)

You need the TagSpecifications argument with 'ResourceType' set to 'instance' :您需要将'ResourceType'设置为'instance'TagSpecifications参数:

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...它在文档中,但您确实需要知道您在寻找什么......

Following works for me with python 3.7 and boto3 1.12.39以下适用于 python 3.7 和 boto3 1.12.39

Reference - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html?highlight=create_instances#EC2.ServiceResource.create_instances参考 - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html?highlight=create_instances#EC2.ServiceResource.create_instances

    AMI = os.environ['AMI']
    INSTANCE_TYPE = os.environ['INSTANCE_TYPE']
    KEY_NAME = os.environ['KEY_NAME']
    SUBNET_ID = os.environ['SUBNET_ID']    

    TAG_SPEC = [
        {
        "ResourceType":"instance",
        "Tags": [
                {
                    "Key": "Name",
                    "Value": "EC2_INSTANCE_TEST_AUTOGENERATED"
                }
            ]
    }
    ]

    ec2 = boto3.resource('ec2')

    instance = ec2.create_instances(
        ImageId = AMI,
        InstanceType = INSTANCE_TYPE,
        KeyName = KEY_NAME,
        SubnetId = SUBNET_ID,
        TagSpecifications = TAG_SPEC,
        MaxCount = 1,
        MinCount = 1
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM