Skip to content

Instantly share code, notes, and snippets.

@trepidity
Created March 13, 2020 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trepidity/a9b83d27d1cc8a60944dcb941a9da8e4 to your computer and use it in GitHub Desktop.
Save trepidity/a9b83d27d1cc8a60944dcb941a9da8e4 to your computer and use it in GitHub Desktop.
from __future__ import print_function
import logging
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# print(response['Reservations'][0]['Instances'][0]['InstanceId'])
# params = {"commands": ["#!/usr/bin/env bash", "", "sh hello_world.sh"], "workingDirectory": ["/usr/bin"],
# "executionTimeout": ["30"]}
# ssm_client.send_command(DocumentName='AWS-RunShellScript', InstanceIds=running_instances,
# Comment='Executing Hello World from Lambda Function', TimeoutSeconds=600,
# Parameters=params)
def handler(event, context):
try:
ec2_client = boto3.client('ec2', region_name='us-east-2')
ssm_client = boto3.client('ssm', region_name='us-east-2')
response = ec2_client.describe_instances(Filters=[{'Name':'tag:Namespace', 'Values':['ninja-tools']}])
# running_instances = [instance.get('InstanceId') for instance in response]
# another example, but doesn't work cause it doesn't filter by tag.
# running_instances = [instance.get('InstanceId') for instance in
# ec2_client.describe_instance_status().get('InstanceStatuses') if
# instance.get('InstanceState').get('Code') == 16]
print(response)
for r in response['Reservations']:
for i in r['Instances']:
print(i.get('InstanceId'))
params = {"commands": ["#!/usr/bin/env bash", "", "sh hello_world.sh"], "workingDirectory": ["/usr/bin"],
"executionTimeout": ["30"]}
# I need to use the collection of Instance IDs here InstanceIds
ssm_client.send_command(DocumentName='AWS-RunShellScript', InstanceIds=running_instances,
Comment='Executing Hello World from Lambda Function', TimeoutSeconds=600,
Parameters=params)
except Exception as e:
raise e
else:
print('Hello World succeeded')
@trepidity
Copy link
Author

trepidity commented Mar 13, 2020

here is what print(response) gives out

{'Reservations': [{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 'ImageId': 'ami-0e01ce4ee18447327', 'InstanceId': 'i-08596bd4b3ac63cad', 'InstanceType': 't3.medium', 'KeyName': 'tweener-generated', 'LaunchTime': datetime.datetime(2020, 3, 13, 15, 42, 2, tzinfo=tzlocal()), 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'us-east-2a', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-172-28-0-103.us-east-2.compute.internal', 'PrivateIpAddress': '172.28.0.103', 'ProductCodes': [], 'PublicDnsName': 'ec2-3-20-168-179.us-east-2.compute.amazonaws.com', 'PublicIpAddress': '3.20.168.179', 'State': {'Code': 16, 'Name': 'running'}, 'StateTransitionReason': '', 'SubnetId': 'subnet-03cdd67c2ad14cd20', 'VpcId': 'vpc-018baf63faed4eb06', 'Architecture': 'x86_64', 'BlockDeviceMappings': [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': datetime.datetime(2020, 3, 13, 1, 31, 17, tzinfo=tzlocal()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-004c51e13f57602c1'}}], 'ClientToken': '', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'IamInstanceProfile': {'Arn': 'arn:aws:iam::457288958696:instance-profile/resource_sync_profile', 'Id': 'AIPAWU6ELYLUC5UTWOPA5'}, 'NetworkInterfaces': [{'Association': {'IpOwnerId': '457288958696', 'PublicDnsName': 'ec2-3-20-168-179.us-east-2.compute.amazonaws.com', 'PublicIp': '3.20.168.179'}, 'Attachment': {'AttachTime': datetime.datetime(2020, 3, 13, 1, 31, 16, tzinfo=tzlocal()), 'AttachmentId': 'eni-attach-058fe5ac16dbe06f3', 'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached'}, 'Description': '', 'Groups': [{'GroupName': 'tweener-web-api-dev', 'GroupId': 'sg-045e8e17e8e3e9b13'}], 'Ipv6Addresses': [], 'MacAddress': '02:8b:77:a5:2e:04', 'NetworkInterfaceId': 'eni-0fba9eef56c045076', 'OwnerId': '457288958696', 'PrivateDnsName': 'ip-172-28-0-103.us-east-2.compute.internal', 'PrivateIpAddress': '172.28.0.103', 'PrivateIpAddresses': [{'Association': {'IpOwnerId': '457288958696', 'PublicDnsName': 'ec2-3-20-168-179.us-east-2.compute.amazonaws.com', 'PublicIp': '3.20.168.179'}, 'Primary': True, 'PrivateDnsName': 'ip-172-28-0-103.us-east-2.compute.internal', 'PrivateIpAddress': '172.28.0.103'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-03cdd67c2ad14cd20', 'VpcId': 'vpc-018baf63faed4eb06', 'InterfaceType': 'interface'}], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'tweener-web-api-dev', 'GroupId': 'sg-045e8e17e8e3e9b13'}], 'SourceDestCheck': True, 'Tags': [{'Key': 'Stage', 'Value': 'dev'}, {'Key': 'Name', 'Value': 'web-api'}, {'Key': 'Namespace', 'Value': 'ninja-tools'}], 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 2}, 'CapacityReservationSpecification': {'CapacityReservationPreference': 'open'}, 'HibernationOptions': {'Configured': False}, 'MetadataOptions': {'State': 'applied', 'HttpTokens': 'optional', 'HttpPutResponseHopLimit': 1, 'HttpEndpoint': 'enabled'}}], 'OwnerId': '457288958696', 'ReservationId': 'r-024d520c4a257857a'}], 'ResponseMetadata': {'RequestId': '78dd8b23-180c-4de1-8bb2-91d003e8363a', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8', 'content-length': '7814', 'vary': 'accept-encoding', 'date': 'Fri, 13 Mar 2020 23:29:12 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment