aws_credentials.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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 configparser
  8. import logging
  9. import os
  10. import pytest
  11. import typing
  12. logger = logging.getLogger(__name__)
  13. logging.getLogger('boto').setLevel(logging.CRITICAL)
  14. class AwsCredentials:
  15. def __init__(self, profile_name: str):
  16. self._profile_name = profile_name
  17. self._credentials_path = os.environ.get('AWS_SHARED_CREDENTIALS_FILE')
  18. if not self._credentials_path:
  19. # Home directory location varies based on the operating system, but is referred to using the environment
  20. # variables %UserProfile% in Windows and $HOME or ~ (tilde) in Unix-based systems.
  21. self._credentials_path = os.path.join(os.environ.get('UserProfile', os.path.expanduser('~')),
  22. '.aws', 'credentials')
  23. self._credentials_file_exists = os.path.exists(self._credentials_path)
  24. self._credentials = configparser.ConfigParser()
  25. self._credentials.read(self._credentials_path)
  26. def get_aws_credentials(self) -> typing.Tuple[str, str, str]:
  27. """
  28. Get aws credentials stored in the specific named profile.
  29. :return AWS credentials.
  30. """
  31. access_key_id = self._get_aws_credential_attribute_value('aws_access_key_id')
  32. secret_access_key = self._get_aws_credential_attribute_value('aws_secret_access_key')
  33. session_token = self._get_aws_credential_attribute_value('aws_session_token')
  34. return access_key_id, secret_access_key, session_token
  35. def set_aws_credentials_by_session(self, session: boto3.Session) -> None:
  36. """
  37. Set AWS credentials stored in the specific named profile using an assumed role session.
  38. :param session: assumed role session.
  39. """
  40. credentials = session.get_credentials().get_frozen_credentials()
  41. self.set_aws_credentials(credentials.access_key, credentials.secret_key, credentials.token)
  42. def set_aws_credentials(self, aws_access_key_id: str, aws_secret_access_key: str,
  43. aws_session_token: str) -> None:
  44. """
  45. Set AWS credentials stored in the specific named profile.
  46. :param aws_access_key_id: AWS access key id.
  47. :param aws_secret_access_key: AWS secrete access key.
  48. :param aws_session_token: AWS assumed role session.
  49. """
  50. self._set_aws_credential_attribute_value('aws_access_key_id', aws_access_key_id)
  51. self._set_aws_credential_attribute_value('aws_secret_access_key', aws_secret_access_key)
  52. self._set_aws_credential_attribute_value('aws_session_token', aws_session_token)
  53. if (len(self._credentials.sections()) == 0) and (not self._credentials_file_exists):
  54. os.remove(self._credentials_path)
  55. return
  56. credentials_file_dir = os.path.dirname(self._credentials_path)
  57. if not os.path.isdir(credentials_file_dir):
  58. os.makedirs(credentials_file_dir)
  59. with open(self._credentials_path, 'w+') as credential_file:
  60. self._credentials.write(credential_file)
  61. def _get_aws_credential_attribute_value(self, attribute_name: str) -> str:
  62. """
  63. Get the value of an AWS credential attribute stored in the specific named profile.
  64. :param attribute_name: Name of the AWS credential attribute.
  65. :return Value of the AWS credential attribute.
  66. """
  67. try:
  68. value = self._credentials.get(self._profile_name, attribute_name)
  69. except configparser.NoSectionError:
  70. # Named profile or key doesn't exist
  71. value = None
  72. except configparser.NoOptionError:
  73. # Named profile doesn't have the specified attribute
  74. value = None
  75. return value
  76. def _set_aws_credential_attribute_value(self, attribute_name: str, attribute_value: str) -> None:
  77. """
  78. Set the value of an AWS credential attribute stored in the specific named profile.
  79. :param attribute_name: Name of the AWS credential attribute.
  80. :param attribute_value: Value of the AWS credential attribute.
  81. """
  82. if self._profile_name not in self._credentials:
  83. self._credentials[self._profile_name] = {}
  84. if attribute_value is None:
  85. self._credentials.remove_option(self._profile_name, attribute_name)
  86. # Remove the named profile if it doesn't have any AWS credential attribute.
  87. if len(self._credentials[self._profile_name]) == 0:
  88. self._credentials.remove_section(self._profile_name)
  89. else:
  90. self._credentials[self._profile_name][attribute_name] = attribute_value