Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.84 KB | None | 0 0
  1. with open(output_file, 'a', newline='') as f:
  2. writer = csv.writer(f)
  3. writer.writerow(row)
  4. #print(row)
  5. #sys.exit()
  6. #pass
  7.  
  8. #!/usr/bin/env python
  9.  
  10. import boto3
  11. import botocore
  12. import argparse
  13. import csv
  14. import logging
  15. import datetime
  16. import click
  17. import yaml
  18. import os
  19. import time
  20. import sys
  21.  
  22. logging.basicConfig(filename='tag-export.log', filemode='a', format='%(levelname)s - %(message)s')
  23. logger = logging.getLogger()
  24. logger.setLevel(logging.INFO)
  25.  
  26. targetaccount = 'allaccounts'
  27.  
  28. # GLOBAL SESSION
  29. sts = boto3.client('sts')
  30.  
  31. def aws_session(account_id, session_name, role_name):
  32. """
  33. Function that creates the boto3 session by assuming a cross account role
  34.  
  35. Uses boto3 to make calls to the STS API
  36.  
  37.  
  38. def account_name(session):
  39. """
  40. Function that resolves the account name (alias) to make output human friendly
  41.  
  42. Uses boto3 to make calls to the IAM API
  43.  
  44. def get_instances(filters=[]):
  45. reservations = {}
  46. try:
  47. reservations = ec2.describe_instances(
  48. Filters=filters
  49. )
  50. except botocore.exceptions.ClientError as e:
  51. print(e.response['Error']['Message'])
  52.  
  53. instances = []
  54. for reservation in reservations.get('Reservations', []):
  55. for instance in reservation.get('Instances', []):
  56. instances.append(instance)
  57. return instances
  58.  
  59. @click.command()
  60. @click.option('--config_file', required=True, prompt=True, default=lambda: str(os.getcwd()) + '/config.yml', show_default='config.yml')
  61.  
  62. def main(config_file):
  63. try:
  64. with open(config_file, 'r') as ymlfile:
  65. config = yaml.load(ymlfile)
  66. ymlfile.close()
  67. except Exception as e:
  68. logger.error('Unable to open config file: ' + str(e))
  69. exit
  70.  
  71. # globals
  72. if 'accounts' in config:
  73. accounts = config['accounts']
  74. if 'role_name' in config:
  75. role_name = config['role_name']
  76.  
  77.  
  78. tag_set = []
  79. for account in accounts:
  80. logger.info('dispatching session call for account: ' + str(account) )
  81. if str(account) == str(config['sourceaccount']):
  82. session = boto3.Session(region_name=config['region'])
  83. else:
  84. session = aws_session(account_id=str(account), session_name='cross-account-assume-role', role_name = role_name)
  85. if session:
  86. AccountName = account_name(session)
  87. logger.info('Working on account: ' + AccountName)
  88. print('Working on gathering tags and sorting them.....Wait...: ')
  89. global ec2
  90. ec2 = session.client('ec2', region_name='ap-southeast-2')
  91. output_file = "{}-tags.csv".format(targetaccount)
  92. instances = get_instances()
  93.  
  94. for instance in instances:
  95. for tag in instance.get('Tags', []):
  96. if tag.get('Key'):
  97. tag_set.append(tag.get('Key'))
  98. tag_set = sorted(list(set(tag_set)))
  99. else:
  100. print("did not get session")
  101. sys.exit()
  102.  
  103. if tag_set:
  104. print ('Tag Gathering Completed! Moving to each account to get Tag Values')
  105. #sys.exit()
  106.  
  107. with open(output_file, 'a', newline='') as csvfile:
  108. fieldnames = ['Account'] + ['InstanceId'] + tag_set
  109. writer = csv.DictWriter(csvfile, fieldnames=fieldnames,extrasaction='ignore')
  110. writer.writeheader()
  111.  
  112. for account in accounts:
  113. if str(account) == str(config['sourceaccount']):
  114. session = boto3.Session(region_name=config['region'])
  115. else:
  116. session = aws_session(account_id=str(account), session_name='cross-account-assume-role', role_name = role_name)
  117.  
  118. if session:
  119. AccountName = account_name(session)
  120. logger.info('Working on account: ' + AccountName)
  121. print('Working on account: ' + AccountName + '....')
  122. instances = get_instances()
  123. for instance in instances:
  124. row = {}
  125. row['Account'] = AccountName
  126. row['InstanceId'] = instance.get('InstanceId')
  127. #print (row)
  128. #sys.exit()
  129. for tag in instance.get('Tags', []):
  130. for vtag in tag_set:
  131. if vtag == tag.get('Key'):
  132. #print (tag.get('Key'))
  133. #print ('vtag=' + vtag)
  134. #sys.exit()
  135. row[tag.get('Key')] = tag.get('Value')
  136. #print(row)
  137. with open(output_file, 'a', newline='') as f:
  138. writer = csv.writer(f)
  139. writer.writerow(row)
  140. #print(row)
  141. #sys.exit()
  142. #pass
  143. else:
  144. print("did not get session")
  145.  
  146.  
  147. if __name__ == "__main__":
  148. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement