2017-09-14 3 views
1

이 질문에 후속 : Filter CloudWatch Logs to extract Instance IDAWS Lambda에서 python으로 이벤트 객체에 액세스하는 방법은 무엇입니까?

나는 그것이 파이썬과 이벤트 객체에 액세스하는 방법을 언급하지 않기 때문에 불완전 질문 잎 생각합니다.

  • 인스턴스
  • 시작 같은 태그가 다른 모든 인스턴스와 연관된 태그 값을 얻을 상태
  • 을 실행에 변화에 의해 촉발 된 인스턴스를 읽어에

    내 목표는

CloudWatch는 트리거 이벤트는 다음과 같습니다

{ 
    "source": [ 
    "aws.ec2" 
    ], 
    "detail-type": [ 
    "EC2 Instance State-change Notification" 
    ], 
    "detail": { 
    "state": [ 
     "running" 
    ] 
    } 
} 

나는 다음과 같은 예를 볼 수 있습니다

def lambda_handler(event, context): 

    # here I want to get the instance tag value 
    # and set the tag filter based on the instance that 
    # triggered the event 

    filters = [{ 
      'Name': 'tag:StartGroup', 
      'Values': ['startgroup1'] 
     }, 
     { 
      'Name': 'instance-state-name', 
      'Values': ['running'] 
     } 
    ] 

    instances = ec2.instances.filter(Filters=filters) 

내가 이벤트 객체를 볼 수 있지만 나는 그것이 상태가 실행으로 변경의 한 인스턴스의 태그를 드릴 다운하는 방법을 볼 수 없습니다.

제발, 트리거 된 인스턴스에서 태그를 가져올 수있는 객체 속성은 무엇입니까?

나는이 같은 의심 : 이벤트의 세부 사항 섹션에서

myTag = event.details.instance-id.tags["startgroup1"] 

답변

0

을, 당신은 인스턴스 ID의를 얻을 것이다. 인스턴스 ID 및 AWS SDK를 사용하여 태그를 쿼리 할 수 ​​있습니다. 다음은 샘플 이벤트입니다.

{ 
    "version": "0", 
    "id": "ee376907-2647-4179-9203-343cfb3017a4", 
    "detail-type": "EC2 Instance State-change Notification", 
    "source": "aws.ec2", 
    "account": "123456789012", 
    "time": "2015-11-11T21:30:34Z", 
    "region": "us-east-1", 
    "resources": [ 
    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111" 
    ], 
    "detail": { 
    "instance-id": "i-abcd1111", 
    "state": "running" 
    } 
} 
+0

감사합니다. 실제로 도움이됩니다. 이벤트 객체와 세부 정보 섹션이 표시되지만이 인스턴스 ID에 대해 Python을 사용하여 특정 태그를 얻는 방법을 알려주십시오. json 파싱 연습입니까? 또는 객체 속성을 사용하여이 작업을 수행 할 수 있습니까? 인스턴스의 태그 값이 이벤트 객체에없는 것처럼 보입니다. 감사합니다. Chris. – Chrisjx

0

람다에 전달 된 이벤트 데이터에는 인스턴스 ID가 들어 있습니다.

그런 다음 describe_tags()으로 전화하여 태그 사전을 검색해야합니다. 이것은 내가 생각 해낸 것입니다

import boto3 
client = boto3.client('ec2') 

client.describe_tags(Filters=[ 
     { 
      'Name': 'resource-id', 
      'Values': [ 
       event['detail']['instance-id'] 
      ] 
     } 
    ] 
) 
+0

John, boto3 문서에서 클라이언트 개체에 대한 참조를 보았지만 describe_tags 메서드가 표시되지 않았습니다. 작동하는 (아마도 좋지 않은) 코드를 게시했습니다. 그것은 존재하지 않는 instance-id로 테스트 할 때 오류를 던지더라도 빠르게 작동합니다. 존재하지 않는 인스턴스 목록에서 인스턴스를 시작하지 않기 때문에 괜찮습니다. 우리는 실제로 목록에서 종료 될 수 있다고 생각합니다. 실수로 그것을 선택합니다. 오, 그럼. – Chrisjx

0

...

내가 그것을 더 잘 할 수있는 방법을 알려 주시기 바랍니다. 도와 주셔서 감사합니다.

# StartMeUp_Instances_byOne 
# 
# This lambda script is triggered by a CloudWatch Event, startGroupByInstance. 
# Every evening a separate lambda script is launched on a schedule to stop 
# all non-essential instances. 
# 
# This script will turn on all instances with a LaunchGroup tag that matches 
# a single instance which has been changed to the running state. 
# 
# To start all instances in a LaunchGroup, 
# start one of the instances in the LaunchGroup and wait about 5 minutes. 
# 
# Costs to run: approx. $0.02/month 
# https://s3.amazonaws.com/lambda-tools/pricing-calculator.html 
# 150 executions per month * 128 MB Memory * 60000 ms Execution Time 
# 
# Problems: talk to chrisj 
# ====================================== 

# test system 
# this is what the event object looks like (see below) 
# it is configured in the test event object with a specific instance-id 
# change that to test a different instance-id with a different LaunchGroup 

# { "version": "0", 
# "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
# "detail-type": "EC2 Instance State-change Notification", 
# "source": "aws.ec2", 
# "account": "999999999999999", 
# "time": "2015-11-11T21:30:34Z", 
# "region": "us-east-1", 
# "resources": [ 
#  "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111" 
# ], 
# "detail": { 
#  "instance-id": "i-0aad9474", # <---------- chg this 
#  "state": "running" 
# } 
# } 
# ====================================== 

import boto3 
import logging 
import json 

ec2 = boto3.resource('ec2') 

def get_instance_LaunchGroup(iid): 
    # When given an instance ID as str e.g. 'i-1234567', 
    # return the instance LaunchGroup. 
    ec2 = boto3.resource('ec2') 
    ec2instance = ec2.Instance(iid) 
    thisTag = '' 
    for tags in ec2instance.tags: 
     if tags["Key"] == 'LaunchGroup': 
      thisTag = tags["Value"] 
    return thisTag 

# this is the entry point for the cloudwatch trigger 
def lambda_handler(event, context): 

    # get the instance id that triggered the event 
    thisInstanceID = event['detail']['instance-id'] 
    print("instance-id: " + thisInstanceID) 

    # get the LaunchGroup tag value of the thisInstanceID 
    thisLaunchGroup = get_instance_LaunchGroup(thisInstanceID) 
    print("LaunchGroup: " + thisLaunchGroup) 
    if thisLaunchGroup == '': 
     print("No LaunchGroup associated with this InstanceID - ending lambda function") 
     return 

    # set the filters 
    filters = [{ 
      'Name': 'tag:LaunchGroup', 
      'Values': [thisLaunchGroup] 
     }, 
     { 
      'Name': 'instance-state-name', 
      'Values': ['stopped'] 
     } 
    ] 

    # get the instances based on the filter, thisLaunchGroup and stopped 
    instances = ec2.instances.filter(Filters=filters) 

    # get the stopped instance IDs 
    stoppedInstances = [instance.id for instance in instances] 

    # make sure there are some instances not already started 
    if len(stoppedInstances) > 0: 
     startingUp = ec2.instances.filter(InstanceIds=stoppedInstances).start() 

    print ("Finished launching all instances for tag: " + thisLaunchGroup) 
관련 문제