Skip to content

Commit 1cbeec1

Browse files
committed
moved dynamodb client and resource to class module
1 parent ef8631d commit 1cbeec1

File tree

3 files changed

+27
-66
lines changed

3 files changed

+27
-66
lines changed

aws_sra_examples/solutions/genai/bedrock_org/lambda/src/app.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -440,29 +440,26 @@ def deploy_state_table():
440440

441441
if DRY_RUN is False:
442442
LOGGER.info("Live run: creating the state table...")
443-
# TODO(liamschn): move dynamodb client and resource to the dynamo class object/module
444443
# TODO(liamschn): move the deploy state table function to the dynamo class object/module?
445-
dynamodb_client = sts.assume_role(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
444+
dynamodb.DYNAMODB_CLIENT = sts.assume_role(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
445+
dynamodb.DYNAMODB_RESOURCE = sts.assume_role_resource(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
446446

447-
if dynamodb.table_exists(STATE_TABLE, dynamodb_client) is False:
448-
dynamodb.create_table(STATE_TABLE, dynamodb_client)
449-
dynamodb_resource = sts.assume_role_resource(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
447+
if dynamodb.table_exists(STATE_TABLE) is False:
448+
dynamodb.create_table(STATE_TABLE)
450449

451450
item_found, find_result = dynamodb.find_item(
452451
STATE_TABLE,
453-
dynamodb_resource,
454452
"sra-common-prerequisites",
455453
{
456454
"arn": f"arn:aws:dynamodb:{sts.HOME_REGION}:{ssm_params.SRA_SECURITY_ACCT}:table/{STATE_TABLE}",
457455
},
458456
)
459457
if item_found is False:
460-
dynamodb_record_id, dynamodb_date_time = dynamodb.insert_item(STATE_TABLE, dynamodb_resource, "sra-common-prerequisites")
458+
dynamodb_record_id, dynamodb_date_time = dynamodb.insert_item(STATE_TABLE, "sra-common-prerequisites")
461459
else:
462460
dynamodb_record_id = find_result["record_id"]
463461
dynamodb.update_item(
464462
STATE_TABLE,
465-
dynamodb_resource,
466463
"sra-common-prerequisites",
467464
dynamodb_record_id,
468465
{
@@ -502,27 +499,24 @@ def add_state_table_record(aws_service: str, component_state: str, description:
502499
None
503500
"""
504501
LOGGER.info(f"Add a record to the state table for {component_name}")
505-
# TODO(liamschn): move dynamodb resource to the dynamo class object/module
506502
# TODO(liamschn): check to ensure we got a 200 back from the service API call before inserting the dynamodb records
507503

508-
dynamodb_resource = sts.assume_role_resource(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
504+
dynamodb.DYNAMODB_RESOURCE = sts.assume_role_resource(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
509505

510506
item_found, find_result = dynamodb.find_item(
511507
STATE_TABLE,
512-
dynamodb_resource,
513508
SOLUTION_NAME,
514509
{
515510
"arn": resource_arn,
516511
},
517512
)
518513
if item_found is False:
519-
sra_resource_record_id, iam_date_time = dynamodb.insert_item(STATE_TABLE, dynamodb_resource, SOLUTION_NAME)
514+
sra_resource_record_id, iam_date_time = dynamodb.insert_item(STATE_TABLE, SOLUTION_NAME)
520515
else:
521516
sra_resource_record_id = find_result["record_id"]
522517

523518
dynamodb.update_item(
524519
STATE_TABLE,
525-
dynamodb_resource,
526520
SOLUTION_NAME,
527521
sra_resource_record_id,
528522
{
@@ -550,12 +544,11 @@ def remove_state_table_record(resource_arn):
550544
response: response from dynamodb delete_item
551545
"""
552546
# TODO(liamschn): move dynamodb resource to the dynamo class object/module
553-
dynamodb_resource = sts.assume_role_resource(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
547+
dynamodb.DYNAMODB_RESOURCE = sts.assume_role_resource(ssm_params.SRA_SECURITY_ACCT, sts.CONFIGURATION_ROLE, "dynamodb", sts.HOME_REGION)
554548
LOGGER.info(f"Searching for {resource_arn} in {STATE_TABLE} dynamodb table...")
555549
try:
556550
item_found, find_result = dynamodb.find_item(
557551
STATE_TABLE,
558-
dynamodb_resource,
559552
SOLUTION_NAME,
560553
{
561554
"arn": resource_arn,
@@ -568,7 +561,7 @@ def remove_state_table_record(resource_arn):
568561
sra_resource_record_id = find_result["record_id"]
569562
LOGGER.info(f"Found record id {sra_resource_record_id}")
570563
LOGGER.info(f"Removing {sra_resource_record_id} from {STATE_TABLE} dynamodb table...")
571-
response = dynamodb.delete_item(STATE_TABLE, dynamodb_resource, SOLUTION_NAME, sra_resource_record_id)
564+
response = dynamodb.delete_item(STATE_TABLE, SOLUTION_NAME, sra_resource_record_id)
572565
except Exception as error:
573566
LOGGER.error(f"Error removing {resource_arn} record from {STATE_TABLE} dynamodb table: {error}")
574567
response = {}
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
#install latest
22
# TODO(liamschn): not using crhelper
3-
crhelper
4-
# mypy_boto3_dynamodb
3+
crhelper

aws_sra_examples/solutions/genai/bedrock_org/lambda/src/sra_dynamodb.py

Lines changed: 17 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -18,54 +18,22 @@ class sra_dynamodb:
1818
UNEXPECTED = "Unexpected!"
1919

2020
LOGGER = logging.getLogger(__name__)
21-
log_level: str = os.environ.get("LOG_LEVEL", "DEBUG")
21+
log_level: str = os.environ.get("LOG_LEVEL", "INFO")
2222
LOGGER.setLevel(log_level)
2323

24-
# DEBUG STUFF
25-
import sys
26-
system_path = []
27-
for path in sys.path:
28-
system_path.append(path)
29-
LOGGER.debug(f"Python import paths: {system_path}")
30-
31-
import pkgutil
32-
packages_installed = []
33-
for module in pkgutil.iter_modules():
34-
packages_installed.append(module.name)
35-
LOGGER.debug(f"Installed packages: {packages_installed}")
36-
37-
# try:
38-
# from mypy_boto3_dynamodb.service_resource import DynamoDBServiceResource
39-
# LOGGER.info("Successfully imported DynamoDBServiceResource.")
40-
# except ModuleNotFoundError as e:
41-
# LOGGER.error(f"Failed to import DynamoDBServiceResource: {e}")
42-
# except Exception as e:
43-
# LOGGER.error(f"Unexpected error during import: {e}")
44-
45-
# try:
46-
# from mypy_boto3_dynamodb.client import DynamoDBClient
47-
# LOGGER.info("Successfully imported DynamoDBClient.")
48-
# except ModuleNotFoundError as e:
49-
# LOGGER.error(f"Failed to import DynamoDBClient: {e}")
50-
# except Exception as e:
51-
# LOGGER.error(f"Unexpected error during import: {e}")
52-
# END DEBUG STUFF
53-
5424
try:
55-
MANAGEMENT_ACCOUNT_SESSION: Session = boto3.Session()
56-
except Exception:
57-
LOGGER.exception(UNEXPECTED)
58-
raise ValueError("Unexpected error executing Lambda function. Review CloudWatch logs for details.") from None
25+
MANAGEMENT_ACCOUNT_SESSION: Session = boto3.Session()
26+
except Exception as error:
27+
LOGGER.exception(f"Error creating boto3 session: {error}")
28+
raise ValueError(f"Error creating boto3 session: {error}") from None
5929

6030
try:
61-
# Use string-based type annotations
6231
DYNAMODB_CLIENT: "DynamoDBClient" = MANAGEMENT_ACCOUNT_SESSION.client("dynamodb")
6332
DYNAMODB_RESOURCE: "DynamoDBServiceResource" = MANAGEMENT_ACCOUNT_SESSION.resource("dynamodb")
64-
# DYNAMODB_RESOURCE: DynamoDBServiceResource = MANAGEMENT_ACCOUNT_SESSION.resource("dynamodb")
65-
# DYNAMODB_CLIENT: DynamoDBClient = MANAGEMENT_ACCOUNT_SESSION.client("dynamodb")
6633
LOGGER.info("DynamoDB resource and client created successfully.")
6734
except Exception as error:
68-
LOGGER.warning(f"Error creating boto3 dymanodb resource and client: {error}")
35+
LOGGER.info(f"Error creating boto3 dymanodb resource and/or client: {error}")
36+
raise ValueError(f"Error creating boto3 dymanodb resource and/or client: {error}") from None
6937

7038

7139
def __init__(self, profile="default") -> None:
@@ -76,12 +44,13 @@ def __init__(self, profile="default") -> None:
7644
else:
7745
self.MANAGEMENT_ACCOUNT_SESSION = boto3.Session()
7846

79-
# self.DYNAMODB_RESOURCE = self.MANAGEMENT_ACCOUNT_SESSION.resource("dynamodb")
47+
self.DYNAMODB_RESOURCE = self.MANAGEMENT_ACCOUNT_SESSION.resource("dynamodb")
48+
self.DYNAMODB_CLIENT = self.MANAGEMENT_ACCOUNT_SESSION.client("dynamodb")
8049
except Exception:
8150
self.LOGGER.exception(self.UNEXPECTED)
8251
raise ValueError("Unexpected error!") from None
8352

84-
def create_table(self, table_name, dynamodb_client):
53+
def create_table(self, table_name, dynamodb_client=DYNAMODB_CLIENT):
8554
# Define table schema
8655
key_schema = [
8756
{"AttributeName": "solution_name", "KeyType": "HASH"},
@@ -112,7 +81,7 @@ def create_table(self, table_name, dynamodb_client):
11281
# TODO(liamschn): need to add a maximum retry mechanism here
11382
sleep(5)
11483

115-
def table_exists(self, table_name, dynamodb_client):
84+
def table_exists(self, table_name, dynamodb_client=DYNAMODB_CLIENT):
11685
# Check if table exists
11786
try:
11887
dynamodb_client.describe_table(TableName=table_name)
@@ -130,7 +99,7 @@ def get_date_time(self):
13099
now = datetime.now()
131100
return now.strftime("%Y%m%d%H%M%S")
132101

133-
def insert_item(self, table_name, dynamodb_resource, solution_name):
102+
def insert_item(self, table_name, solution_name, dynamodb_resource=DYNAMODB_RESOURCE):
134103
table = dynamodb_resource.Table(table_name)
135104
record_id = self.generate_id()
136105
date_time = self.get_date_time()
@@ -144,7 +113,7 @@ def insert_item(self, table_name, dynamodb_resource, solution_name):
144113
# self.LOGGER.info({"insert_record_response": response})
145114
return record_id, date_time
146115

147-
def update_item(self, table_name, dynamodb_resource, solution_name, record_id, attributes_and_values):
116+
def update_item(self, table_name, solution_name, record_id, attributes_and_values, dynamodb_resource=DYNAMODB_RESOURCE):
148117
self.LOGGER.info(f"Updating {table_name} dynamodb table with {attributes_and_values}")
149118
table = dynamodb_resource.Table(table_name)
150119
update_expression = ""
@@ -167,7 +136,7 @@ def update_item(self, table_name, dynamodb_resource, solution_name, record_id, a
167136
)
168137
return response
169138

170-
def find_item(self, table_name, dynamodb_resource, solution_name, additional_attributes) -> tuple[bool, dict]:
139+
def find_item(self, table_name, solution_name, additional_attributes, dynamodb_resource=DYNAMODB_RESOURCE) -> tuple[bool, dict]:
171140
"""Find an item in the dynamodb table based on the solution name and additional attributes.
172141
173142
Args:
@@ -213,7 +182,7 @@ def get_unique_values_from_list(self, list_of_values):
213182
unique_values.append(value)
214183
return unique_values
215184

216-
def get_distinct_solutions_and_accounts(self, table_name, dynamodb_resource):
185+
def get_distinct_solutions_and_accounts(self, table_name, dynamodb_resource=DYNAMODB_RESOURCE):
217186
table = dynamodb_resource.Table(table_name)
218187
response = table.scan()
219188
solution_names = [item["solution_name"] for item in response["Items"]]
@@ -222,7 +191,7 @@ def get_distinct_solutions_and_accounts(self, table_name, dynamodb_resource):
222191
accounts = self.get_unique_values_from_list(accounts)
223192
return solution_names, accounts
224193

225-
def get_resources_for_solutions_by_account(self, table_name, dynamodb_resource, solutions, account):
194+
def get_resources_for_solutions_by_account(self, table_name, solutions, account, dynamodb_resource=DYNAMODB_RESOURCE):
226195
table = dynamodb_resource.Table(table_name)
227196
query_results = {}
228197
for solution in solutions:
@@ -240,7 +209,7 @@ def get_resources_for_solutions_by_account(self, table_name, dynamodb_resource,
240209
query_results[solution] = response
241210
return query_results
242211

243-
def delete_item(self, table_name, dynamodb_resource, solution_name, record_id):
212+
def delete_item(self, table_name, solution_name, record_id, dynamodb_resource=DYNAMODB_RESOURCE):
244213
"""Delete an item from the dynamodb table
245214
246215
Args:

0 commit comments

Comments
 (0)