繁体   English   中英

Lambda function Python 3.6 关闭带有特定标签的 EC2 实例

[英]Lambda function Python 3.6 to shut off EC2 instance with specific tags

这是我到目前为止所拥有的。 我只需要帮助创建 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))

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

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
  }
}

暂无
暂无

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

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