【问题标题】:Lambda function Python 3.6 to shut off EC2 instance with specific tagsLambda 函数 Python 3.6 使用特定标签关闭 EC2 实例
【发布时间】:2021-05-08 02:49:03
【问题描述】:

这是我目前所拥有的。我只需要帮助创建 if 语句/for 循环来比较标签。我的标签是:键:'名称',值:'TestServer'。谢谢!

import boto3

ec2 = boto3.resource('ec2')
#tag = ec2.Tag('i-018b3ee8dd8b9fed3','Name','TestServer1')

region = 'us-east-1'
instances = ['i-018b3ee8dd8b9fes4']
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    
    ec2.stop_instances(InstanceIds=instances )
    print('stopped your instances: ' + str(instances) +str(tag))

【问题讨论】:

  • 仅供参考,我创建了一个Simple EC2 Stopinator in Lambda - DEV Community,它可以根据标签停止/终止实例。随意使用代码。
  • 我试过了,但它似乎不起作用,你能把它贴在下面吗:)。我尝试创建一个 JSON 策略,该策略仅指定允许基于某些标签停止或启动,但我需要更具体地过滤掉我不想要的标签等标签。
  • import boto3 region = 'us-east-1' ec2 = boto3.client('ec2') instances = ['i-018b3ee8dd8b9fes5'] def lambda_handler(event,context): ec2.stop_instances( InstanceIds=instances)
  • 这就是我所拥有的并且它有效。我尝试了许多不同的过滤器变体,按键排序等。似乎没有任何效果。我还是个新手,所以想学习,但是当正常工作的代码无法编译时我会感到不安:(

标签: python amazon-web-services amazon-ec2 aws-lambda


【解决方案1】:

根据您的标签要求准备过滤器并运行查询,最终遍历资源。

import boto3
# Connect to EC2
ec2 = boto3.client('ec2', region_name='us-east-1')
 

def lambda_handler(event,context):
    custom_filter = [{
        'Name':'tag:Name', 
        'Values': ['TestServer']}]
    instances_to_stop = []
    running_instances = ec2.describe_instances(Filters=custom_filter)
    for reservation in running_instances.get('Reservations'):
        for instance in reservation.get('Instances'):
            instances_to_stop.append(instance.get('InstanceId'))
    print(f'Stopping following instance Ids : {instances_to_stop}')
    response = ec2.stop_instances(InstanceIds=instances_to_stop)
    print(response)

Response:

{
  "StoppingInstances": [
    {
      "CurrentState": {
        "Code": 64,
        "Name": "stopping"
      },
      "InstanceId": "i-011ac4a33afdsadasd",
      "PreviousState": {
        "Code": 16,
        "Name": "running"
      }
    }
  ],
  "ResponseMetadata": {
    "RequestId": "35a3ab",
      "date": "Thu, 04 Feb 2021 16:35:38 GMT",
      "server": "AmazonEC2"
    },
    "RetryAttempts": 0
  }
}

【讨论】:

  • 是python 3.7或3.6我使用3.6,目前调试和整理时出现了一些错误。另外,标签'Name'字段不应该是Key吗??
  • ec2.stop_instances*
  • @robby 我刚刚在这里输入了代码,以帮助您朝着正确的方向前进。当您准备过滤器时,您提供上述格式的标签。喜欢filters = [{'Name':'tag:environment', 'Values':[Env]}, {'Name':'tag:role', 'Values':[Role]} ]
  • 实际上它说我无法在 ec2.stop_instances 中使用过滤器参数... :( 感谢您的帮助!如果您能想到其他任何事情,请告诉我!
  • @robby stop_instances 不支持 custom filters。在我上面的代码中,我正在传递Instances
猜你喜欢
  • 2016-10-31
  • 2016-03-11
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 2020-05-09
  • 2013-07-26
  • 1970-01-01
相关资源
最近更新 更多