MindKooper

Untitled

Jun 18th, 2019
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import boto3
  3.  
  4. ec2 = boto3.client('ec2', region_name='us-west-2')
  5. sts_client = boto3.client('sts')
  6.  
  7. # Call the assume_role method of the STSConnection object and pass the role
  8. # ARN and a role session name.
  9. assumed_role_object = sts_client.assume_role(
  10. RoleArn="arn:aws:iam::369874303498:role/cl/app/crossaccount/amimanager/jenkins_role_policy",
  11. RoleSessionName="AssumeRoleSession1"
  12. )
  13. credentials = assumed_role_object['Credentials']
  14. autoscaling = boto3.client('autoscaling',
  15. aws_access_key_id=credentials['AccessKeyId'],
  16. aws_secret_access_key=credentials['SecretAccessKey'],
  17. aws_session_token=credentials['SessionToken'],
  18. region_name='us-west-2')
  19. ec2 = boto3.client('ec2',
  20. aws_access_key_id=credentials['AccessKeyId'],
  21. aws_secret_access_key=credentials['SecretAccessKey'],
  22. aws_session_token=credentials['SessionToken'],
  23. region_name='us-west-2')
  24.  
  25.  
  26. def get_asg_instances(asgs):
  27. asg_instances = []
  28. for asg in asgs['AutoScalingGroups']:
  29. for instance in asg['Instances']:
  30. asg_instances.append(instance['InstanceId'])
  31. return asg_instances
  32.  
  33.  
  34. def get_asg_instance_info(asgi, option=False):
  35. result = []
  36. for reservation in asgi.get('Reservations'):
  37. for instance in reservation.get('Instances'):
  38. if (option == False):
  39. result.append({'PrivateDnsName': instance['PrivateDnsName'],
  40. 'PrivateIpAddress': instance['PrivateIpAddress']})
  41. else:
  42. if (instance.get(option) is not None):
  43. result.append({option: instance.get(option)})
  44. else:
  45. print("Debug info: Instance doesn't have an PrivateIpAddress")
  46. return result
  47. # For export as a function
  48.  
  49.  
  50. def get_private_info(endpoint, option):
  51. asgs = autoscaling.describe_auto_scaling_groups(
  52. AutoScalingGroupNames=[endpoint])
  53. asgi_ids = get_asg_instances(asgs)
  54. asgi = ec2.describe_instances(InstanceIds=asgi_ids)
  55. test_data = get_asg_instance_info(asgi, option)
  56. return test_data
  57.  
  58.  
  59. # As a separate script
  60. if __name__ == "__main__":
  61. print('main')
  62. # asgs = autoscaling.describe_auto_scaling_groups(
  63. # AutoScalingGroupNames=[AUTO_SCALING_GROUP])
  64. # asgi_ids = get_asg_instances(asgs)
  65. # asgi = ec2.describe_instances(InstanceIds=asgi_ids)
  66. # test_data = get_asg_instance_info(asgi)
Add Comment
Please, Sign In to add comment