如何在AWS Lambda中使用python访问事件对象?
就这一问题采取后续行动: 我认为这个问题不完整,因为它没有说明如何使用python访问事件对象 我的目标是:如何在AWS Lambda中使用python访问事件对象?,python,amazon-web-services,aws-lambda,eventtrigger,Python,Amazon Web Services,Aws Lambda,Eventtrigger,就这一问题采取后续行动: 我认为这个问题不完整,因为它没有说明如何使用python访问事件对象 我的目标是: 读取由运行状态更改触发的实例 获取与实例关联的标记值 启动具有相同标记的所有其他实例 Cloudwatch触发事件是: { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ], "detail": { "state": [
- 读取由运行状态更改触发的实例
- 获取与实例关联的标记值
- 启动具有相同标记的所有其他实例
{
"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)
我可以看到event对象,但看不到如何深入到状态更改为running的实例的标记
请问,我可以通过什么对象属性从触发的实例获取标记
我怀疑是这样的:
myTag = event.details.instance-id.tags["startgroup1"]
在事件的详细信息部分,您将获得实例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"
}
}
传递给Lambda的事件数据包含实例ID 然后需要调用
descripe_tags()
来检索标签字典
import boto3
client = boto3.client('ec2')
client.describe_tags(Filters=[
{
'Name': 'resource-id',
'Values': [
event['detail']['instance-id']
]
}
]
)
这就是我想到的 请让我知道如何做得更好。谢谢你的帮助
# 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)
#逐个启动MEUP#U实例
#
#此lambda脚本由CloudWatch事件startGroupByInstance触发。
#每天晚上,一个单独的lambda脚本按计划启动以停止
#所有非必要的实例。
#
#此脚本将打开具有匹配的LaunchGroup标记的所有实例
#已更改为运行状态的单个实例。
#
#要启动启动组中的所有实例,
#启动LaunchGroup中的一个实例并等待大约5分钟。
#
#运行成本:约0.02美元/月
# https://s3.amazonaws.com/lambda-tools/pricing-calculator.html
#每月执行150次*128 MB内存*60000毫秒执行时间
#
#问题:与克里斯对话
# ======================================
#测试系统
#这就是事件对象的外观(见下文)
#它在测试事件对象中使用特定实例id进行配置
#将其更改为使用不同的启动组测试不同的实例id
#{“版本”:“0”,
#“id”:“XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”,
#“详细信息类型”:“EC2实例状态更改通知”,
#“来源”:“aws.ec2”,
#“账户”:“999999999999”,
#“时间”:“2015-11-11T21:30:34Z”,
#“区域”:“us-east-1”,
#“资源”:[
#“arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111”
# ],
#“细节”:{
#“实例id”:“i-0aad9474”,#0:
startingUp=ec2.instances.filter(instanceId=stoppedInstances.start())
打印(“已完成启动标记“+thisLaunchGroup”的所有实例)
因此,下面是如何在Python代码中为Lambda函数获取标记的
ec2 = boto3.resource('ec2')
instance = ec2.Instance(instanceId)
# get image_id from instance-id
imageId = instance.image_id
print(imageId)
for tags in instance.tags:
if tags["Key"] == 'Name':
newName = tags["Value"] + ".mydomain.com"
print(newName)
因此,使用
instance.tags
,然后检查与我的Name
标记匹配的“Key”
,并拉出“Value”
,以创建FQDN(完全限定域名).谢谢,Vaisakh。这实际上很有帮助。我看到了事件对象和详细信息部分,但请注意,如何使用python获取此实例id的特定标记。这是一个json解析练习吗?还是可以使用对象属性来完成?实例的标记值似乎不在事件对象中。谢谢,Chris、 John,我在boto3文档中看到了对客户端对象的引用,但没有看到descripe_tags方法。我已经发布了我的工作(可能不是最好的)代码。虽然在使用不存在的实例id进行测试时会抛出错误,但它工作得很快。我认为这没关系,因为我可能不会从不存在的实例列表中启动实例。实际上,我认为它可能会被终止,仍然在列表中,并且我意外地选择了它。哦,好吧。