Skip to content

Instantly share code, notes, and snippets.

@WinstonN
Created January 30, 2020 05:58
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 WinstonN/0199cff71acba66e3b95285cf9d8d32a to your computer and use it in GitHub Desktop.
Save WinstonN/0199cff71acba66e3b95285cf9d8d32a to your computer and use it in GitHub Desktop.
def get_hosts_from_ec2(environment, filter):
"""
Create hosts pool, containing available hosts to be targeted
"""
if environment not in environments:
raise Exception(f"Environment must be one of {environments}")
# get ip information
get_local_ip_information()
# print info
print(f"Targeting environment [{c(environment, white, attrs=['bold'])}] with filter '{c(filter, white, attrs=['bold'])}'")
boto3.setup_default_session(profile_name=f"{company}-{environment}")
ec2 = boto3.resource('ec2')
# setup filters
filters = [
{'Name': 'instance-state-name', 'Values': ['running']}, # only get running instances
{'Name': 'tag:Name', 'Values': ['*{query}*'.format(query=filter)]},
]
# make api call to EC2
instances = ec2.instances.filter(Filters=filters)
return instances
def extract_instances_information(context, environment, filter, tags=None):
"""
Get information from instances and create hosts pool
"""
default_attributes = [
'Name',
'private_ip_address',
'public_ip_address',
'instance_type'
]
attributes = default_attributes if tags is None else tags.split(',')
# get instances with filter
instances = get_hosts_from_ec2(environment, filter)
instance_name = None
if len(attributes) is 1 and 'private_ip_address' in attributes:
results = []
else:
results = {}
for instance in instances:
# gather data from tags
for tag in instance.tags:
# set other attributes
if tag['Key'] in attributes:
if tag['Key'] == 'Name':
instance_name=tag['Value']
instance_id=getattr(instance, 'id')
instance_name = f'{instance_name}[{instance_id}]'
# print(tag['Value'])
results.update({instance_name: {tag['Key']: tag['Value']}})
# gather data from attributes
# figure out what properties the instance object has
# print(instance.__dict__.keys())
instance_properties = [i for i in dir(instance) if not callable(i)]
# print(instance_properties)
for attribute in attributes:
if attribute in instance_properties:
if isinstance(results, list):
results.append(getattr(instance, attribute))
else:
results[instance_name].update({attribute: getattr(instance, attribute)})
# print hosts information
print(f"Information for attributes: {c(attributes, white, attrs=['bold'])}")
number_of_hosts = len(results)
print(c(f"Found {number_of_hosts} host(s)", white, attrs=['bold']))
print(json.dumps(results, sort_keys=True, indent=4))
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment