Skip to content

Commit 79890aa

Browse files
committed
lambda-ec2-ssm-command
1 parent 24426dd commit 79890aa

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

lambda/lambda_ec2_ssm.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#-*- coding: utf-8 -*-
2+
__author__ = "Chirag Rathod (Srce Cde)"
3+
__license__ = "MIT"
4+
__email__ = "chiragr83@gmail.com"
5+
__maintainer__ = "Chirag Rathod (Srce Cde)"
6+
7+
import time
8+
import json
9+
import boto3
10+
11+
def lambda_handler(event, context):
12+
13+
# boto3 client
14+
client = boto3.client('ec2')
15+
ssm = boto3.client('ssm')
16+
17+
# getting instance information
18+
describeInstance = client.describe_instances()
19+
20+
InstanceId=[]
21+
# fetchin public IP address of the running instances
22+
for i in describeInstance['Reservations']:
23+
for instance in i['Instances']:
24+
if instance["State"]["Name"] == "running":
25+
InstanceId.append(instance['InstanceId'])
26+
27+
for instanceid in InstanceId:
28+
response = ssm.send_command(
29+
InstanceIds=[instanceid],
30+
DocumentName="AWS-RunShellScript",
31+
Parameters={'commands': ['command_to_be_executed']}, )
32+
33+
command_id = response['Command']['CommandId']
34+
35+
time.sleep(3)
36+
37+
output = ssm.get_command_invocation(
38+
CommandId=command_id,
39+
InstanceId=instanceid
40+
)
41+
print(output)
42+
43+
return {
44+
'statusCode': 200,
45+
'body': json.dumps('Thanks from Srce Cde!')
46+
}

0 commit comments

Comments
 (0)