Python script to start/stop instances in AWS, meant to be run as a Lambda function.
Uses the python-lambda toolset nficano/python-lambda .
To setup, create a virtualenv and run pip install -r requirements.txt
To enable AWS connection you need to configure a default AWS profile in ~/.aws/credentials or provide keys in config.yaml.
Once the AWS connection has been configured you can test instance_manager from the local workstation. The file event.json contains sample data for test purposes.
{
"tags": {
"Purpose": "lambda-testing",
"Testing": "true"
},
"state": "stop"
}
Basically the tags given here are matched against the EC2 instance tags and when a match is found the instance state is moved to one of start/stop/terminate/restart which ever is defined here.
Define the tags and state as you want and run the test with command lambda invoke -v
.
instance_manager needs certain access rights to be able to perform its tasks. The easiest way may be to create a new IAM role for it as follows.
- IAM - Roles - Create New Role
- Role name = lambda_instance_manager (defined in config.yaml)
- Select Role Type - AWS Service Roles - AWS Lambda
- Attach Policy (leave empty) - Next Step
- Review - Create Role
- Select lambda_instance_manager role - Permissions - Inline Policies - Create - Custom Policy - Select
Policy Name = InstanceManagerPolicy Policy Document
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1474026789000",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstanceStatus",
"ec2:DescribeInstances",
"ec2:DescribeReservedInstances",
"ec2:MonitorInstances",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": [
"*"
]
}
]
}
To deploy instance_manager to AWS, just type lambda deploy
. (make sure you're deploying to the correct account)
Once the deployment is complete verify that instance-manager (defined in config.yaml) is visible on the AWS Lambda Functions page.
The final step is to create the CloudWatch schedule to run the lambda.
- CloudWatch - Rules - Create Rule
- Event Source - Schedule - Cron Expression - Put your schedule here e.g.
30 15 ? * * *
runs every day at 15:30 UTC - Add Target - Lambda Function - Function = instance-manager
- Configure Input - Constant (JSON Text) - Paste your event.json here e.g.
{ "tags": { "Purpose": "lambda-testing", "Testing": "true" }, "state": "stop" }
- Configure Details - Give name and description and click Create Rule