Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions ansible_library/modules/ec2_asg_facts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/python

import re
from operator import itemgetter
try:
import boto.ec2
import boto.ec2.autoscale
import boto.ec2.elb
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False


def list_asgs(connections, module):
asg_names = []
if module.params.get("name"):
asg_names.append(module.params.get("name"))
else:
asg_names = module.params.get("names")

sort_order = module.params.get("sort_order")
if not asg_names:
names_prefix = module.params.get("startswith")
names_suffix = module.params.get("endswith")

try:
all_asgs = connections['asg'].get_all_groups(names=asg_names)
except BotoServerError as e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))

if len(all_asgs) <= 0:
module.exit_json(changed=False, asgs=None)

asgs_array = []
for asg in all_asgs:
asg_info = {
'name': asg.name,
'load_balancers': asg.load_balancers,
'min_size': asg.min_size,
'max_size': asg.max_size,
'desired_capacity': asg.desired_capacity,
'health_check_period': asg.health_check_period,
'health_check_type': asg.health_check_type,
'instances': [i.instance_id for i in asg.instances],
'instance_count': len(asg.instances) or 0,
'availability_zones': asg.availability_zones,
'termination_policies': asg.termination_policies,
'vpc_zone_identifier': asg.vpc_zone_identifier,
'launch_config': asg.launch_config_name,
}

# if searching using startswith and endswith (i.e. no explicit names)
if not asg_names:
# if both prefix and suffix are specified return items that matches both conditions
#name_pattern = '^{}{}$'.format(names_prefix or '', names_suffix or '')
name_pattern = ''
if names_prefix:
name_pattern += '^' + names_prefix
if names_suffix:
name_pattern += names_suffix + '$'
if ( re.match(name_pattern, asg.name) ):
asgs_array.append(asg_info)
else:
# if searching via explicit asg names, just append the string as the boto library has
# filtered it for us already
asgs_array.append(asg_info)

module.exit_json( asgs=sorted(asgs_array,
key=itemgetter('name'),
reverse=(sort_order!='ascending')) )


def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
name={'default': None, 'type': 'str'},
names={'default': None, 'type': 'list'},
startswith={'default': None, 'type': 'str'},
endswith={'default': None, 'type':'str'},
region={'default': 'us-east-1', 'type':'str'},
sort_order={'required': False, 'default': 'ascending', 'choices':['ascending', 'descending'] },
)
)

module = AnsibleModule(argument_spec=argument_spec)

if not HAS_BOTO:
module.fail_json(msg='boto required for this module')

region, ec2_url, aws_connect_params = get_aws_connection_info(module)
connections = {}
if not region:
region = module.params.get("region")
if region:
try:
connections['asg'] = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params)
connections['elb'] = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError), e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")

list_asgs(connections, module)

from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *

if __name__ == '__main__':
main()
File renamed without changes.
File renamed without changes.
40 changes: 40 additions & 0 deletions python/ec2_get_tag
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#! /usr/bin/env python

import boto
import urllib2
import time
import sys

def expand_compound_tags(compact_tags):
expanded_tags = dict()
for tag_name,tag_value in compact_tags.iteritems():
if ',' in tag_value:
tag_values = tag_value.split(',')
for value_element in tag_values:
if ':' in value_element:
new_tag_name = "{}_{}".format(tag_name, value_element.split(':')[0])
expanded_tags.update({ new_tag_name: value_element.split(':')[1] })

expanded_tags.update({tag_name: ','.join(tag_values)})
else:
expanded_tags.update({tag_name:tag_value})
return expanded_tags

required_tag_names = sys.argv[1:]

instance_id = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read()

ec2 = boto.connect_ec2()
try:
instance = ec2.get_only_instances(instance_ids = instance_id)[0]
tags = instance.tags
except boto.exception.EC2ResponseError:
sys.exit(2)

required_tag_names = [t.lower() for t in required_tag_names]
expanded_tags = expand_compound_tags(tags)

matching_tags = dict({k:v for k,v in expanded_tags.iteritems() if k.lower() in required_tag_names})

print ' '.join(["{}={}".format(k,v) for k,v in matching_tags.iteritems()])
#print matching_tags
34 changes: 34 additions & 0 deletions python/ec2_tags_json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python

import boto
import sys
import json

def parse_tag_value(value):
if ',' in value:
values = value.split(',')
# parsed_values = [{subv.split(':')[0]:subv.split(':')[1]} if ':' in subv else subv for subv in values]
parsed_values = [{subv.split(':')[0]:subv.split(':')[1]} if ':' in subv else subv for subv in values]
return parsed_values
else:
return ({value.split(':')[0]:value.split(':')[1]} if ':' in value else value)

instance_id = sys.argv[1]
required_tag_names = sys.argv[2:]

ec2 = boto.connect_ec2()
try:
instance = ec2.get_only_instances(instance_ids = instance_id)[0]
tags = instance.tags
except boto.exception.EC2ResponseError:
sys.exit(2)

required_tag_names = [t.lower() for t in required_tag_names]
#matching_tags = dict({k:v for k,v in tags.iteritems() if k.lower() in required_tag_names
matching_tags = dict()
for k,v in tags.iteritems():
if k.lower() in required_tag_names:
v = parse_tag_value(v)
matching_tags.update({k:v})

print json.dumps(matching_tags)
File renamed without changes.
71 changes: 71 additions & 0 deletions python/roman.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#!/usr/local/bin/python

import sys

ROMAN_PREFIX = {
10000: 'M',
5000: 'M',
1000: 'C',
500: 'C',
100: 'X',
50: 'X',
10: 'I',
5: 'I',
1: 'I',
}

ROMAN_DIGIT = {
10000: '??',
5000: '?',
1000: 'M',
500: 'D',
100: 'C',
50: 'L',
10: 'X',
5: 'V',
1: 'I',
}

def get_roman_digit(number, power_of_ten):
if power_of_ten < 1: return
(quotient, remainder) = divmod(number, power_of_ten)

if quotient >= 5:
# do something including the half power_of_ten
if quotient == 9:
sys.stdout.write('%s%s' % (ROMAN_PREFIX[(power_of_ten*10)], ROMAN_DIGIT[(power_of_ten*10)]))
else:
sys.stdout.write('%s' % ROMAN_DIGIT[(power_of_ten*5)])
remaining = quotient - 5
sys.stdout.write('%s' % ROMAN_DIGIT[power_of_ten] * remaining)
else:
if quotient == 4:
if power_of_ten == 1000:
sys.stdout.write('%s' % ROMAN_DIGIT[power_of_ten] * quotient)
else:
sys.stdout.write('%s%s' % (ROMAN_PREFIX[(power_of_ten*10)], ROMAN_DIGIT[(power_of_ten*5)] ))
else:
sys.stdout.write('%s' % ROMAN_DIGIT[power_of_ten] * quotient)

get_roman_digit(remainder, power_of_ten/10)

def get_largest_power_of_ten(number):
if number < 10:
return 0
for i in range(4,0,-1):
if (0 < number / (10**i) < 10):
return 10**i

def main(argv):
number_to_convert = int(argv[0])
if number_to_convert >= 5000:
print "Can't convert number bigger than 5000 - Romans are kinda limited"
return
power_of_ten = get_largest_power_of_ten(number_to_convert)
print "power of then is {}".format(power_of_ten)
get_roman_digit(number_to_convert, power_of_ten)
print ""

if __name__ == "__main__":
main(sys.argv[1:])

68 changes: 0 additions & 68 deletions roman.py

This file was deleted.

Loading