aws_utils.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. Copyright (c) Contributors to the Open 3D Engine Project.
  3. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. SPDX-License-Identifier: Apache-2.0 OR MIT
  5. """
  6. import boto3
  7. import logging
  8. logger = logging.getLogger(__name__)
  9. logging.getLogger('boto3').setLevel(logging.WARNING)
  10. logging.getLogger('botocore').setLevel(logging.WARNING)
  11. logging.getLogger('nose').setLevel(logging.WARNING)
  12. class AwsUtils:
  13. def __init__(self, arn: str, session_name: str, region_name: str):
  14. local_session = boto3.Session()
  15. local_sts_client = local_session.client('sts')
  16. self._local_account_id = local_sts_client.get_caller_identity()["Account"]
  17. logger.info(f'Local Account Id: {self._local_account_id}')
  18. response = local_sts_client.assume_role(RoleArn=arn, RoleSessionName=session_name)
  19. self._assume_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
  20. aws_secret_access_key=response['Credentials']['SecretAccessKey'],
  21. aws_session_token=response['Credentials']['SessionToken'],
  22. region_name=region_name)
  23. assume_sts_client = self._assume_session.client('sts')
  24. assume_account_id = assume_sts_client.get_caller_identity()["Account"]
  25. logger.info(f'Assume Account Id: {assume_account_id}')
  26. self._assume_account_id = assume_account_id
  27. def client(self, service: str):
  28. """
  29. Get the client for a specific AWS service from configured session
  30. :return: Client for the AWS service.
  31. """
  32. return self._assume_session.client(service)
  33. def resource(self, service: str):
  34. """
  35. Get the resource for a specific AWS service from configured session
  36. :return: Client for the AWS service.
  37. """
  38. return self._assume_session.resource(service)
  39. def assume_session(self):
  40. return self._assume_session
  41. def local_account_id(self):
  42. return self._local_account_id
  43. def assume_account_id(self):
  44. return self._assume_account_id
  45. def destroy(self) -> None:
  46. """
  47. clears stored session
  48. """
  49. self._assume_session = None