You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.0 KiB

  1. #!/usr/bin/env python
  2. import boto3
  3. import os
  4. import argparse
  5. import json
  6. class SearchEC2Tags(object):
  7. def __init__(self):
  8. self.parse_args()
  9. if self.args.list:
  10. self.search_tags()
  11. if self.args.host:
  12. data = {}
  13. print json.dumps(data, indent=2)
  14. def parse_args(self):
  15. ##Check if VPC_VISIBILITY is set, if not default to private
  16. if "VPC_VISIBILITY" in os.environ:
  17. self.vpc_visibility = os.environ['VPC_VISIBILITY']
  18. else:
  19. self.vpc_visibility = "private"
  20. ##Support --list and --host flags. We largely ignore the host one.
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument('--list', action='store_true', default=False, help='List instances')
  23. parser.add_argument('--host', action='store_true', help='Get all the variables about a specific instance')
  24. self.args = parser.parse_args()
  25. def search_tags(self):
  26. hosts = {}
  27. hosts['_meta'] = { 'hostvars': {} }
  28. ##Search ec2 three times to find nodes of each group type. Relies on kubespray-role key/value.
  29. for group in ["kube-master", "kube-node", "etcd"]:
  30. hosts[group] = []
  31. tag_key = "kubespray-role"
  32. tag_value = ["*"+group+"*"]
  33. region = os.environ['REGION']
  34. ec2 = boto3.resource('ec2', region)
  35. instances = ec2.instances.filter(Filters=[{'Name': 'tag:'+tag_key, 'Values': tag_value}, {'Name': 'instance-state-name', 'Values': ['running']}])
  36. for instance in instances:
  37. if self.vpc_visibility == "public":
  38. hosts[group].append(instance.public_dns_name)
  39. hosts['_meta']['hostvars'][instance.public_dns_name] = {
  40. 'ansible_ssh_host': instance.public_ip_address
  41. }
  42. else:
  43. hosts[group].append(instance.private_dns_name)
  44. hosts['_meta']['hostvars'][instance.private_dns_name] = {
  45. 'ansible_ssh_host': instance.private_ip_address
  46. }
  47. hosts['k8s-cluster'] = {'children':['kube-master', 'kube-node']}
  48. print json.dumps(hosts, sort_keys=True, indent=2)
  49. SearchEC2Tags()