Lamda函数获取实例标签并发布到SNS

时间:2018-09-24 10:04:20

标签: amazon-web-services aws-lambda

我正在编写一个lambda函数,以从新启动的aws实例的cloudwatch中获取实例ID,并检查标签组,如果标签不存在,则发布到sns主题,但是我遇到错误了

  

'lambda_function'模块中的语法错误:意外缩进(lambda_function.py,第5行)

这是我更新的lambda函数

import boto3
SNS_TOPIC_ARN = 'arn:aws:sns:us-east-1:xxxxx:xxxx'
CODES = ['ttl', 'GGG', 'BRB', 'YLO']
def lambda_handler(event, context):
user = record['userIdentity']['userName']
        region = record['awsRegion']
        ec2 = boto3.resource('ec2', region_name = 'ap-south-1')
    # Extract Instance ID from event
    instance_id = event['detail']['instance-id']
    instance_object = ec2.Instance(instance['instanceId'])
    try:
        tags = {}
        for tag in instance_object.tags:
            tags[tag['Key']] = tag['Value']
        if('Code' not in tags or tags['Code'] not in CODES):
            sns.publish(TopicArn=SNS_TOPIC_ARN, Message=report(instance, user, region))
    except Exception as e:
        print(e)
        raise e

1 个答案:

答案 0 :(得分:0)

好像您缺少try语句:

import boto3
SNS_TOPIC_ARN = 'arn:aws:sns:us-east-1:xxxxx:xxxx'
CODES = ['ttl', 'GGG', 'BRB', 'YLO']
def lambda_handler(event, context):

    # Extract Instance ID from event
    instance_id = event['detail']['instance-id']
    instance_object = ec2.Instance(instance['instanceId'])
    try:
        tags = {}
        for tag in instance_object.tags:
            tags[tag['Key']] = tag['Value']
        if('Code' not in tags or tags['Code'] not in CODES):
            sns.publish(TopicArn=SNS_TOPIC_ARN, Message=report(instance, user, region))
    except Exception as e:
        print(e)
        raise e