Count Running and Stopped Ec2 Instances with AWS Lambda

2024/7/8 6:24:09

How can I count number of running and stopped EC2 instances in a particular region using boto3 and an AWS Lambda function?

Answer

Here's some code that retrieves a list of instances and count the number of stopped and running instances:

import boto3def lambda_handler(event, context):ec2_resource = boto3.resource('ec2')instances = [instance.state["Name"] for instance in ec2_resource.instances.all()]print('Running: ', instances.count('running'))print('Stopped: ', instances.count('stopped'))

The call to ec2_resource.instances.all() retrieves a list of all instances, and there is a state attribute that contains the Name of the state.

This will run in the default region for the Lambda function. If you wish to change regions, specify the region name like this:

ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')

Update: How to be notified via SNS.

If you want to be notified via SNS, there are two options:

  • Have the Lambda function directly send an SMS message to your phone via Amazon SNS using the publish(PhoneNumber='123') command, or
  • Have the Lambda function send a message to an Amazon SNS topic using the publish(TopicArn=xxx) command, and then subscribe to the SNS topic via the preferred method (eg email, SMS).

Please note that it will take a minute or so for instances to start/stop, so if you combine this with code that starts/stops instances, the count will not be accurate immediately after issuing those commands.

https://en.xdnf.cn/q/120236.html

Related Q&A

Python2.7: How to split a column into multiple column based on special strings like this?

Im a newbie for programming and python, so I would appreciate your advice!I have a dataframe like this.In info column, there are 7 different categories: activities, locations, groups, skills, sights, t…

python - return and print does not give same result

what Im trying to do is take the entered string separated by commas and change it to list then for each list as a key print the associated value.def main():myDict = {a:1, b:2, c:3, d:4, e:5....}u_input…

Creating a menuBar in a frame?

import Tkinter as tk from Tkinter import Label, StringVar, Entry, Button, Menu, Frame, Tk, Canvas import subprocess from Tkconstants import LEFT, CENTER,W, SUNKEN , X, Yclass SampleApp(tk.Tk):def __ini…

Python return dictionary [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Use selenium and python to move mouse outside of web page area

I need to test the exit intent form on this page: https://www.graphicproducts.com/guides/5s-system/When the mouse pointer is moved outside of the web page area a popup window appears. I then need to en…

Python „stack overflow” (104 if statements). Is def(x) the only solution to optimise code?

Today have tried to check files with path directory name. Previously it worked, until I tried to create 104 if/else statements. How to dispose of this overflow error? More specific question: Does def(…

How to fix Python restarting whenever I start program on IDLE environment?

import randomwinning_conditon = 0 no_of_guesses = 0 comp_guess = random.randint(1,100)while (no_of_guesses == 11) or (winning_conditon == 1):user_guess = int(input("What is your guess? "))if…

Fetching Lawyers details from a set of urls using bs4 in python

I am an absolute beginner to Web Scraping using Python and know very little about programming in Python. I am just trying to extract the information of the lawyers in the Tennessee location. In the web…

Having trouble with python simple code running in console [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

.upper not working in python

I currently have this codenum_lines = int(input()) lines = [] tempy = ctr = 1 abc = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z } for i in range(0, num_lines):tempy = input()lines.append([])l…