Saturday, February 24, 2018

Enforce Tagging. Using AWS Lambda Part-2

Hello Guys,

As we have already completed with prerequisites in the part-1. so Lets get going with lambda function.

Go to the https://aws.amazon.com  and login to console and click on lambda.
Then click on the Create Function --> Author from Scratch

When you click on author from scratch scroll down and you will find a form so fill it as shown in the snapshot

I have use the Run-time environment as Python 2.7 as I have written the code in Python 2.7
In the Role section Select the Role as Choose from existing role and in the next combo/drop-down box select the role Our role name "Lambda_basic_execution".
and click on Create function.

A nice screen will pop up

and on the left side of the function mean who will trigger it add cloud watch event which we have created in the Part1


Its configuration will look something like this at the bottom of the function.


Now click on the Function and Copy Paste the code.

import boto3
import logging

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

TopicArn = 'Write the Topic ARN for notification here'

#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': 'instance-state-name',
            'Values': ['running']
        }
    ]
   
    #filter the instances
    instances = ec2.instances.filter(Filters=filters)

    #locate Untagged untagged instances
    untaggedInstances = [instance.id for instance in instances if 'Name' not in [t['Key'] for t in instance.tags]]
#    The below line was added for debugging
    print untaggedInstances
    ptower_untaggedInstances = [instance.id for instance in instances if 'Product Tower' not in [t['Key'] for t in instance.tags]]
    app_untaggedInstances = [instance.id for instance in instances if 'Application' not in [t['Key'] for t in instance.tags]]
    scon_untaggedInstances = [instance.id for instance in instances if 'Support Contact' not in [t['Key'] for t in instance.tags]]
    appown_untaggedInstances = [instance.id for instance in instances if 'Application Owner' not in [t['Key'] for t in instance.tags]]
    dom_untaggedInstances = [instance.id for instance in instances if 'Domain' not in [t['Key'] for t in instance.tags]]
    untaggedInstances = untaggedInstances + ptower_untaggedInstances + app_untaggedInstances  + scon_untaggedInstances + appown_untaggedInstances + dom_untaggedInstances
    untaggedInstances = list(set(untaggedInstances))
    print untaggedInstances
    #print the instances for logging purposes
    #print untaggedInstances
   
    #make sure there are actually instances to shut down.
    if len(untaggedInstances) > 0:
        #perform the shutdown
         #print "Right now doing testing"
         shuttingDown = ec2.instances.filter(InstanceIds=untaggedInstances).stop()
        #publish_to_sns(shuttingDown)
         print shuttingDown
    #     print untaggedInstances
    else:
        print "Nothing to see here"



def publish_to_sns(message):
    sns = boto3.client('sns')
    sns_message = "We have shutdown the instances and Instace IDS are..."+str(message)
    response = sns.publish(TopicArn=topic_arn, Message = sns_message)
--------------------------------------------------------------------------------------------------------------------------
Code is Ends Here dont copy the ------
and After pasting it in the Function code section it will be like.


We are mostly Done.

Now If you Don't Create an Instance with The Tag :

  • Name
  • Product Tower
  • Application
  • Support Contact
  • Application Owner
  • Domain
Then the Instance will be ShutDown also Before enabling the script also make sure your exesting Instances also Have These tags otherwise it will also Stop them....

let me know If you face any issue while Implementing this....Am Happy to help you....
and also Belive me guys You wont find a better way to do this If you have multiple accounts and if they have different tagging requirement this will be the portable and simple solution....Enjoy...


Enforce Tagging. Using AWS Lambda Part-1

Hello Guys,

I have done a very interesting assignment in recent days in my office as the requirement was to shutdown all the instances of aws account which are not tagged with tag 'Owner' in it so I have started working on it for couple of days and created a simple lambda function

So lets start with the implementation
1. Created a IAM role using which the lambda service is going to execute the lambda function.
SO I have created a role name lambda_basic_execution  and attached two one is inline policy which looks something like this and other is EC2fulladmin which is available in aws.

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

}

So my IAM role is look something like below snapshot.


Cloudwatch Rule

Then I have Created a cloud-watch Rule which will we use to trigger the function
Sc  this is my rule which will trigger the even when ever the instance change its state.
{ "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ] }


We are almost done with our preparations  We will continue in the next part about the lamda function...