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.

73 lines
2.4 KiB

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