Guest User

Untitled

a guest
Jan 16th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import gzip
  4. import io
  5. import boto3
  6. import json
  7. from botocore.exceptions import ClientError
  8.  
  9. class STS(object):
  10. """
  11. Sts: Object to manage the persistence of authentication over multiple
  12. runs of an automation script. When testing a script this will
  13. save having to input an MFA token multiple times when using
  14. an account that requires it.
  15. """
  16.  
  17. def __init__(self, role_arn, temporary_credentials_path, mfa_arn):
  18. self.temp_creds_path = temporary_credentials_path
  19. self.mfa_arn = mfa_arn
  20. self.role_arn = role_arn
  21.  
  22. def get_temporary_session(self):
  23. """
  24. get_temporary_session: checks the temporary credentials stored
  25. on disk, if they fail to authenticate re-attempt to assume
  26. the role. The credentials requested last 15 minutes. For
  27. debugging purposes these can be persisted for up to an hour.
  28. """
  29.  
  30. try:
  31. with open(self.temp_creds_path, 'r') as tmp_creds:
  32. credentials = json.loads(tmp_creds.read())
  33. client = boto3.client(
  34. 'sts',
  35. aws_access_key_id=credentials['AccessKeyId'],
  36. aws_secret_access_key=credentials['SecretAccessKey'],
  37. aws_session_token=credentials['SessionToken']
  38. )
  39. _ = client.get_caller_identity()['Account']
  40. except (IOError, ClientError, FileNotFoundError):
  41. response = boto3.client('sts').assume_role(
  42. DurationSeconds=900,
  43. RoleArn=self.role_arn,
  44. RoleSessionName='sts-assume-role-script',
  45. SerialNumber=self.mfa_arn,
  46.  
  47. TokenCode=input('MFA_Token:')
  48. )
  49. credentials = response['Credentials']
  50. with open(self.temp_creds_path, 'w+') as tmp_creds:
  51. tmp_creds.write(json.dumps({
  52. 'AccessKeyId': credentials['AccessKeyId'],
  53. 'SecretAccessKey': credentials['SecretAccessKey'],
  54. 'SessionToken': credentials['SessionToken']}))
  55.  
  56. return boto3.Session(
  57. aws_access_key_id=credentials['AccessKeyId'],
  58. aws_secret_access_key=credentials['SecretAccessKey'],
  59. aws_session_token=credentials['SessionToken'],
  60. )
  61. # -----------
  62. BUCKET_NAME = "cdl.t1c.dev"
  63.  
  64.  
  65. def main():
  66. sts = STS("arn:aws:iam::246898065194:role/r_data-engineer", "/tmp/aws_sts_creds.json",
  67. "arn:aws:iam::627443353872:mfa/__YOUR_USER__@central.tech")
  68. boto3.setup_default_session(profile_name='cg-aws-operation')
  69. session = sts.get_temporary_session()
  70. s3 = session.resource("s3")
  71. for bucket in s3.buckets.all():
  72. print(bucket.name)
  73.  
  74. if __name__ == "__main__":
  75. main()
Add Comment
Please, Sign In to add comment