Will Aws Continue to Stop an Instance After I Close

Pre-requisite:
  • AWS Account
  • Launched AWS EC2 servers
  • Basic knowledge of Python

Architecture Diagram

lambda-to-stop-ec2-instances


Implementation:

To stop the instances, we will follow below steps:

  1. Create IAM policy & execution role for Lambda function
  2. Create lambda function using python codebase
    • Approach-1: Pass the hardcoded instance IDs as list in python to stop the instances
    • Approach-2: Stop the instances by using instance tags
  3. Create lambda function trigger using AWS EventBridge
Step-1: Create IAM policy & execution role for lambda function
  1. Login to AWS Console
  2. Go to IAM Services ⇒ Go to Policies
  3. Click on Create Policy
  4. Click on JSON & paste the below policy
    { 	"Version": "2012-10-17", 	"Statement": [ 		{ 			"Effect": "Allow", 			"Action": [ 				"logs:CreateLogGroup", 				"logs:CreateLogStream", 				"logs:PutLogEvents" 			], 			"Resource": "arn:aws:logs:*:*:*" 		}, 		{ 			"Effect": "Allow", 			"Action": [ 				"ec2:DescribeInstances", 				"ec2:Start*", 				"ec2:Stop*" 			], 			"Resource": "*" 		} 	] }
  5. Add Tags & Name for policy
  6. Review & Create the Policy
Step-2: Create lambda function using python codebase
  1. Go to AWS Lambda service
  2. Click on "Create Function"
  3. Select "Author from scratch"
  4. Add Function Name
  5. In Runtime, select "Python 3.9"
  6. In "Change default execution role" tab, select "Use an existing role"
  7. In "Existing role" select the role created in Step-1
  8. In "Advanced settings", you can setup the Tags & Enable VPC if required
  9. Click on "Create Function"
  10. Once function is create, go to function & then in configuration tab ⇒ General configuration ⇒ Change the timeout to 1 minute
  11. Go to Code tab
  12. Edit file lambda_function.py and use the code depending on the approach given below.
    • Approach-1: Use the hardcoded instance IDs in python script to stop the instances using lambda function. Use below code in lambda function:
      import boto3 region = 'REGION' #example: us-east-1 ec2 = boto3.client('ec2', region_name=region)  def lambda_handler(event, context): 	instances = ['INSTANCE_ID_1','INSTANCE_ID_2'] 	response = [] 	if len(instances) > 0: 		response.append(ec2.stop_instances(InstanceIds=instances)) 	else: 		response.append('No instances found')                            

      *Note: Replace content in red i.e., REGION, INSTANCE_ID_1, INSTANCE_ID_2 with actual values

    • Approach-2: Use instance tags to stop the instances using lambda function. Use below code in lambda function:
      import boto3 region = 'REGION' #example: us-east-1  def lambda_handler(event, context):     ec2 = boto3.resource('ec2')     ec2Client = boto3.client('ec2', region_name=region)     instances = []     response = [] 	 		#Filter checks if the instance is running & has a tag with Name:ScheduledShutdown Value: Yes     instancelist = [i for i in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag:ScheduledShutdown', 'Values':[event['ScheduledShutdown']]}])]     for instance in instancelist:         instances.append(instance.id)     if len(instances) > 0:         response.append(ec2Client.stop_instances(InstanceIds=instances))     else:         response.append('No running instances found with given tag')     return response                            

      *Note: Replace content in red i.e., REGION with actual values

  13. Once the code changes are done, click on "Deploy" to save & deploy the changes.
  14. To test the function, click on test and pass below JSON as test event JSON.
    {     "ScheduledShutdown": "Yes" }                        
Step-3: Create trigger for lambda function using AWS EventBridge
  1. Go to Amazon EventBridge ⇒ Go to Rules
  2. Click on "Create rule"
  3. Use below parameters and create the rule
    • Name: lambda-trigger-stop-instance
    • Rule type: Schedule
    • Schedule pattern: A fine-grained schedule
    • Cron expression: cron(30 14 ? * MON-FRI *)

      *Note: Assuming we have to stop the servers at 8:00pm from monday to friday

    • Select a target: Lambda Function
    • Function: stop-instances-lambda
  4. Review the details and create rule

Lambda destination can be used if needed

Search Blogs

Search Blogs

Pre-requisite:
  • AWS Account
  • Launched AWS EC2 servers
  • Basic knowledge of Python

Architecture Diagram

lambda-to-stop-ec2-instances


Implementation:

To stop the instances, we will follow below steps:

  1. Create IAM policy & execution role for Lambda function
  2. Create lambda function using python codebase
    • Approach-1: Pass the hardcoded instance IDs as list in python to stop the instances
    • Approach-2: Stop the instances by using instance tags
  3. Create lambda function trigger using AWS EventBridge
Step-1: Create IAM policy & execution role for lambda function
  1. Login to AWS Console
  2. Go to IAM Services ⇒ Go to Policies
  3. Click on Create Policy
  4. Click on JSON & paste the below policy
    { 	"Version": "2012-10-17", 	"Statement": [ 		{ 			"Effect": "Allow", 			"Action": [ 				"logs:CreateLogGroup", 				"logs:CreateLogStream", 				"logs:PutLogEvents" 			], 			"Resource": "arn:aws:logs:*:*:*" 		}, 		{ 			"Effect": "Allow", 			"Action": [ 				"ec2:DescribeInstances", 				"ec2:Start*", 				"ec2:Stop*" 			], 			"Resource": "*" 		} 	] }
  5. Add Tags & Name for policy
  6. Review & Create the Policy
Step-2: Create lambda function using python codebase
  1. Go to AWS Lambda service
  2. Click on "Create Function"
  3. Select "Author from scratch"
  4. Add Function Name
  5. In Runtime, select "Python 3.9"
  6. In "Change default execution role" tab, select "Use an existing role"
  7. In "Existing role" select the role created in Step-1
  8. In "Advanced settings", you can setup the Tags & Enable VPC if required
  9. Click on "Create Function"
  10. Once function is create, go to function & then in configuration tab ⇒ General configuration ⇒ Change the timeout to 1 minute
  11. Go to Code tab
  12. Edit file lambda_function.py and use the code depending on the approach given below.
    • Approach-1: Use the hardcoded instance IDs in python script to stop the instances using lambda function. Use below code in lambda function:
      import boto3 region = 'REGION' #example: us-east-1 ec2 = boto3.client('ec2', region_name=region)  def lambda_handler(event, context): 	instances = ['INSTANCE_ID_1','INSTANCE_ID_2'] 	response = [] 	if len(instances) > 0: 		response.append(ec2.stop_instances(InstanceIds=instances)) 	else: 		response.append('No instances found')                            

      *Note: Replace content in red i.e., REGION, INSTANCE_ID_1, INSTANCE_ID_2 with actual values

    • Approach-2: Use instance tags to stop the instances using lambda function. Use below code in lambda function:
      import boto3 region = 'REGION' #example: us-east-1  def lambda_handler(event, context):     ec2 = boto3.resource('ec2')     ec2Client = boto3.client('ec2', region_name=region)     instances = []     response = [] 	 		#Filter checks if the instance is running & has a tag with Name:ScheduledShutdown Value: Yes     instancelist = [i for i in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag:ScheduledShutdown', 'Values':[event['ScheduledShutdown']]}])]     for instance in instancelist:         instances.append(instance.id)     if len(instances) > 0:         response.append(ec2Client.stop_instances(InstanceIds=instances))     else:         response.append('No running instances found with given tag')     return response                            

      *Note: Replace content in red i.e., REGION with actual values

  13. Once the code changes are done, click on "Deploy" to save & deploy the changes.
  14. To test the function, click on test and pass below JSON as test event JSON.
    {     "ScheduledShutdown": "Yes" }                        
Step-3: Create trigger for lambda function using AWS EventBridge
  1. Go to Amazon EventBridge ⇒ Go to Rules
  2. Click on "Create rule"
  3. Use below parameters and create the rule
    • Name: lambda-trigger-stop-instance
    • Rule type: Schedule
    • Schedule pattern: A fine-grained schedule
    • Cron expression: cron(30 14 ? * MON-FRI *)

      *Note: Assuming we have to stop the servers at 8:00pm from monday to friday

    • Select a target: Lambda Function
    • Function: stop-instances-lambda
  4. Review the details and create rule

Lambda destination can be used if needed

cocawititival.blogspot.com

Source: https://chetanzade.com/blogs/aws-lambda-function-to-stop-instances/

0 Response to "Will Aws Continue to Stop an Instance After I Close"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel