-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands-ec2-lambda.py
52 lines (42 loc) · 1.69 KB
/
commands-ec2-lambda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import time
import json
import boto3
def str_decode(val):
val = val.split('\n')
ip_adress = val[0]
launch_time = val[1]
uptime = int(float(val[2].split(' ', 1)[0]))
os_version = val[4]
return ip_adress, launch_time, uptime, os_version
def lambda_handler(event, context):
# boto3 client
client = boto3.client('ec2')
ssm = boto3.client('ssm')
# getting instance information and ssm instance information
describeInstance = client.describe_instances()
ssm_describeInstance = ssm.describe_instance_information()
InstanceId=[]
# fetchin instance id of the running instances
for i in describeInstance['Reservations']:
for instance in i['Instances']:
if instance["State"]["Name"] == "running":
InstanceId.append(instance['InstanceId'])
# looping through instance ids
for instanceid in InstanceId:
# command to be executed on instance
response = ssm.send_command(
InstanceIds=[instanceid],
DocumentName="AWS-RunShellScript",
Parameters={'commands': ['hostname -i; uptime -s; cat /proc/uptime; cat /etc/*_version']})
# fetching command id for the output
json_response = response['Command']['CommandId']
time.sleep(3)
# fetching command output
json_output = ssm.get_command_invocation(
CommandId=json_response,
InstanceId=instanceid
)
ip_address, launch_time, uptime, os_version = str_decode(str(json_output['StandardOutputContent']))
# print(ip_address, launch_time, uptime, os_version)
# print(json_output['InstanceId'])
return json_output