cdk-factory 0.17.6__py3-none-any.whl → 0.20.2__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.

Potentially problematic release.


This version of cdk-factory might be problematic. Click here for more details.

Files changed (44) hide show
  1. cdk_factory/configurations/deployment.py +12 -0
  2. cdk_factory/configurations/resources/acm.py +9 -2
  3. cdk_factory/configurations/resources/auto_scaling.py +7 -5
  4. cdk_factory/configurations/resources/ecs_cluster.py +5 -0
  5. cdk_factory/configurations/resources/ecs_service.py +24 -2
  6. cdk_factory/configurations/resources/lambda_edge.py +18 -4
  7. cdk_factory/configurations/resources/rds.py +1 -1
  8. cdk_factory/configurations/resources/route53.py +5 -0
  9. cdk_factory/configurations/resources/s3.py +9 -1
  10. cdk_factory/constructs/cloudfront/cloudfront_distribution_construct.py +1 -1
  11. cdk_factory/constructs/lambdas/policies/policy_docs.py +1 -1
  12. cdk_factory/interfaces/networked_stack_mixin.py +1 -1
  13. cdk_factory/interfaces/standardized_ssm_mixin.py +82 -10
  14. cdk_factory/stack_library/acm/acm_stack.py +5 -15
  15. cdk_factory/stack_library/api_gateway/api_gateway_stack.py +2 -2
  16. cdk_factory/stack_library/auto_scaling/{auto_scaling_stack_standardized.py → auto_scaling_stack.py} +213 -105
  17. cdk_factory/stack_library/cloudfront/cloudfront_stack.py +76 -22
  18. cdk_factory/stack_library/code_artifact/code_artifact_stack.py +3 -25
  19. cdk_factory/stack_library/cognito/cognito_stack.py +2 -2
  20. cdk_factory/stack_library/dynamodb/dynamodb_stack.py +2 -2
  21. cdk_factory/stack_library/ecs/__init__.py +2 -4
  22. cdk_factory/stack_library/ecs/{ecs_cluster_stack_standardized.py → ecs_cluster_stack.py} +52 -41
  23. cdk_factory/stack_library/ecs/ecs_service_stack.py +49 -26
  24. cdk_factory/stack_library/lambda_edge/EDGE_LOG_RETENTION_TODO.md +226 -0
  25. cdk_factory/stack_library/lambda_edge/LAMBDA_EDGE_LOG_RETENTION_BLOG.md +215 -0
  26. cdk_factory/stack_library/lambda_edge/lambda_edge_stack.py +241 -81
  27. cdk_factory/stack_library/load_balancer/load_balancer_stack.py +128 -177
  28. cdk_factory/stack_library/rds/rds_stack.py +65 -72
  29. cdk_factory/stack_library/route53/route53_stack.py +244 -38
  30. cdk_factory/stack_library/rum/rum_stack.py +3 -3
  31. cdk_factory/stack_library/security_group/security_group_full_stack.py +1 -31
  32. cdk_factory/stack_library/security_group/security_group_stack.py +1 -8
  33. cdk_factory/stack_library/simple_queue_service/sqs_stack.py +1 -34
  34. cdk_factory/stack_library/stack_base.py +5 -0
  35. cdk_factory/stack_library/vpc/{vpc_stack_standardized.py → vpc_stack.py} +6 -109
  36. cdk_factory/stack_library/websites/static_website_stack.py +7 -3
  37. cdk_factory/utilities/api_gateway_integration_utility.py +2 -2
  38. cdk_factory/utilities/environment_services.py +2 -2
  39. cdk_factory/version.py +1 -1
  40. {cdk_factory-0.17.6.dist-info → cdk_factory-0.20.2.dist-info}/METADATA +1 -1
  41. {cdk_factory-0.17.6.dist-info → cdk_factory-0.20.2.dist-info}/RECORD +44 -42
  42. {cdk_factory-0.17.6.dist-info → cdk_factory-0.20.2.dist-info}/WHEEL +0 -0
  43. {cdk_factory-0.17.6.dist-info → cdk_factory-0.20.2.dist-info}/entry_points.txt +0 -0
  44. {cdk_factory-0.17.6.dist-info → cdk_factory-0.20.2.dist-info}/licenses/LICENSE +0 -0
@@ -53,6 +53,8 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
53
53
  self.workload: Optional[WorkloadConfig] = None
54
54
  self.function: Optional[_lambda.Function] = None
55
55
  self.function_version: Optional[_lambda.Version] = None
56
+ # Cache for resolved environment variables to prevent duplicate construct creation
57
+ self._resolved_env_cache: Optional[Dict[str, str]] = None
56
58
 
57
59
  def build(
58
60
  self,
@@ -98,41 +100,74 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
98
100
  # Create version (required for Lambda@Edge)
99
101
  self._create_function_version(function_name)
100
102
 
103
+ # Configure edge log retention for regional logs
104
+ self._configure_edge_log_retention(function_name)
105
+
101
106
  # Add outputs
102
107
  self._add_outputs(function_name)
103
108
 
109
+ def _sanitize_construct_name(self, name: str) -> str:
110
+ """
111
+ Create a deterministic, valid CDK construct name from any string.
112
+ Replaces non-alphanumeric characters with dashes and limits length.
113
+ """
114
+ # Replace non-alphanumeric characters with dashes
115
+ sanitized = ''.join(c if c.isalnum() else '-' for c in name)
116
+ # Remove consecutive dashes
117
+ while '--' in sanitized:
118
+ sanitized = sanitized.replace('--', '-')
119
+ # Remove leading/trailing dashes
120
+ sanitized = sanitized.strip('-')
121
+ # Limit to 255 characters (CDK limit)
122
+ return sanitized[:255]
123
+
104
124
  def _resolve_environment_variables(self) -> Dict[str, str]:
105
125
  """
106
126
  Resolve environment variables, including SSM parameter references.
107
127
  Supports {{ssm:parameter-path}} syntax for dynamic SSM lookups.
108
128
  Uses CDK tokens that resolve at deployment time, not synthesis time.
129
+ Caches results to prevent duplicate construct creation.
109
130
  """
131
+ # Return cached result if available
132
+ if self._resolved_env_cache is not None:
133
+ return self._resolved_env_cache
134
+
110
135
  resolved_env = {}
111
136
 
112
- for key, value in self.edge_config.environment.items():
137
+ # Use the new simplified configuration structure
138
+ configuration = self.edge_config.dictionary.get("configuration", {})
139
+ runtime_config = configuration.get("runtime", {})
140
+ ui_config = configuration.get("ui", {})
141
+
142
+ for key, value in runtime_config.items():
113
143
  # Check if value is an SSM parameter reference
114
144
  if isinstance(value, str) and value.startswith("{{ssm:") and value.endswith("}}"):
115
145
  # Extract SSM parameter path
116
146
  ssm_param_path = value[6:-2] # Remove {{ssm: and }}
117
147
 
148
+ # Create deterministic construct name from parameter path
149
+ construct_name = self._sanitize_construct_name(f"env-{key}-{ssm_param_path}")
150
+
118
151
  # Import SSM parameter - this creates a token that resolves at deployment time
119
152
  param = ssm.StringParameter.from_string_parameter_name(
120
153
  self,
121
- f"env-{key}-{hash(ssm_param_path) % 10000}",
154
+ construct_name,
122
155
  ssm_param_path
123
156
  )
124
157
  resolved_value = param.string_value
125
- logger.info(f"Resolved environment variable {key} from SSM {ssm_param_path}")
158
+ logger.info(f"Resolved environment variable {key} from SSM {ssm_param_path} as {construct_name}")
126
159
  resolved_env[key] = resolved_value
127
160
  else:
128
161
  resolved_env[key] = value
129
162
 
163
+ # Cache the result
164
+ self._resolved_env_cache = resolved_env
130
165
  return resolved_env
131
166
 
132
167
  def _create_lambda_function(self, function_name: str) -> None:
133
168
  """Create the Lambda function"""
134
169
 
135
- # Resolve code path - support package references (e.g., "cdk_factory:lambdas/edge/ip_gate")
170
+ # Resolve code path - support package references (e.g., "cdk_factory:lambdas/cloudfront/ip_gate")
136
171
  code_path_str = self.edge_config.code_path
137
172
 
138
173
  if ':' in code_path_str:
@@ -185,10 +220,24 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
185
220
  # Create runtime configuration file for Lambda@Edge
186
221
  # Since Lambda@Edge doesn't support environment variables, we bundle a config file
187
222
  # Use the full function_name (e.g., "tech-talk-dev-ip-gate") not just the base name
223
+ resolved_env = self._resolve_environment_variables()
224
+
225
+ # Get the UI configuration
226
+ configuration = self.edge_config.dictionary.get("configuration", {})
227
+ ui_config = configuration.get("ui", {})
228
+
229
+
230
+ workload_name = self.deployment.workload.get("name")
231
+
232
+ if not workload_name:
233
+ raise ValueError("Workload name is required for Lambda@Edge function")
188
234
  runtime_config = {
189
235
  'environment': self.deployment.environment,
236
+ 'workload': workload_name,
190
237
  'function_name': function_name,
191
- 'region': self.deployment.region
238
+ 'region': self.deployment.region,
239
+ 'runtime': resolved_env, # Runtime variables (SSM, etc.)
240
+ 'ui': ui_config # UI configuration (colors, messages, etc.)
192
241
  }
193
242
 
194
243
  runtime_config_path = temp_code_dir / 'runtime_config.json'
@@ -216,21 +265,17 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
216
265
  self.edge_config.runtime,
217
266
  _lambda.Runtime.PYTHON_3_11
218
267
  )
219
-
220
- # Lambda@Edge does NOT support environment variables
221
- # Configuration must be handled via:
222
- # 1. Hardcoded in the function code
223
- # 2. Fetched from SSM Parameter Store at runtime
224
- # 3. Other configuration mechanisms
225
-
268
+
226
269
  # Log warning if environment variables are configured
227
- if self.edge_config.environment:
270
+ configuration = self.edge_config.dictionary.get("configuration", {})
271
+ runtime_config = configuration.get("runtime", {})
272
+
273
+ if runtime_config:
228
274
  logger.warning(
229
275
  f"Lambda@Edge function '{function_name}' has environment variables configured, "
230
- "but Lambda@Edge does not support environment variables. "
231
- "The function must fetch these values from SSM Parameter Store at runtime."
276
+ "but Lambda@Edge does not support environment variables. The function must fetch these values from SSM Parameter Store at runtime."
232
277
  )
233
- for key, value in self.edge_config.environment.items():
278
+ for key, value in runtime_config.items():
234
279
  logger.warning(f" - {key}: {value}")
235
280
 
236
281
  # Create execution role with CloudWatch Logs and SSM permissions
@@ -239,7 +284,8 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
239
284
  f"{function_name}-Role",
240
285
  assumed_by=iam.CompositePrincipal(
241
286
  iam.ServicePrincipal("lambda.amazonaws.com"),
242
- iam.ServicePrincipal("edgelambda.amazonaws.com")
287
+ iam.ServicePrincipal("edgelambda.amazonaws.com"),
288
+ iam.ServicePrincipal("cloudfront.amazonaws.com") # Add CloudFront service principal
243
289
  ),
244
290
  description=f"Execution role for Lambda@Edge function {function_name}",
245
291
  managed_policies=[
@@ -250,7 +296,7 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
250
296
  )
251
297
 
252
298
  # Add SSM read permissions if environment variables reference SSM parameters
253
- if self.edge_config.environment:
299
+ if runtime_config:
254
300
  execution_role.add_to_policy(
255
301
  iam.PolicyStatement(
256
302
  effect=iam.Effect.ALLOW,
@@ -260,12 +306,88 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
260
306
  "ssm:GetParametersByPath"
261
307
  ],
262
308
  resources=[
263
- f"arn:aws:ssm:*:{cdk.Aws.ACCOUNT_ID}:parameter/*"
309
+ f"arn:aws:ssm:*:{self.deployment.account}:parameter/*"
264
310
  ]
265
311
  )
266
312
  )
267
313
 
268
- # Create the Lambda function WITHOUT environment variables
314
+ # Add Secrets Manager permissions for origin secret access
315
+ execution_role.add_to_policy(
316
+ iam.PolicyStatement(
317
+ effect=iam.Effect.ALLOW,
318
+ actions=[
319
+ "secretsmanager:GetSecretValue",
320
+ "secretsmanager:DescribeSecret"
321
+ ],
322
+ resources=[
323
+ f"arn:aws:secretsmanager:*:{self.deployment.account}:secret:{self.deployment.environment}/{self.workload.name}/origin-secret*"
324
+ ]
325
+ )
326
+ )
327
+
328
+ # Add ELB permissions for target health API access
329
+ execution_role.add_to_policy(
330
+ iam.PolicyStatement(
331
+ effect=iam.Effect.ALLOW,
332
+ actions=[
333
+ "elasticloadbalancing:DescribeTargetHealth",
334
+ "elasticloadbalancing:DescribeTargetGroups",
335
+ "elasticloadbalancing:DescribeLoadBalancers",
336
+ "elasticloadbalancing:DescribeListeners",
337
+ "elasticloadbalancing:DescribeTags"
338
+ ],
339
+ resources=[
340
+ "*"
341
+ ]
342
+ )
343
+ )
344
+
345
+ # Add ACM permissions for certificate validation
346
+ execution_role.add_to_policy(
347
+ iam.PolicyStatement(
348
+ effect=iam.Effect.ALLOW,
349
+ actions=[
350
+ "acm:DescribeCertificate",
351
+ "acm:ListCertificates"
352
+ ],
353
+ resources=[
354
+ f"arn:aws:acm:*:{self.deployment.account}:certificate/*"
355
+ ]
356
+ )
357
+ )
358
+
359
+ # Add Route 53 permissions for health check access
360
+ execution_role.add_to_policy(
361
+ iam.PolicyStatement(
362
+ effect=iam.Effect.ALLOW,
363
+ actions=[
364
+ "route53:GetHealthCheckStatus",
365
+ "route53:ListHealthChecks",
366
+ "route53:GetHealthCheck"
367
+ ],
368
+ resources=[
369
+ f"arn:aws:route53:::{self.deployment.account}:health-check/*"
370
+ ]
371
+ )
372
+ )
373
+
374
+ # Add CloudWatch permissions for enhanced logging and metrics
375
+ execution_role.add_to_policy(
376
+ iam.PolicyStatement(
377
+ effect=iam.Effect.ALLOW,
378
+ actions=[
379
+ "logs:CreateLogGroup",
380
+ "logs:CreateLogStream",
381
+ "logs:PutLogEvents",
382
+ "cloudwatch:PutMetricData"
383
+ ],
384
+ resources=[
385
+ f"arn:aws:logs:*:{self.deployment.account}:log-group:/aws/lambda/*",
386
+ f"arn:aws:cloudwatch:*:{self.deployment.account}:metric:*"
387
+ ]
388
+ )
389
+ )
390
+
269
391
  self.function = _lambda.Function(
270
392
  self,
271
393
  function_name,
@@ -278,6 +400,7 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
278
400
  description=self.edge_config.description,
279
401
  role=execution_role,
280
402
  # Lambda@Edge does NOT support environment variables
403
+ # Configuration must be fetched from SSM at runtime
281
404
  log_retention=logs.RetentionDays.ONE_WEEK,
282
405
  )
283
406
 
@@ -285,6 +408,36 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
285
408
  for key, value in self.edge_config.tags.items():
286
409
  cdk.Tags.of(self.function).add(key, value)
287
410
 
411
+ # Add resource-based policy allowing CloudFront to invoke the Lambda function
412
+ # This is REQUIRED for Lambda@Edge to work properly
413
+ permission_kwargs = {
414
+ "principal": iam.ServicePrincipal("cloudfront.amazonaws.com"),
415
+ "action": "lambda:InvokeFunction",
416
+ }
417
+
418
+ # Optional: Add source ARN restriction if CloudFront distribution ARN is available
419
+ # This provides more secure permission scoping
420
+ distribution_arn_path = f"/{self.deployment.environment}/{self.workload.name}/cloudfront/arn"
421
+ try:
422
+ distribution_arn = ssm.StringParameter.from_string_parameter_name(
423
+ self,
424
+ "cloudfront-distribution-arn",
425
+ distribution_arn_path
426
+ ).string_value
427
+
428
+ # Add source ARN condition for more secure permission scoping
429
+ permission_kwargs["source_arn"] = distribution_arn
430
+ logger.info(f"Adding CloudFront permission with source ARN restriction: {distribution_arn}")
431
+ except Exception:
432
+ # Distribution ARN not available (common during initial deployment)
433
+ # CloudFront will scope the permission appropriately when it associates the Lambda
434
+ logger.warning(f"CloudFront distribution ARN not found at {distribution_arn_path}, using open permission")
435
+
436
+ self.function.add_permission(
437
+ "CloudFrontInvokePermission",
438
+ **permission_kwargs
439
+ )
440
+
288
441
  def _create_function_version(self, function_name: str) -> None:
289
442
  """
290
443
  Create a version of the Lambda function.
@@ -300,36 +453,49 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
300
453
  f"Version for Lambda@Edge deployment - {self.edge_config.description}"
301
454
  )
302
455
 
303
- def _add_outputs(self, function_name: str) -> None:
304
- """Add CloudFormation outputs and SSM exports"""
456
+ def _configure_edge_log_retention(self, function_name: str) -> None:
457
+ """
458
+ Configure log retention for Lambda@Edge log groups in all edge regions
305
459
 
306
- # CloudFormation outputs
307
- cdk.CfnOutput(
308
- self,
309
- "FunctionName",
310
- value=self.function.function_name,
311
- description="Lambda function name",
312
- export_name=f"{function_name}-name"
313
- )
460
+ TODO: IMPLEMENT POST-DEPLOYMENT SOLUTION
461
+ --------------------------------------
462
+ Lambda@Edge log groups are created on-demand when the function is invoked
463
+ at edge locations, not during deployment. This means we cannot set retention
464
+ policies during CloudFormation deployment.
314
465
 
315
- cdk.CfnOutput(
316
- self,
317
- "FunctionArn",
318
- value=self.function.function_arn,
319
- description="Lambda function ARN (unversioned)",
320
- export_name=f"{function_name}-arn"
321
- )
466
+ Possible solutions to implement:
467
+ 1. EventBridge rule that triggers on log group creation
468
+ 2. Custom Lambda function that runs periodically to set retention
469
+ 3. Post-deployment script that waits for log groups to appear
470
+ 4. CloudWatch Logs subscription filter that handles new log groups
322
471
 
323
- cdk.CfnOutput(
324
- self,
325
- "FunctionVersionArn",
326
- value=self.function_version.function_arn,
327
- description="Lambda function version ARN (use this for Lambda@Edge)",
328
- export_name=f"{function_name}-version-arn"
472
+ Current behavior: DISABLED to prevent deployment failures
473
+ """
474
+
475
+ # DISABLED: Edge log groups don't exist during deployment
476
+ # Lambda@Edge creates log groups on-demand at edge locations
477
+ # Setting retention policies during deployment fails with "log group does not exist"
478
+
479
+ edge_retention_days = self.edge_config.dictionary.get("edge_log_retention_days", 7)
480
+ logger.warning(
481
+ f"Edge log retention configuration disabled - log groups are created on-demand. "
482
+ f"Desired retention: {edge_retention_days} days. "
483
+ f"See TODO in _configure_edge_log_retention() for implementation approach."
329
484
  )
330
485
 
486
+ # TODO: Implement one of these solutions:
487
+ # 1. EventBridge + Lambda: Trigger on log group creation and set retention
488
+ # 2. Periodic Lambda: Scan for edge log groups and apply retention policies
489
+ # 3. Post-deployment script: Wait for log groups to appear after edge replication
490
+ # 4. CloudWatch Logs subscription: Process new log group events
491
+
492
+ return
493
+
494
+ def _add_outputs(self, function_name: str) -> None:
495
+ """Add CloudFormation outputs and SSM exports"""
496
+
331
497
  # SSM Parameter Store exports (if configured)
332
- ssm_exports = self.edge_config.dictionary.get("ssm_exports", {})
498
+ ssm_exports = self.edge_config.dictionary.get("ssm", {}).get("exports", {})
333
499
  if ssm_exports:
334
500
  export_values = {
335
501
  "function_name": self.function.function_name,
@@ -349,40 +515,34 @@ class LambdaEdgeStack(IStack, StandardizedSsmMixin):
349
515
  description=f"{key} for Lambda@Edge function {function_name}"
350
516
  )
351
517
 
352
- # Export environment variables as SSM parameters
353
- # Since Lambda@Edge doesn't support environment variables, we export them
354
- # to SSM so the Lambda function can fetch them at runtime
355
- if self.edge_config.environment:
356
- logger.info("Exporting Lambda@Edge environment variables as SSM parameters")
357
- env_ssm_exports = self.edge_config.dictionary.get("environment_ssm_exports", {})
358
-
359
- # If no explicit environment_ssm_exports, create default SSM paths
360
- if not env_ssm_exports:
361
- # Auto-generate SSM parameter names based on environment variable names
362
- for env_key in self.edge_config.environment.keys():
363
- # Use snake_case version of the key for SSM path
364
- ssm_key = env_key.lower().replace('_', '-')
365
- env_ssm_exports[env_key] = f"/{self.deployment.environment}/{function_name}/{ssm_key}"
366
-
367
- # Resolve and export environment variables to SSM
368
- resolved_env = self._resolve_environment_variables()
369
- for env_key, ssm_path in env_ssm_exports.items():
370
- if env_key in resolved_env:
371
- env_value = resolved_env[env_key]
372
-
373
- # Handle empty values - SSM doesn't allow empty strings
374
- # Use sentinel value "NONE" to indicate explicitly unset
375
- if not env_value or (isinstance(env_value, str) and env_value.strip() == ""):
376
- env_value = "NONE"
377
- logger.info(
378
- f"Environment variable {env_key} is empty - setting SSM parameter to 'NONE'. "
379
- f"Lambda function should treat 'NONE' as unset/disabled."
380
- )
381
-
382
- self.export_ssm_parameter(
383
- self,
384
- f"env-{env_key}-param",
385
- env_value,
386
- ssm_path,
387
- description=f"Configuration for Lambda@Edge: {env_key}"
388
- )
518
+ # Export the complete configuration as a single SSM parameter
519
+ config_ssm_path = f"/{self.deployment.environment}/{self.workload.name}/lambda-edge/config"
520
+ configuration = self.edge_config.dictionary.get("configuration", {})
521
+ environment_variables = configuration.get("environment_variables", {})
522
+
523
+ # Build full configuration that Lambda@Edge expects
524
+ full_config = {
525
+ "environment_variables": environment_variables,
526
+ "runtime": configuration.get("runtime", {}),
527
+ "ui": configuration.get("ui", {})
528
+ }
529
+
530
+ self.export_ssm_parameter(
531
+ self,
532
+ "full-config-param",
533
+ json.dumps(full_config),
534
+ config_ssm_path,
535
+ description=f"Complete Lambda@Edge configuration for {function_name} - update this for dynamic changes"
536
+ )
537
+
538
+ # Export cache TTL parameter for dynamic cache control
539
+ cache_ttl_ssm_path = f"/{self.deployment.environment}/{self.workload.name}/lambda-edge/cache-ttl"
540
+ default_cache_ttl = self.edge_config.dictionary.get("cache_ttl_seconds", 300) # Default 5 minutes
541
+
542
+ self.export_ssm_parameter(
543
+ self,
544
+ "cache-ttl-param",
545
+ str(default_cache_ttl),
546
+ cache_ttl_ssm_path,
547
+ description=f"Lambda@Edge configuration cache TTL in seconds for {function_name} - adjust for maintenance windows (30-3600)"
548
+ )