Skip to content

Commit f87dda0

Browse files
committed
working on sns fanout (for config 1st)
1 parent 5e2c13f commit f87dda0

File tree

2 files changed

+96
-67
lines changed

2 files changed

+96
-67
lines changed

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

Lines changed: 94 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -202,40 +202,41 @@ def get_resource_parameters(event):
202202
CFN_RESPONSE_DATA["dry_run"] = DRY_RUN
203203

204204

205-
def get_rule_params(rule_name, event):
205+
def get_rule_params(rule_name, resource_properties):
206206
"""Get rule parameters from event and return them in a tuple
207207
208208
Args:
209209
rule_name (str): name of config rule
210-
event (dict): lambda event
210+
resource_properties (dict): lambda event resource properties
211211
212212
Returns:
213213
tuple: (rule_deploy, rule_accounts, rule_regions, rule_params)
214214
rule_deploy (bool): whether to deploy the rule
215-
rule_accounts (list): list of accounts to deploy the rule to
216-
rule_regions (list): list of regions to deploy the rule to
217215
rule_input_params (dict): dictionary of rule input parameters
218216
"""
217+
# rule_accounts (list): list of accounts to deploy the rule to
218+
# rule_regions (list): list of regions to deploy the rule to
219+
219220
# TODO(liamschn): SRA-BEDROCK-ACCOUNTS and SRA-BEDROCK-REGIONS to be moved to a more global area so it is not defined more than once
220-
if "SRA-BEDROCK-ACCOUNTS" in event["ResourceProperties"]:
221-
LOGGER.info("SRA-BEDROCK-ACCOUNTS found in event ResourceProperties")
222-
rule_accounts = json.loads(event["ResourceProperties"]["SRA-BEDROCK-ACCOUNTS"])
223-
LOGGER.info(f"SRA-BEDROCK-ACCOUNTS: {rule_accounts}")
224-
else:
225-
LOGGER.info("SRA-BEDROCK-ACCOUNTS not found in event ResourceProperties; setting to None and deploy to False")
226-
rule_accounts = []
227-
rule_deploy = False
228-
if "SRA-BEDROCK-REGIONS" in event["ResourceProperties"]:
229-
LOGGER.info("SRA-BEDROCK-REGIONS found in event ResourceProperties")
230-
rule_regions = json.loads(event["ResourceProperties"]["SRA-BEDROCK-REGIONS"])
231-
LOGGER.info(f"SRA-BEDROCK-REGIONS: {rule_regions}")
232-
else:
233-
LOGGER.info("SRA-BEDROCK-REGIONS not found in event ResourceProperties; setting to None and deploy to False")
234-
rule_regions = []
235-
rule_deploy = False
236-
if rule_name.upper() in event["ResourceProperties"]:
221+
# if "SRA-BEDROCK-ACCOUNTS" in resource_properties:
222+
# LOGGER.info("SRA-BEDROCK-ACCOUNTS found in event ResourceProperties")
223+
# rule_accounts = json.loads(resource_properties["SRA-BEDROCK-ACCOUNTS"])
224+
# LOGGER.info(f"SRA-BEDROCK-ACCOUNTS: {rule_accounts}")
225+
# else:
226+
# LOGGER.info("SRA-BEDROCK-ACCOUNTS not found in event ResourceProperties; setting to None and deploy to False")
227+
# rule_accounts = []
228+
# rule_deploy = False
229+
# if "SRA-BEDROCK-REGIONS" in resource_properties:
230+
# LOGGER.info("SRA-BEDROCK-REGIONS found in event ResourceProperties")
231+
# rule_regions = json.loads(resource_properties["SRA-BEDROCK-REGIONS"])
232+
# LOGGER.info(f"SRA-BEDROCK-REGIONS: {rule_regions}")
233+
# else:
234+
# LOGGER.info("SRA-BEDROCK-REGIONS not found in event ResourceProperties; setting to None and deploy to False")
235+
# rule_regions = []
236+
# rule_deploy = False
237+
if rule_name.upper() in resource_properties:
237238
LOGGER.info(f"{rule_name} parameter found in event ResourceProperties")
238-
rule_params = json.loads(event["ResourceProperties"][rule_name.upper()])
239+
rule_params = json.loads(resource_properties[rule_name.upper()])
239240
LOGGER.info(f"{rule_name.upper()} parameters: {rule_params}")
240241
if "deploy" in rule_params:
241242
LOGGER.info(f"{rule_name.upper()} 'deploy' parameter found in event ResourceProperties")
@@ -271,10 +272,10 @@ def get_rule_params(rule_name, event):
271272
else:
272273
LOGGER.info(f"{rule_name.upper()} 'input_params' parameter not found in event ResourceProperties; setting to None")
273274
rule_input_params = {}
274-
return rule_deploy, rule_accounts, rule_regions, rule_input_params
275+
return rule_deploy, rule_input_params
275276
else:
276277
LOGGER.info(f"{rule_name.upper()} config rule parameter not found in event ResourceProperties; skipping...")
277-
return False, [], [], {}
278+
return False, {}
278279

279280

280281
def get_filter_params(filter_name, event):
@@ -432,31 +433,41 @@ def deploy_sns_configuration_topics(context):
432433
else:
433434
LOGGER.info(f"{SOLUTION_NAME}-configuration SNS topic already exists.")
434435
topic_arn = topic_search
436+
return topic_arn
435437

436-
def deploy_config_rules(event):
438+
def deploy_config_rules(region, accounts, resource_properties):
437439
global DRY_RUN_DATA
438440
global LIVE_RUN_DATA
439441
global CFN_RESPONSE_DATA
442+
for prop in resource_properties:
443+
if prop.startswith("SRA-BEDROCK-CHECK-"):
444+
rule_name: str = prop
445+
LOGGER.info(f"Create operation: retrieving {rule_name} parameters...")
446+
rule_deploy, rule_input_params = get_rule_params(rule_name, resource_properties)
447+
rule_name = rule_name.lower()
448+
LOGGER.info(f"Create operation: examining {rule_name} resources...")
440449

441-
for rule in repo.CONFIG_RULES[SOLUTION_NAME]:
442-
rule_name = rule.replace("_", "-")
450+
for acct in accounts:
451+
452+
# for rule in repo.CONFIG_RULES[SOLUTION_NAME]:
453+
# rule_name = rule.replace("_", "-")
443454
# Get bedrock solution rule accounts and regions
444-
rule_deploy, rule_accounts, rule_regions, rule_input_params = get_rule_params(rule_name, event)
445-
if rule_deploy is False:
446-
continue
455+
# rule_deploy, rule_accounts, rule_regions, rule_input_params = get_rule_params(rule_name, event)
456+
if rule_deploy is False:
457+
continue
447458

448-
for acct in rule_accounts:
449-
if DRY_RUN is False:
450-
# 3a) Deploy IAM role for custom config rule lambda
451-
LOGGER.info(f"Deploying IAM role for custom config rule lambda in {acct}")
452-
role_arn = deploy_iam_role(acct, rule_name)
453-
LIVE_RUN_DATA[f"{rule_name}_{acct}_IAMRole"] = "Deployed IAM role for custom config rule lambda"
454-
else:
455-
LOGGER.info(f"DRY_RUN: Deploying IAM role for custom config rule lambda in {acct}")
456-
DRY_RUN_DATA[f"{rule_name}_{acct}_IAMRole"] = "DRY_RUN: Deploy IAM role for custom config rule lambda"
459+
# for acct in rule_accounts:
460+
if DRY_RUN is False:
461+
# 3a) Deploy IAM role for custom config rule lambda
462+
LOGGER.info(f"Deploying IAM role for custom config rule lambda in {acct}")
463+
role_arn = deploy_iam_role(acct, rule_name)
464+
LIVE_RUN_DATA[f"{rule_name}_{acct}_IAMRole"] = "Deployed IAM role for custom config rule lambda"
465+
else:
466+
LOGGER.info(f"DRY_RUN: Deploying IAM role for custom config rule lambda in {acct}")
467+
DRY_RUN_DATA[f"{rule_name}_{acct}_IAMRole"] = "DRY_RUN: Deploy IAM role for custom config rule lambda"
457468

458-
for acct in rule_accounts:
459-
for region in rule_regions:
469+
# for acct in rule_accounts:
470+
# for region in rule_regions:
460471
# 3b) Deploy lambda for custom config rule
461472
if DRY_RUN is False:
462473
lambda_arn = deploy_lambda_function(acct, rule_name, role_arn, region)
@@ -804,12 +815,28 @@ def create_event(event, context):
804815

805816
# 2) SNS topics for fanout configuration operations (global/home region)
806817
# TODO(liamschn): change the code to have the create events call the sns topic (by publishing events for accounts/regions) which calls the lambda for configuration/deployment
807-
deploy_sns_configuration_topics(context)
818+
topic_arn = deploy_sns_configuration_topics(context)
808819

809820
# 3, 4, and 5 handled by SNS
810-
# create_sns_messages()
821+
# TODO(liamschn): Move get regions and accounts into its own function
822+
if "SRA-BEDROCK-ACCOUNTS" in event["ResourceProperties"]:
823+
LOGGER.info("SRA-BEDROCK-ACCOUNTS found in event ResourceProperties")
824+
accounts = json.loads(event["ResourceProperties"]["SRA-BEDROCK-ACCOUNTS"])
825+
LOGGER.info(f"SRA-BEDROCK-ACCOUNTS: {accounts}")
826+
else:
827+
LOGGER.info("SRA-BEDROCK-ACCOUNTS not found in event ResourceProperties; setting to None")
828+
accounts = []
829+
if "SRA-BEDROCK-REGIONS" in event["ResourceProperties"]:
830+
LOGGER.info("SRA-BEDROCK-REGIONS found in event ResourceProperties")
831+
regions = json.loads(event["ResourceProperties"]["SRA-BEDROCK-REGIONS"])
832+
LOGGER.info(f"SRA-BEDROCK-REGIONS: {regions}")
833+
else:
834+
LOGGER.info("SRA-BEDROCK-REGIONS not found in event ResourceProperties; setting to None")
835+
regions = []
836+
811837
# 3) Deploy config rules (regional)
812-
deploy_config_rules(event)
838+
# deploy_config_rules(event)
839+
create_sns_messages(accounts, regions, topic_arn, event["ResourceProperties"], "configure")
813840

814841
# 4) deploy kms cmk, cloudwatch metric filters, and SNS topics for alarms (regional)
815842
deploy_metric_filters_and_alarms(event)
@@ -1159,7 +1186,7 @@ def delete_event(event, context):
11591186
cfnresponse.send(event, context, cfnresponse.SUCCESS, CFN_RESPONSE_DATA, CFN_RESOURCE_ID)
11601187

11611188

1162-
def create_sns_messages(accounts: list, regions: list, sns_topic_arn: str, action: str, event: dict) -> None:
1189+
def create_sns_messages(accounts: list, regions: list, sns_topic_arn: str, resource_properties: dict, action: str, ) -> None:
11631190
"""Create SNS Message.
11641191
11651192
Args:
@@ -1168,20 +1195,20 @@ def create_sns_messages(accounts: list, regions: list, sns_topic_arn: str, actio
11681195
sns_topic_arn: SNS Topic ARN
11691196
action: Action
11701197
"""
1198+
LOGGER.info("Creating SNS Messages...")
11711199
sns_messages = []
1172-
if "ResourceProperties" in event:
1173-
for region in regions:
1174-
sns_message = {"Accounts": accounts, "Region": region, "Action": action, "ResourceProperties": event["ResourceProperties"]}
1175-
sns_messages.append(
1176-
{
1177-
"Id": region,
1178-
"Message": json.dumps(sns_message),
1179-
"Subject": "SRA Bedrock Configuration",
1180-
}
1181-
)
1182-
sns.process_sns_message_batches(sns_messages, sns_topic_arn)
1183-
else:
1184-
LOGGER.info("No ResourceProperties found in event")
1200+
LOGGER.info("ResourceProperties found in event")
1201+
1202+
for region in regions:
1203+
sns_message = {"Accounts": accounts, "Region": region, "ResourceProperties": resource_properties, "Action": action}
1204+
sns_messages.append(
1205+
{
1206+
"Id": region,
1207+
"Message": json.dumps(sns_message),
1208+
"Subject": "SRA Bedrock Configuration",
1209+
}
1210+
)
1211+
sns.process_sns_message_batches(sns_messages, sns_topic_arn)
11851212

11861213

11871214
def process_sns_records(event) -> None:
@@ -1190,6 +1217,7 @@ def process_sns_records(event) -> None:
11901217
Args:
11911218
records: list of SNS event records
11921219
"""
1220+
LOGGER.info("Processing SNS records...")
11931221
# for record in records:
11941222
# sns_info = record["Sns"]
11951223
# LOGGER.info(f"SNS INFO: {sns_info}")
@@ -1204,20 +1232,20 @@ def process_sns_records(event) -> None:
12041232
# rule_deploy, rule_accounts, rule_regions, rule_input_params = get_rule_params(rule_name, event)
12051233

12061234
# 3) Deploy config rules (regional)
1207-
# deploy_config_rules(
1208-
# message["Region"],
1209-
# message["Accounts"],
1210-
# rule_deploy,
1211-
# rule_accounts,
1212-
# rule_regions,
1213-
# rule_input_params,
1214-
# )
1235+
1236+
deploy_config_rules(
1237+
message["Region"],
1238+
message["Accounts"],
1239+
message["ResourceProperties"],
1240+
)
12151241

12161242
# 4) deploy kms cmk, cloudwatch metric filters, and SNS topics for alarms (regional)
12171243
# deploy_metric_filters_and_alarms(event)
12181244

12191245
# # 5) Central CloudWatch Observability (regional)
12201246
# deploy_central_cloudwatch_observability(event)
1247+
else:
1248+
LOGGER.info(f"Action specified is {message['Action']}")
12211249

12221250
def deploy_iam_role(account_id: str, rule_name: str) -> str:
12231251
"""Deploy IAM role.

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def publish_sns_message_batch(self, message_batch: list, sns_topic_arn: str) ->
164164
message_batch: Batch of SNS messages
165165
sns_topic_arn: SNS Topic ARN
166166
"""
167-
self.LOGGER.info("Publishing SNS Message Batch")
167+
self.LOGGER.info("Publishing SNS Message Batch...")
168168
self.LOGGER.info({"SNSMessageBatch": message_batch})
169169
response: PublishBatchResponseTypeDef = self.SNS_CLIENT.publish_batch(TopicArn=sns_topic_arn, PublishBatchRequestEntries=message_batch)
170170
api_call_details = {"API_Call": "sns:PublishBatch", "API_Response": response}
@@ -177,6 +177,7 @@ def process_sns_message_batches(self, sns_messages: list, sns_topic_arn: str) ->
177177
sns_messages: SNS messages to be batched.
178178
sns_topic_arn: SNS Topic ARN
179179
"""
180+
self.LOGGER.info("Processing SNS Message Batches...")
180181
message_batches = []
181182
for i in range(
182183
self.SNS_PUBLISH_BATCH_MAX,

0 commit comments

Comments
 (0)