Lambda Function For Auto-Tagging EC2 Instances

Mithun Kadyada
6 min readApr 28, 2020

--

Amazon Web Services(AWS) has a big impact on Cloud world with a number of services to its users. Services provided by AWS are belongs to free tier as well paid one. So, its better to have good knowledge on AWS services and their pricing before using any of its services. Here, I’m going to explain how to write a lambda function which will automatically tags the username and principalID to EC2 instances when it created. This will helps to identify which EC2 instance created by whom( IAM user).

Amazon Elastic Compute Cloud (EC2) forms a central part of Amazon.com’s cloud-computing platform, Amazon Web Services (AWS), by allowing users to rent virtual computers on which to run their own computer applications.

-According to Wikipedia

Services will be used for auto-tagging are:

  • EC2 Instance(For Testing)
  • cloudWatch
  • AWS Lambda
  • IAM( Creating role by attaching policies)
Fig.1: Basic workflow of autoTagging EC2 instances

When EC2 Instrance is created it will automatically runs the Instance. Whatever work we are doing on AWS will be tracked under cloudWatch. So, In cloudWatch we have to create event Rule which will trigger AWS Lambda on particular eventI(ex: RunInstances). We have to configure cloudWatch event rule in such a way that it should send required information to aws Lambda.
Steps Involved in setting up autoTag Lambda function in AWS are:
1. Writing AWS Lambda.
2. Setting-up event Rule in cloudWatch.
3. Creating IAM role and attaching role to AWS Lambda.

Writing Script in AWS Lambda

AWS lambda is a serverless platform to host and run our script. In this blog, I’m writing python script(2.7). To know more on AWS Lambda visit my blog on Lambda for using ElasticSearch service. Create a Lambda function with the proper name( EX: AutoTagging) and paste the below code.

Ref: https://aws.amazon.com/blogs/security/how-to-automatically-tag-amazon-ec2-resources-in-response-to-api-events/

The above code will automatically adds the Username and PrincipalID to EC2 Instance whenRunInstancesevent is triggered. RunInstances will be triggered when EC2 is created and starts running for first time. If you stop and restart the EC2 Instance, then startInstances will be triggered. Here, we have to pass details of the event(ex: eventName , userIdentity, principalID and so on) to the lambda main function(lambdahandler). This can be achieved through Setting-up event Rule in cloudWatch.

Setting-up event Rule in cloudWatch.

Amazon CloudWatch Events delivers a near real-time stream of system events that describe changes in Amazon Web Services (AWS) resources. Using simple rules that you can quickly set up, you can match events and route them to one or more target functions or streams. CloudWatch Events becomes aware of operational changes as they occur. CloudWatch Events responds to these operational changes and takes corrective action as necessary, by sending messages to respond to the environment, activating functions, making changes, and capturing state information.

Amazon Web Services(AWS)

Events: Event is a change in cloud Environment such as state changes( Creating EC2, stop, start, terminate and so on) Any changes in cloud Environment will be known as Event.
Rules: Rules will process the targets on any matching Event occurs. A single rule can routes multiple targets.
Targets: A target is which processes the Events. Targets can includes AWS cloud services such as Amazon EC2 instances, AWS Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, Amazon SNS topics, Amazon SQS queues, and built-in targets. Target receives Events and these events will be in JSON format.

Step 1: Go to AWS dashborad -> CloudWatch Services -> EVents -> Rules -> create Rule.

Fig 2.1: Creating Event Rule in CloudWatch for AutoTagging EC2

Step 2: Under Create rule Select Service name (EC2 @ 1)-> Event Type(AWS API Call via cloudTrail @ 2)-> Select Any Operation on left side of dashboard (Event Source).

Fig 2.2: Configuring Event Rule for AutoTagging EC2

Step 3: Goto Targets (Right side of dashboard) -> Click on Add Target @3 -> Select Lambda Function@4 from the fist dropdown -> select function name that you have created in second dropdown @5(Ex: AutoTagging).
Step 4: Click on Configure details ->under Configure Rule details-> Add rule Name(Mandatory, ex: AutoTagRule @1)-> Add Description (optional) @2 -> check state Enabled @3 -> Create Rule @4.

Fig 2.3: Configuring rule details for AutoTagging EC2

Note:The above Event Rule will triggers aws Lambda function(AutoTagging) on any EC2 state changes( All EC2 events will trigger AutoTagging Lambda function). Event Type: AWS API Call via cloudTrail helps to record all information about API call and capturing Event Details which will be used in AutoTagging Lambda function. To know more about Event Type click here.

Creating IAM role and attaching role to AWS Lambda.

By default AWS Lambda will have basic access permission to Amazon CloudWatch Logs. With this basic Permission can perform following tasks through aws lambda.

  • logs:CreateLogGroup
  • logs:CreateLogStream
  • logs:PutLogEvents

With the basic permission we cannot add or modify tags for EC2 instances. So, we need to setup IAM role which grants access to add , modify or delete tags on EC2. This IAM role should be attached to our AWS lambda. Through IAM role you can grant permission to individual or group to access the resources securely.

Step 1: Creating IAM Policies

1. goto IAM from aws services-> Policies-> create Policies-> create policy for EC2 Tagging as shown below.

Fig 3.1.1: Creating policies for EC2 Tagging

2. Give proper name and description for policy(Ex: EC2TaggingPermission)->click on create policy

Fig 3.1.2: Creating IAM policies with description

Step 2: Creating Role and Attaching policies

1. Click on Role from IAM dashboard-> click on create role-> select AWS service @1(by default selected) ->Select Lambda -> Click on Next: Permissions

Fig 3.2.1: Creating IAM role for Lambda

2. Attach policies AWSLambdaBasicExecutionRole and EC2TaggingPermission(created policy for attaching tags) -> Click on Next: Tags

Fig 3.2.2: Attaching policies to IAM role

3. Add tags if required( key : value pair )-> click Next to got to step 4.
4. Add Role name(EX: AutoTaggingRole)-> Role description -> click on Create role.

Fig 3.2.3: final step for creating IAM role

Note: This IAM role allows Lambda to add, delete Tags to EC2 instances and basic cloud watch permissions (logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents). If you want to grant more aws services to be accessed by your Lambda then you need to attach policies accordingly to your IAM role.

step 4: Attaching created IAM role to Lambda:

1. goto Lambda-> select your Lambda function(EX: AutoTag)-> scroll down to Execution Role-> Select use an existing role @1 -> Select IAM role that we created(EX: AutoTaggingRole)@2

Fig 4.1: Attaching IAM role to AWS Lambda

2. Under Basic settings-> Click on Edit @3-> Increase Timeout (Min : 1 min)@4 -> Save the Lambda function @5.

Note: If Created IAM role is not showing in dropdown click on refresh button. If same thing happens then goto your IAM role-> Trust Relationship-> Edit trust realtionship-> add "Service": "lambda.amazonaws.com" under principal.

Now, if any user creates EC2 instance under region where Lambda and cloudWatch events were configured, it will automatically adds username and principalID to that EC2 instance and Lambda will automatically creates logs in cloudWatch which helps us to track the lambda functionality.

Conclusion: I hope you liked and followed this blog.In this blog, we created cloudWatch event to call lambda on EC2 state changes, creating IAM policies and role and also attaching the created IAM role to aws lambda. If you’re having any queries please free to comment below.

References:
Amazon Web Services

--

--