1

I am running a python job in AWS Lambda to stop ec2 instances based on tags. The script is running properly, but even if the script completes successfully, I am getting output "null" in the result returned by function execution. Attached herewith is the python script. I am new to Python scripting. I am from ops side.

import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    # Use the filter() method of the instances collection to retrieve
    # all running EC2 instances.
    filters = [{
            'Name': 'tag:AutoOff',
            'Values': ['True']
        },
        {
            'Name': 'instance-state-name', 
            'Values': ['running']
        }
    ]

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

    #locate all running instances
    RunningInstances = [instance.id for instance in instances]

    #print the instances for logging purposes
    print RunningInstances 

    #make sure there are actually instances to shut down. 
    if len(RunningInstances) > 0:
        #perform the shutdown
        shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
        print shuttingDown
    else:
        print "NOTHING"
2
  • I don't see the python script... Commented Sep 5, 2017 at 8:57
  • Added the script now.. Commented Sep 5, 2017 at 9:00

1 Answer 1

1

In order to get response from the lambda you need to return something (usually a dictionary) from lambda_handler method. By default all Python methods return None type, that is why you do not receive any valuable response.

def lambda_handler(event, context):
    ... your code here ...
    return {"turned_off": RunningInstances}

PS. it is preferred to use logging.debug|info|... method instead of print(). You can find more info in the documentation: https://docs.python.org/2.7/library/logging.html

Anyway all the output is saved to CloudWatch Logs. The Log Stream is created automatically when you create a Lambda function. You can find all your prints there for debugging.

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

Comments

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.