aws_utils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. its licensors.
  4. For complete copyright and license terms please see the LICENSE at the root of this
  5. distribution (the "License"). All use of this software is governed by the License,
  6. or, if provided, by the license below or the license accompanying this file. Do not
  7. remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. """
  10. import boto3
  11. import logging
  12. logger = logging.getLogger(__name__)
  13. logging.getLogger('boto3').setLevel(logging.WARNING)
  14. logging.getLogger('botocore').setLevel(logging.WARNING)
  15. logging.getLogger('nose').setLevel(logging.WARNING)
  16. class AwsUtils:
  17. def __init__(self, arn: str, session_name: str, region_name: str):
  18. local_session = boto3.Session(profile_name='default')
  19. local_sts_client = local_session.client('sts')
  20. self._local_account_id = local_sts_client.get_caller_identity()["Account"]
  21. logger.info(f'Local Account Id: {self._local_account_id}')
  22. response = local_sts_client.assume_role(RoleArn=arn, RoleSessionName=session_name)
  23. self._assume_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
  24. aws_secret_access_key=response['Credentials']['SecretAccessKey'],
  25. aws_session_token=response['Credentials']['SessionToken'],
  26. region_name=region_name)
  27. assume_sts_client = self._assume_session.client('sts')
  28. assume_account_id = assume_sts_client.get_caller_identity()["Account"]
  29. logger.info(f'Assume Account Id: {assume_account_id}')
  30. self._assume_account_id = assume_account_id
  31. def client(self, service: str):
  32. """
  33. Get the client for a specific AWS service from configured session
  34. :return: Client for the AWS service.
  35. """
  36. return self._assume_session.client(service)
  37. def resource(self, service: str):
  38. """
  39. Get the resource for a specific AWS service from configured session
  40. :return: Client for the AWS service.
  41. """
  42. return self._assume_session.resource(service)
  43. def assume_session(self):
  44. return self._assume_session
  45. def local_account_id(self):
  46. return self._local_account_id
  47. def assume_account_id(self):
  48. return self._assume_account_id
  49. def destroy(self) -> None:
  50. """
  51. clears stored session
  52. """
  53. self._assume_session = None