0

So, I have a Cloudwatch rule which can send a SNS topic when triggered. Now, I'm setting up a lambda function to change the security group of the EC2 instance when the CloudWatch rule triggers. I'm using python in Lambda, but my code it generating some "module errors". The tricky part is that I am trying to take the cloudwatch data and pass it as a variable. The event variable is in this syntax- event['detail']['resource']['instanceDetails']['instanceId'] so in my python code, it looks like this... I'm VERY new to python and lambda, but I'm trying to learn as much as I can. As you can see I'm trying to use this event variable and then utilize the SDK to execute the appropriate ModifyInstanceAttribute to change the security groups associated with the instance (for example with python): This code will replace the Security Group associated with the Instance specified as described in the boto3 docs here: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.modify_instance_attribute

my code so far below...

import boto3
client = boto3.client('ec2')
response = 
client.modify_instance_attribute(InstanceId=event['detail']. ['resource']['instanceDetails']['instanceId'], 
    Groups=['sg-4e499332',]
)

error I get is this module initialization error: name 'event' is not defined

1 Answer 1

1

You don't write code like that for Lambda. Your handler needs to be a function which takes the event and context parameters.

See the Lambda handler docs for Python.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, I've gotten further and got this to work but I have to actually define the exact instance ID. Not really what I want, because if I have multiple instances that match the Cloudwatch rule, they should get their security group changed too. Any help in parsing the event data as a variable in the lambda script?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.