Last active
December 12, 2023 03:29
-
-
Save beisong7/f9892f581197d7fb9fe0453fa1198361 to your computer and use it in GitHub Desktop.
check ec2 instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def lambda_handler(event, context): | |
# List of EC2 instance IDs to check | |
instance_ids_to_check = ['i-08ac25730cea1a2a0', 'i-05f6ac34768663efc', 'i-0123456789abcdef2'] | |
# Print the list of instances to check | |
print(f"Instances to check: {instance_ids_to_check}") | |
# Check the EC2 instance state for each instance in the list | |
ec2_client = boto3.client('ec2') | |
for instance_id in instance_ids_to_check: | |
try: | |
response = ec2_client.describe_instances(InstanceIds=[instance_id]) | |
instance_state = response['Reservations'][0]['Instances'][0]['State']['Name'] | |
print(f"Current State of EC2 Instance {instance_id}: {instance_state}") | |
if(instance_state == 'running'): | |
print("running") | |
else: | |
print("not running") | |
# Add your custom logic based on the instance state if needed | |
# For example, send a notification, perform an action, etc. | |
except Exception as e: | |
print(f"Error checking state for instance {instance_id}: {e}") | |
# send email regarding error | |
# Add error handling logic as needed | |
# You can return a response if necessary | |
return { | |
'statusCode': 200, | |
'body': 'Function executed successfully!' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment