Using Jenkins AWS Lambda API Gateway to start Instances with tag

Posted By : Amarnath Arora | 31-Jul-2019

This is a sample Lambda function which will help you to start/stop EC2 Instances tagged properly in this example I am using the tag of key: value, env: staging please change the tags accordingly and feel free to change the python code as per your requirement.

Creating an IAM policy and Role for Lambda function so that Lambda can access EC2 resources.

1. Go to the IAM Console.
2. From navigation panel at the left side, go to Policies and click Create policy.
3. On the next screen select the JSON tab and paste this policy and click Review policy.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:Start*",
        "ec2:Stop*"
      ],
      "Resource": "*"
    }
  ]
}

4. On the next screen, enter Name, Description & Summary as per your choice.
5. Now on the IAM Console page go to Roles and click Create Role.
6. Under Select type of trusted entity select AWS Service then under Choose the service that will use this role select Lambda.
7. Click Next: Permissions.
8. On the next screen select the policy you just created using the search bar.
9. On next screen enter Key, Value if required and click Next: Review.
10. Now on review page enter Role name as per your choice, check the Policies for the confirmation that only selected policies are listed then click Create Role.

 

Creating a Lambda Function:

1. Go to Lambda Console
2. Click Create Function
3. Choose Author from scratch.
4. Under Basic information, add the following:
Function name as per your choice.
For Runtime, choose Python 2.7.
Under Permissions, expand, choose or create the execution role.
Under Execution role, choose to use an existing role.
Under Existing role, choose the IAM role that you created in the previous step.
5. Click Create Function.
6. Copy and paste this code under Function code editor

This function will filter the instances with the tag of key: value , env: staging from all EC2 Instances and start them if their current status is stopped.

 

import boto3
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    filters = [{
            'Name': 'tag:env',
            'Values': ['staging']
        },
        {
            'Name': 'instance-state-name',
            'Values': ['stopped']
            #'Values': ['running']
        }
    ]
    instances = ec2.instances.filter(Filters=filters)
    RunningInstances = [instance.id for instance in instances]
    if len(RunningInstances) > 0:
        startingUP = ec2.instances.filter(InstanceIds=RunningInstances).start()
        #shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
        print startingUP
        return {"code":0, "message":"SUCCESS"}
    else:
        print "Some Issue"
        return {"code":1, "message":"FAILED"}

 

7. Now click Save then Test your function.

 

Now to call this function remotely we can use AWS API Gateway.

To Create an API:

1. Go to API Gateway console and click Create API.
2. On the next page keep everything as already selected just enter the API name as per your choice.
3. Now API will be created and a new page will open of API Resources configuration.
4. Now click Actions and then Create Method and select the GET method and click Correct tick option right beside it.
5. Now under Choose the integration point for your new method there will be Integration type, select Lambda Function, on the same page in Lambda Function type the name of the lambda function we just created and select it and click Save.
6. Now a new page will open GET - Method Execution, here you can test your API, calling this API will execute the lambda function we created and start the EC2 Instance stopped with the selected tag if everything works fine you can click on Actions and Deploy API.

 

In the next blog, we will be using this API in the Jenkins job pipeline to execute the lambda function and return the SUCCESS or FAIL result so the pipeline can execute accordingly.

 

 

Related Tags

About Author

Author Image
Amarnath Arora

Amarnath has keen interest in cloud technologies & automation. He is very eager to learn and implement new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..