【问题标题】:Create and Filter EC2 with Tags使用标签创建和过滤 EC2
【发布时间】:2020-03-27 08:38:59
【问题描述】:

尝试使用 Python 3.6 在 AWS 中创建一个 Lambda 函数,该函数会创建一个在特定时间段后终止的 EC2 实例。由于我对此仍然很陌生,因此我选择在终止实例时使用“标签”作为过滤器。

但是,我无法找到一种在生成实例时将标签添加到实例的方法。

我创建EC2的代码如下

import os
import boto3

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

ec2 = boto3.resource('ec2')


def lambda_handler(event, context):

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

    print("New instance created...")

环境变量手动填写

我还有一个终止函数,它应该用标签过滤掉上面python脚本创建的EC2并终止它们

import os
import boto3

def lambda_handler(event, context):
    ec2 = boto3.resource('ec2')
    instances = ec2.instance.filter(Filters=[{"Name" :"tag:webserver", "Values":[delete] }])
    deleteInstances = [instance.id for instance in instances]
    for i in deleteInstances:
        terminateInstances = ec2.instances.terminate(i)
        print(terminateInstances)

    print("Terminating instances...")

没有运气找到简单的方法。

【问题讨论】:

  • 您在创建新实例时没有标记它
  • 之前我说过我不确定如何在创建时标记它们。

标签: python-3.x amazon-ec2 aws-lambda boto3


【解决方案1】:

boto3 create_instances api 有参数 TagInstancesdocumentation here

TagSpecifications 是一个 python 列表 - 它包括在启动期间应用于资源的标签。指定的标签应用于在启动期间创建的所有实例或卷。

TagSpecifications=[
        {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        },
    ],

【讨论】:

    【解决方案2】:

    您可以轻松地为您的请求添加附加参数,例如:

    def lambda_handler(event, context):
    
    instance = ec2.create_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        SubnetId=SUBNET_ID,
        MaxCount=1,
        MinCount=1,
        TagSpecifications=[
          {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'TAG_KEY',
                    'Value': 'TAG_VALUE'
                }
            ]
          }
        ]
    )
    

    【讨论】:

    • 我将此添加到我的代码中并进行了一些测试,它遇到了错误“您无权执行此操作”“客户端错误”我检查了 IAM 角色,它有json { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "ec2:DescribeInstances", "ec2:RunInstances", "ec2:DescribeInstanceStatus" ], "Resource": "*" } 我我不确定是什么问题
    • 我认为您可以向您的 IAM 角色添加权限“ec2:CreateTags”
    • 我也添加了它并给了它所有资源,但是当我尝试它时,同样的错误我需要创建一个新功能还是应该自动更新角色
    • 尝试使用"ec2:*"进行测试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多