Will Aws Continue to Stop an Instance After I Close
- Posted on
Pre-requisite:
- AWS Account
- Launched AWS EC2 servers
- Basic knowledge of Python
Architecture Diagram
Implementation:
To stop the instances, we will follow below steps:
- Create IAM policy & execution role for Lambda function
- 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
- Create lambda function trigger using AWS EventBridge
- Login to AWS Console
- Go to IAM Services ⇒ Go to Policies
- Click on Create Policy
- 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": "*" } ] }
- Add Tags & Name for policy
- Review & Create the Policy
- Go to AWS Lambda service
- Click on "Create Function"
- Select "Author from scratch"
- Add Function Name
- In Runtime, select "Python 3.9"
- In "Change default execution role" tab, select "Use an existing role"
- In "Existing role" select the role created in Step-1
- In "Advanced settings", you can setup the Tags & Enable VPC if required
- Click on "Create Function"
- Once function is create, go to function & then in configuration tab ⇒ General configuration ⇒ Change the timeout to 1 minute
- Go to Code tab
- 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
-
- Once the code changes are done, click on "Deploy" to save & deploy the changes.
- To test the function, click on test and pass below JSON as test event JSON.
{ "ScheduledShutdown": "Yes" }
- Go to Amazon EventBridge ⇒ Go to Rules
- Click on "Create rule"
- 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
- 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
Implementation:
To stop the instances, we will follow below steps:
- Create IAM policy & execution role for Lambda function
- 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
- Create lambda function trigger using AWS EventBridge
- Login to AWS Console
- Go to IAM Services ⇒ Go to Policies
- Click on Create Policy
- 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": "*" } ] }
- Add Tags & Name for policy
- Review & Create the Policy
- Go to AWS Lambda service
- Click on "Create Function"
- Select "Author from scratch"
- Add Function Name
- In Runtime, select "Python 3.9"
- In "Change default execution role" tab, select "Use an existing role"
- In "Existing role" select the role created in Step-1
- In "Advanced settings", you can setup the Tags & Enable VPC if required
- Click on "Create Function"
- Once function is create, go to function & then in configuration tab ⇒ General configuration ⇒ Change the timeout to 1 minute
- Go to Code tab
- 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
-
- Once the code changes are done, click on "Deploy" to save & deploy the changes.
- To test the function, click on test and pass below JSON as test event JSON.
{ "ScheduledShutdown": "Yes" }
- Go to Amazon EventBridge ⇒ Go to Rules
- Click on "Create rule"
- 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
- Review the details and create rule
Lambda destination can be used if needed
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