boto3-assist 0.14.0__py3-none-any.whl → 0.16.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ import os
2
+ from pathlib import Path
3
+ import configparser
4
+ from typing import Literal, Optional
5
+ from boto3_assist.utilities.serialization_utility import SerializableModel
6
+
7
+
8
+ class AWSConfigProfile(SerializableModel):
9
+ def __init__(
10
+ self, region: Optional[str] = "us-east-1", output: Optional[str] = "json"
11
+ ):
12
+
13
+ self.region: Optional[str] = region
14
+ self.output: Optional[str] = output
15
+
16
+ self.aws_access_key_id: Optional[str] = None
17
+ self.aws_secret_access_key: Optional[str] = None
18
+ self.aws_session_token: Optional[str] = None
19
+
20
+ self.sso_session: Optional[str] = None
21
+ self.sso_account_id: Optional[str] = None
22
+ self.sso_role_name: Optional[str] = None
23
+
24
+ self.credential_process: Optional[str] = None
25
+ self.credential_source: Optional[str] = None
26
+ self.role_arn: Optional[str] = None
27
+ self.source_profile: Optional[str] = None
28
+ self.external_id: Optional[str] = None
29
+ self.role_session_name: Optional[str] = None
30
+ self.duration_seconds: Optional[str] = None
31
+
32
+
33
+ class AWSConfigSSOSession(SerializableModel):
34
+ def __init__(
35
+ self,
36
+ sso_start_url: Optional[str] = None,
37
+ sso_region: Optional[str] = None,
38
+ sso_registration_scopes: Optional[str] = None,
39
+ ):
40
+ self.sso_start_url: Optional[str] = sso_start_url
41
+ self.sso_region: Optional[str] = sso_region
42
+ self.sso_registration_scopes: Optional[str] = sso_registration_scopes
43
+
44
+
45
+ class AWSConfig:
46
+ """
47
+ Performs Operations on an AWS Config
48
+ """
49
+
50
+ def __init__(self):
51
+ pass
52
+
53
+ def get_path(self) -> Path:
54
+ """
55
+ Returns the path to the AWS config file, honoring AWS_CONFIG_FILE
56
+ and falling back to ~/.aws/config (or %USERPROFILE%\.aws\config on Windows).
57
+ """
58
+ # 1) Check for explicit override
59
+ env_path = os.environ.get("AWS_CONFIG_FILE")
60
+ if env_path:
61
+ return Path(env_path).expanduser()
62
+
63
+ # 2) Default location
64
+ return os.path.join(Path.home(), ".aws", "config")
65
+
66
+ def path_exists(self) -> bool:
67
+ path = self.get_path()
68
+
69
+ return os.path.isfile(path)
70
+
71
+ def has_profile(self, profile_name: str) -> bool:
72
+ config = configparser.ConfigParser()
73
+ self.read_section(profile_name, config)
74
+ return profile_name in config.sections()
75
+
76
+ def upsert_profile(
77
+ self,
78
+ name: str,
79
+ profile: AWSConfigProfile,
80
+ config_path: Optional[str] = None,
81
+ ):
82
+ self.write_section(name, profile, config_path)
83
+
84
+ def upsert_sso_session(
85
+ self,
86
+ profile_name: str,
87
+ sso_session: AWSConfigSSOSession,
88
+ profile: AWSConfigProfile | None = None,
89
+ config_path: Optional[str] = None,
90
+ ):
91
+ """
92
+ Insert / Update the SSO Session block in the aws config
93
+ Args:
94
+ Name (str): Required. Specifies the profile name. This is the init key
95
+ which is added to the section for both sso-session and profile
96
+ e.g. [profile {profile_name}] or [sso-session {profile_name}]
97
+ sso_session (AWSConfigSSOSession): Defines the values written to this session block
98
+ profile (AWSConfigProfile): Defines the values written to the profile block. Typically
99
+ you will need a profile block along with a session block when using sso-session
100
+
101
+
102
+ As a general rule you will typically need to build the following:
103
+ [profile {profile-name}]
104
+ sso_session = {optionally-use-profile-name}
105
+ sso_account_id = {aws-acount-id}
106
+ sso_role_name = {sso-role}
107
+ region = {region}
108
+ output = {output}
109
+
110
+ [sso-session {profile-name}]
111
+ sso_start_url = {sso_start_url} e.g. https://account-alias.awsapps.com/start
112
+ sso_region = {region}
113
+ sso_registration_scopes = {scopes}
114
+
115
+ """
116
+
117
+ if not profile_name:
118
+ raise ValueError("Name is required")
119
+
120
+ self.write_section(profile_name, sso_session, config_path)
121
+
122
+ if profile:
123
+ self.write_section(profile_name, profile, config_path)
124
+
125
+ def write_section(
126
+ self,
127
+ profile_name: str | None,
128
+ section: AWSConfigProfile | AWSConfigSSOSession,
129
+ config_path: Optional[str] = None,
130
+ ):
131
+ config = configparser.ConfigParser()
132
+ path = config_path or self.get_path()
133
+
134
+ if self.path_exists():
135
+ config.read(path) # or any INI file path
136
+
137
+ section_key = ""
138
+
139
+ if profile_name.startswith("sso-session "):
140
+ profile_name = profile_name.replace("sso-session ", "")
141
+ if profile_name.startswith("profile "):
142
+ profile_name = profile_name.replace("profile ", "")
143
+
144
+ if isinstance(section, AWSConfigProfile):
145
+ if profile_name:
146
+ section_key = f"profile {profile_name}"
147
+ else:
148
+ section_key = "default"
149
+ elif isinstance(section, AWSConfigSSOSession):
150
+ section_key = f"sso-session {profile_name}"
151
+ else:
152
+ raise ValueError("Invalid section type")
153
+
154
+ config = self._write_section(section_key, section, config)
155
+
156
+ with open(path, "w", encoding="utf-8") as cfg_file:
157
+ config.write(cfg_file)
158
+
159
+ def _write_section(
160
+ self,
161
+ section_key: str,
162
+ section: AWSConfigProfile | AWSConfigSSOSession,
163
+ config: configparser.ConfigParser,
164
+ ) -> configparser.ConfigParser:
165
+
166
+ # always start with a "fresh" section
167
+ config[section_key] = {}
168
+
169
+ section_dictionary = section.to_dictionary()
170
+ for key, value in section_dictionary.items():
171
+ if value is not None:
172
+ config[section_key][key] = value
173
+
174
+ return config
175
+
176
+ def read_section(
177
+ self,
178
+ profile_name: Optional[str] = None,
179
+ config_path: Optional[str] = None,
180
+ section_type: Literal["profile", "sso-session"] = "profile",
181
+ ) -> configparser.SectionProxy:
182
+ config = configparser.ConfigParser()
183
+ if not config_path:
184
+ config_path = self.get_path()
185
+
186
+ if not os.path.isfile(config_path):
187
+ return config
188
+
189
+ config.read(config_path)
190
+ profile_ini = f"{section_type} {profile_name}"
191
+ if profile_ini in config:
192
+ profile = config[profile_ini]
193
+ return profile
194
+
195
+ if profile_name in config:
196
+ profile = config[profile_name]
197
+ return profile
198
+
199
+ return {}
@@ -41,6 +41,8 @@ class DynamoDB(DynamoDBConnection):
41
41
  aws_access_key_id: Optional[str] = None,
42
42
  aws_secret_access_key: Optional[str] = None,
43
43
  assume_role_arn: Optional[str] = None,
44
+ assume_role_chain: Optional[List[str]] = None,
45
+ assume_role_duration_seconds: Optional[int] = 3600,
44
46
  ) -> None:
45
47
  super().__init__(
46
48
  aws_profile=aws_profile,
@@ -49,6 +51,8 @@ class DynamoDB(DynamoDBConnection):
49
51
  aws_access_key_id=aws_access_key_id,
50
52
  aws_secret_access_key=aws_secret_access_key,
51
53
  assume_role_arn=assume_role_arn,
54
+ assume_role_chain=assume_role_chain,
55
+ assume_role_duration_seconds=assume_role_duration_seconds,
52
56
  )
53
57
  self.helpers: DynamoDBHelpers = DynamoDBHelpers()
54
58
  self.log_dynamodb_item_size = (
@@ -3,3 +3,5 @@
3
3
  1. Unable to locate credentials. You can configure credentials by running "aws configure".
4
4
 
5
5
  - out of the blue, this started happening
6
+ - depending on how you are connecting boto3 may require a credentials file
7
+ - running "aws configure" and simply puttting in some garbage may fix the issue.
@@ -4,8 +4,10 @@ Maintainers: Eric Wilson
4
4
  MIT License. See Project Root for the license information.
5
5
  """
6
6
 
7
+ import os
7
8
  import boto3
8
9
  from typing import Optional
10
+ from boto3_assist.aws_config import AWSConfig
9
11
 
10
12
 
11
13
  class SessionSetupMixin:
@@ -26,4 +28,43 @@ class SessionSetupMixin:
26
28
  aws_session_token=aws_session_token,
27
29
  )
28
30
  except Exception as e:
29
- raise RuntimeError(f"Failed to create boto3 session: {e}") from e
31
+
32
+ error_message = f"Failed to create boto3 session "
33
+ if "profile" in str(e).lower():
34
+ error_message += " due to a profile error "
35
+
36
+ error_message += f" with profile '{aws_profile}'."
37
+ config: AWSConfig = AWSConfig()
38
+ if not config.path_exists():
39
+ error_message += (
40
+ f" The AWS config file '{config.get_path()}' was not found. "
41
+ "Please ensure that the AWS CLI is installed and configured correctly. "
42
+ "You can install the AWS CLI by running 'pip install awscli' or 'pip install awscli --upgrade'. "
43
+ )
44
+
45
+ if (
46
+ os.getenv("HOME") == "/tmp"
47
+ or os.getenv("AWS_CONFIG_FILE") == "/tmp"
48
+ ):
49
+ error_message += (
50
+ f'The environment HOME path is set to {os.getenv("HOME")}. '
51
+ )
52
+ if os.getenv("AWS_CONFIG_FILE"):
53
+ error_message += (
54
+ f"The environment AWS_CONFIG_FILE is set to {os.getenv('AWS_CONFIG_FILE')}. "
55
+ "The AWS_CONFIG_FILE overrides the HOME directory and path. "
56
+ )
57
+
58
+ error_message += (
59
+ "If you are running this locally and expecting it to be in your users home "
60
+ "directory, you may need to set the HOME or AWS_CONFIG_FILE environment variable manually. "
61
+ "There could be other actions such as a Lambda environment resetting the path to /tmp. "
62
+ "If you are running in a GitHub Actions environment, "
63
+ "you may need to set the HOME or AWS_CONFIG_FILE environment variable to '/home/runner'. "
64
+ )
65
+ elif not config.has_profile(aws_profile):
66
+ error_message += f" The profile '{aws_profile}' was not found in the AWS config file in {config.get_path()}."
67
+
68
+ # check for the existence of the profile and the path to the profile
69
+
70
+ raise RuntimeError(error_message) from e
@@ -22,7 +22,7 @@ logger = Logger()
22
22
 
23
23
 
24
24
  class SerializableModel:
25
- """Library to Serialize object to a DynamoDB Format"""
25
+ """Library to Serialize object to a DynamoDB Format or other dictionary"""
26
26
 
27
27
  T = TypeVar("T", bound="SerializableModel")
28
28
 
@@ -47,9 +47,16 @@ class SerializableModel:
47
47
 
48
48
  return mapped
49
49
 
50
+ def dict(self) -> Dict[str, Any]:
51
+ """
52
+ Same as .to_dictionary
53
+
54
+ """
55
+ return self.to_dictionary()
56
+
50
57
  def to_dictionary(self) -> Dict[str, Any]:
51
58
  """
52
- Convert the object to a dictionary.
59
+ Convert the object to a dictionary. Same as .dict()
53
60
  """
54
61
  # return Serialization.convert_object_to_dict(self)
55
62
  return Serialization.to_dict(
boto3_assist/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = '0.14.0'
1
+ __version__ = '0.16.0'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: boto3_assist
3
- Version: 0.14.0
3
+ Version: 0.16.0
4
4
  Summary: Additional boto3 wrappers to make your life a little easier
5
5
  Author-email: Eric Wilson <boto3-assist@geekcafe.com>
6
6
  License-File: LICENSE-EXPLAINED.txt
@@ -1,11 +1,12 @@
1
1
  boto3_assist/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ boto3_assist/aws_config.py,sha256=hEIX1YihsXCqpM5ftbGmSuWySQoEUFgOQ9KXb3zmlK0,6557
2
3
  boto3_assist/boto3session.py,sha256=p4FKVSX5A-xNHdpRan8pgMoY4iIywNfwriyTfjQ-zTQ,2967
3
4
  boto3_assist/connection.py,sha256=tqsNGLouAzCiTdtm9JylDTA6IiYqaQQiHmY-kH2bksU,4905
4
5
  boto3_assist/connection_tracker.py,sha256=UgfR9RlvXf3A4ssMr3gDMpw89ka8mSRvJn4M34SzhbU,4378
5
6
  boto3_assist/http_status_codes.py,sha256=G0zRSWenwavYKETvDF9tNVUXQz3Ae2gXdBETYbjvJe8,3284
6
7
  boto3_assist/role_assumption_mixin.py,sha256=PMUU5yC2FUBjFD1UokVkRY3CPB5zTw85AhIB5BMtbc8,1031
7
- boto3_assist/session_setup_mixin.py,sha256=KgHOf560f2W_Qj04mnu4CiGHXAI_irjmQeEfhAJN3kA,865
8
- boto3_assist/version.py,sha256=4pkGIcN2HdoT4OEADiR3LUoE-VfT0mtYYKhwVWEwVMY,23
8
+ boto3_assist/session_setup_mixin.py,sha256=X-JQKyyaWNA8Z8kKgf2V2I5vsiLAH8udLTX_xepnsdQ,3140
9
+ boto3_assist/version.py,sha256=ZkVXSbnNkhhpmMRr5ur6FqBcUYuqHyK0KUV5Je_XFn8,23
9
10
  boto3_assist/aws_lambda/event_info.py,sha256=OkZ4WzuGaHEu_T8sB188KBgShAJhZpWASALKRGBOhMg,14648
10
11
  boto3_assist/aws_lambda/mock_context.py,sha256=LPjHP-3YSoY6iPl1kPqJDwSVf1zLNTcukUunDtYcbK0,116
11
12
  boto3_assist/cloudwatch/cloudwatch_connection.py,sha256=mnGWaLSQpHh5EeY7Ek_2o9JKHJxOELIYtQVMX1IaHn4,2480
@@ -18,7 +19,7 @@ boto3_assist/cognito/cognito_connection.py,sha256=deuXR3cNHz0mCYff2k0LfAvK--9Okq
18
19
  boto3_assist/cognito/cognito_utility.py,sha256=IVZAg58nHG1U7uxe7FsTYpqwwZiwwdIBGiVTZuLCFqg,18417
19
20
  boto3_assist/cognito/jwks_cache.py,sha256=1Y9r-YfQ8qrgZN5xYPvjUEEV0vthbdcPdAIaPbZP7kU,373
20
21
  boto3_assist/cognito/user.py,sha256=qc44qLx3gwq6q2zMxcPQze1EjeZwy5Kuav93vbe-4WU,820
21
- boto3_assist/dynamodb/dynamodb.py,sha256=8uzKaw9knqPvlkroQK5aMR-ASRxFwCCcMacm6wWpp8g,15757
22
+ boto3_assist/dynamodb/dynamodb.py,sha256=Xkt-dRFVqvlUkDf8P_h9VX91qfY9kLxNgpV8e-QUzbk,15992
22
23
  boto3_assist/dynamodb/dynamodb_connection.py,sha256=D4KmVpMpE0OuVOwW5g4JBWllUNkwy0hMXEGUiToAMBc,3608
23
24
  boto3_assist/dynamodb/dynamodb_helpers.py,sha256=RoRRqKjdwfC-2-gvlkLvCoNWhIoMrHm-68dkyhXI_Xk,12080
24
25
  boto3_assist/dynamodb/dynamodb_importer.py,sha256=nCKsyRQeMqDSf0Q5mQ_X_oVIg4PRnu0hcUzZnBli610,3471
@@ -31,7 +32,7 @@ boto3_assist/dynamodb/dynamodb_reindexer.py,sha256=bCj6KIU0fQOgjkkiq9yF51PFZZr4Y
31
32
  boto3_assist/dynamodb/dynamodb_reserved_words.py,sha256=p0irNBSqGe4rd2FwWQqbRJWrNr4svdbWiyIXmz9lj4c,1937
32
33
  boto3_assist/dynamodb/dynamodb_reserved_words.txt,sha256=rvctS63Cv3i9SHmPq2Unmj6RZyQ-OMqxUXsNhtbg1is,4136
33
34
  boto3_assist/dynamodb/readme.md,sha256=wNMzdRwk0qRV0kE88UUYnJos3pEK0HNjEIVkq2PATf8,1490
34
- boto3_assist/dynamodb/troubleshooting.md,sha256=uGpBaBUt_MyzjzwFOLOe0udTgcvaOpiTFxfj7ilLNkM,136
35
+ boto3_assist/dynamodb/troubleshooting.md,sha256=Wa2SlH7_5UDz_fffg1h8b9ua9YG7l65bZU22UltPFio,292
35
36
  boto3_assist/ec2/ec2_connection.py,sha256=IrtaidH6_SF5l3OeNehRsTlC-sX7EURVqcO-U6P6ff8,1318
36
37
  boto3_assist/environment_services/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
37
38
  boto3_assist/environment_services/environment_loader.py,sha256=1uVLqSPQriUWazGXpxPJBLveGL8rLZaT5ZsciqqjVek,3979
@@ -53,10 +54,10 @@ boto3_assist/utilities/file_operations.py,sha256=IYhJkh8wUPMvGnyDRRa9yOCDdHN9wR3
53
54
  boto3_assist/utilities/http_utility.py,sha256=_K39Fq0V4QcgklAWctUktuMjqXDTwgMld77IOUfR2zc,1282
54
55
  boto3_assist/utilities/logging_utility.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
55
56
  boto3_assist/utilities/numbers_utility.py,sha256=wzv9d0uXT_2_ZHHio7LBzibwxPqhGpvbq9HinrVn_4A,10160
56
- boto3_assist/utilities/serialization_utility.py,sha256=nieqW9b71Dr0X2HPsNmCei6zoIbsPRl9fDAigBQkaUg,21730
57
+ boto3_assist/utilities/serialization_utility.py,sha256=_soAHu2Ym6SVwMBafMPcP4t9QwtxVC03MP0cm0L3A4g,21897
57
58
  boto3_assist/utilities/string_utility.py,sha256=0ChxbuT37xdG4y3cKzbNTHk4T3fl8lNMdOT7L5aJBQk,10382
58
- boto3_assist-0.14.0.dist-info/METADATA,sha256=p5_nuSMuOn99SxTVRdVG98y139Z2poxNjaVOL3Oj0WA,2875
59
- boto3_assist-0.14.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
60
- boto3_assist-0.14.0.dist-info/licenses/LICENSE-EXPLAINED.txt,sha256=WFREvTpfTjPjDHpOLADxJpCKpIla3Ht87RUUGii4ODU,606
61
- boto3_assist-0.14.0.dist-info/licenses/LICENSE.txt,sha256=PXDhFWS5L5aOTkVhNvoitHKbAkgxqMI2uUPQyrnXGiI,1105
62
- boto3_assist-0.14.0.dist-info/RECORD,,
59
+ boto3_assist-0.16.0.dist-info/METADATA,sha256=-PF1TMawM0HtsBC04sRDVryOP4BYhBpfNGOvPQNyyBk,2875
60
+ boto3_assist-0.16.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
61
+ boto3_assist-0.16.0.dist-info/licenses/LICENSE-EXPLAINED.txt,sha256=WFREvTpfTjPjDHpOLADxJpCKpIla3Ht87RUUGii4ODU,606
62
+ boto3_assist-0.16.0.dist-info/licenses/LICENSE.txt,sha256=PXDhFWS5L5aOTkVhNvoitHKbAkgxqMI2uUPQyrnXGiI,1105
63
+ boto3_assist-0.16.0.dist-info/RECORD,,