Created
January 17, 2016 12:35
-
-
Save metajungle/ce3ca99ae04b774aec10 to your computer and use it in GitHub Desktop.
Augments response from Ansible EC2 dynamic inventory with additional non-tagged host groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Augments response from Ansible EC2 dynamic inventory with additional | |
non-tagged host groups | |
To run: | |
$ (virtualenv) python ec2-augment.py --list | |
Tested with Python 2.7.10 | |
""" | |
__author__ = "Jakob Henriksson" | |
__email__ = "jakob@metajungle.net" | |
__version__ = "1.0.0" | |
import json | |
import re | |
import subprocess | |
import sys | |
# replaces underscores with dashes in host group names if True, | |
# and not if False | |
replace_underscore_in_groups = True | |
# ec2.py script | |
ec2_py_script = "/home/user/bin/ec2.py" | |
# tag key to convert | |
# for example: if ec2_tag_key = "group", then | |
# will for an existing host group "tag_group_[x]" add | |
# the following group "[x]" | |
ec2_tag_key = "group" | |
def main(argv): | |
""" | |
Augments response from Ansible EC2 dynamic inventory with additional | |
non-tagged host groups | |
""" | |
# result | |
json_augmented = {} | |
try: | |
# execute command | |
stdout = subprocess.check_output([ec2_py_script] + sys.argv[1:]) | |
value = stdout.decode('ascii', 'ignore') | |
# parse output as JSON | |
_json = json.loads(value) | |
# construct tag prefix | |
prefix = "tag_%s_" % ec2_tag_key | |
for key, value in _json.items(): | |
# look for a match | |
if bool(re.match(prefix, key, re.I)): | |
# construct group name to add | |
group_name = key[len(prefix):] | |
# optionally replace underscores | |
if replace_underscore_in_groups: | |
group_name = group_name.replace("_", "-") | |
# propagate value | |
json_augmented[key] = value | |
# augment result | |
json_augmented[group_name] = value | |
else: | |
# propagate value | |
json_augmented[key] = value | |
except: | |
# default empty result | |
json_augmented = { | |
"_meta": { | |
"hostvars": {} | |
} | |
} | |
# print agumented JSON | |
print(json.dumps(json_augmented, indent=4)) | |
if __name__ == "__main__": | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment