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

@@ -243,3 +243,66 @@ class CognitoConfig(EnhancedBaseConfig):
243
243
  def ssm(self) -> Dict[str, Any]:
244
244
  """Whether to export the user pool name (default: False)"""
245
245
  return self.__config.get("ssm", {})
246
+
247
+ @property
248
+ def app_clients(self) -> list | None:
249
+ """
250
+ App clients for the user pool.
251
+ Supports multiple clients with different auth flows and OAuth settings.
252
+
253
+ Structure:
254
+ [{
255
+ "name": "web-client",
256
+ "generate_secret": False,
257
+ "auth_flows": {
258
+ "user_password": True,
259
+ "user_srp": True,
260
+ "custom": False,
261
+ "admin_user_password": False
262
+ },
263
+ "oauth": {
264
+ "flows": {
265
+ "authorization_code_grant": True,
266
+ "implicit_code_grant": False,
267
+ "client_credentials": False
268
+ },
269
+ "scopes": ["email", "openid", "profile"],
270
+ "callback_urls": ["https://example.com/callback"],
271
+ "logout_urls": ["https://example.com/logout"]
272
+ },
273
+ "supported_identity_providers": ["COGNITO"],
274
+ "prevent_user_existence_errors": True,
275
+ "enable_token_revocation": True,
276
+ "access_token_validity": {"minutes": 60},
277
+ "id_token_validity": {"minutes": 60},
278
+ "refresh_token_validity": {"days": 30},
279
+ "read_attributes": ["email", "name"],
280
+ "write_attributes": ["name"]
281
+ }]
282
+
283
+ Example:
284
+ [
285
+ {
286
+ "name": "web-app",
287
+ "generate_secret": False,
288
+ "auth_flows": {
289
+ "user_password": True,
290
+ "user_srp": True
291
+ }
292
+ },
293
+ {
294
+ "name": "backend-service",
295
+ "generate_secret": True,
296
+ "oauth": {
297
+ "flows": {
298
+ "client_credentials": True
299
+ },
300
+ "scopes": ["api/read", "api/write"]
301
+ }
302
+ }
303
+ ]
304
+
305
+ Returns:
306
+ list: List of app client configurations
307
+ """
308
+ return self.__config.get("app_clients")
@@ -16,7 +16,7 @@ class ECRConfig(EnhancedBaseConfig):
16
16
  ) -> None:
17
17
  super().__init__(config, resource_type="ecr", resource_name=config.get("name", "ecr") if config else "ecr")
18
18
  self.__config = config
19
- self.__deployment = config
19
+ self.__deployment = deployment
20
20
  self.__ssm_prefix_template = config.get("ssm_prefix_template", None)
21
21
 
22
22
  @property
@@ -74,12 +74,13 @@ class ECRConfig(EnhancedBaseConfig):
74
74
  Clear out untagged images after x days. This helps save costs.
75
75
  Untagged images will stay forever if you don't clean them out.
76
76
  """
77
+ days = None
77
78
  if self.__config and isinstance(self.__config, dict):
78
79
  days = self.__config.get("auto_delete_untagged_images_in_days")
79
80
  if days:
80
81
  days = int(days)
81
82
 
82
- return None
83
+ return days
83
84
 
84
85
  @property
85
86
  def use_existing(self) -> bool:
@@ -118,6 +119,50 @@ class ECRConfig(EnhancedBaseConfig):
118
119
  if not value:
119
120
  raise RuntimeError("Region is not defined")
120
121
  return value
122
+
123
+ @property
124
+ def cross_account_access(self) -> dict:
125
+ """
126
+ Cross-account access configuration.
127
+
128
+ Example:
129
+ {
130
+ "enabled": true,
131
+ "accounts": ["123456789012", "987654321098"],
132
+ "services": [
133
+ {
134
+ "name": "lambda",
135
+ "actions": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"],
136
+ "condition": {
137
+ "StringLike": {
138
+ "aws:sourceArn": "arn:aws:lambda:*:*:function:*"
139
+ }
140
+ }
141
+ },
142
+ {
143
+ "name": "ecs-tasks",
144
+ "service_principal": "ecs-tasks.amazonaws.com",
145
+ "actions": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"]
146
+ },
147
+ {
148
+ "name": "codebuild",
149
+ "service_principal": "codebuild.amazonaws.com",
150
+ "actions": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
151
+ }
152
+ ]
153
+ }
154
+ """
155
+ if self.__config and isinstance(self.__config, dict):
156
+ return self.__config.get("cross_account_access", {})
157
+ return {}
158
+
159
+ @property
160
+ def cross_account_enabled(self) -> bool:
161
+ """Whether cross-account access is explicitly enabled"""
162
+ access_config = self.cross_account_access
163
+ if access_config:
164
+ return str(access_config.get("enabled", "true")).lower() == "true"
165
+ return True # Default to enabled for backward compatibility
121
166
 
122
167
  # SSM properties are now inherited from EnhancedBaseConfig
123
168
  # Keeping these for any direct access patterns in existing code
@@ -0,0 +1,144 @@
1
+ """
2
+ ECS Service Configuration
3
+ Maintainers: Eric Wilson
4
+ MIT License. See Project Root for the license information.
5
+ """
6
+
7
+ from typing import Dict, Any, List, Optional
8
+
9
+
10
+ class EcsServiceConfig:
11
+ """ECS Service Configuration"""
12
+
13
+ def __init__(self, config: Dict[str, Any]) -> None:
14
+ self._config = config
15
+
16
+ @property
17
+ def name(self) -> str:
18
+ """Service name"""
19
+ return self._config.get("name", "")
20
+
21
+ @property
22
+ def cluster_name(self) -> Optional[str]:
23
+ """ECS Cluster name"""
24
+ return self._config.get("cluster_name")
25
+
26
+ @property
27
+ def task_definition(self) -> Dict[str, Any]:
28
+ """Task definition configuration"""
29
+ return self._config.get("task_definition", {})
30
+
31
+ @property
32
+ def container_definitions(self) -> List[Dict[str, Any]]:
33
+ """Container definitions"""
34
+ return self.task_definition.get("containers", [])
35
+
36
+ @property
37
+ def cpu(self) -> str:
38
+ """Task CPU units"""
39
+ return self.task_definition.get("cpu", "256")
40
+
41
+ @property
42
+ def memory(self) -> str:
43
+ """Task memory (MB)"""
44
+ return self.task_definition.get("memory", "512")
45
+
46
+ @property
47
+ def launch_type(self) -> str:
48
+ """Launch type: FARGATE or EC2"""
49
+ return self._config.get("launch_type", "FARGATE")
50
+
51
+ @property
52
+ def desired_count(self) -> int:
53
+ """Desired number of tasks"""
54
+ return self._config.get("desired_count", 2)
55
+
56
+ @property
57
+ def min_capacity(self) -> int:
58
+ """Minimum number of tasks"""
59
+ return self._config.get("min_capacity", 1)
60
+
61
+ @property
62
+ def max_capacity(self) -> int:
63
+ """Maximum number of tasks"""
64
+ return self._config.get("max_capacity", 4)
65
+
66
+ @property
67
+ def vpc_id(self) -> Optional[str]:
68
+ """VPC ID"""
69
+ return self._config.get("vpc_id")
70
+
71
+ @property
72
+ def subnet_group_name(self) -> Optional[str]:
73
+ """Subnet group name for service placement"""
74
+ return self._config.get("subnet_group_name")
75
+
76
+ @property
77
+ def security_group_ids(self) -> List[str]:
78
+ """Security group IDs"""
79
+ return self._config.get("security_group_ids", [])
80
+
81
+ @property
82
+ def assign_public_ip(self) -> bool:
83
+ """Whether to assign public IP addresses"""
84
+ return self._config.get("assign_public_ip", False)
85
+
86
+ @property
87
+ def target_group_arns(self) -> List[str]:
88
+ """Target group ARNs for load balancing"""
89
+ return self._config.get("target_group_arns", [])
90
+
91
+ @property
92
+ def container_port(self) -> int:
93
+ """Container port for load balancer"""
94
+ return self._config.get("container_port", 80)
95
+
96
+ @property
97
+ def health_check_grace_period(self) -> int:
98
+ """Health check grace period in seconds"""
99
+ return self._config.get("health_check_grace_period", 60)
100
+
101
+ @property
102
+ def enable_execute_command(self) -> bool:
103
+ """Enable ECS Exec for debugging"""
104
+ return self._config.get("enable_execute_command", False)
105
+
106
+ @property
107
+ def enable_auto_scaling(self) -> bool:
108
+ """Enable auto-scaling"""
109
+ return self._config.get("enable_auto_scaling", True)
110
+
111
+ @property
112
+ def auto_scaling_target_cpu(self) -> int:
113
+ """Target CPU utilization percentage for auto-scaling"""
114
+ return self._config.get("auto_scaling_target_cpu", 70)
115
+
116
+ @property
117
+ def auto_scaling_target_memory(self) -> int:
118
+ """Target memory utilization percentage for auto-scaling"""
119
+ return self._config.get("auto_scaling_target_memory", 80)
120
+
121
+ @property
122
+ def tags(self) -> Dict[str, str]:
123
+ """Resource tags"""
124
+ return self._config.get("tags", {})
125
+
126
+ @property
127
+ def ssm_exports(self) -> Dict[str, str]:
128
+ """SSM parameter exports"""
129
+ return self._config.get("ssm_exports", {})
130
+
131
+ @property
132
+ def ssm_imports(self) -> Dict[str, str]:
133
+ """SSM parameter imports"""
134
+ return self._config.get("ssm_imports", {})
135
+
136
+ @property
137
+ def deployment_type(self) -> str:
138
+ """Deployment type: production, maintenance, or blue-green"""
139
+ return self._config.get("deployment_type", "production")
140
+
141
+ @property
142
+ def is_maintenance_mode(self) -> bool:
143
+ """Whether this is a maintenance mode deployment"""
144
+ return self.deployment_type == "maintenance"
@@ -33,6 +33,7 @@ class ECRConstruct(Construct, SsmParameterMixin):
33
33
 
34
34
  self.scope = scope
35
35
  self.deployment = deployment
36
+ self.repo = repo
36
37
  self.ecr_name = repo.name
37
38
  self.image_scan_on_push = repo.image_scan_on_push
38
39
  self.empty_on_delete = repo.empty_on_delete
@@ -98,28 +99,17 @@ class ECRConstruct(Construct, SsmParameterMixin):
98
99
  )
99
100
 
100
101
  # Add dependencies to ensure SSM parameters are created after the ECR repository
101
- for param in params.values():
102
- if param and param.node.default_child and isinstance(param.node.default_child, CfnResource):
103
- param.node.default_child.add_dependency(
104
- cast(CfnResource, self.ecr.node.default_child)
105
- )
102
+ if params:
103
+ for param in params.values():
104
+ if param and hasattr(param, 'node') and param.node.default_child and isinstance(param.node.default_child, CfnResource):
105
+ param.node.default_child.add_dependency(
106
+ cast(CfnResource, self.ecr.node.default_child)
107
+ )
106
108
 
107
109
  def __set_life_cycle_rules(self) -> None:
108
- # ToDo/FixMe: tag_pattern_list is not recognized in the current version in AWS
109
-
110
- try:
111
- # always keep images tagged as prod
112
- self.ecr.add_lifecycle_rule(
113
- tag_pattern_list=["prod*"], max_image_count=9999
114
- )
115
- except Exception as e: # pylint: disable=w0718
116
- if "unexpected keyword argument" in str(e):
117
- logger.warning(
118
- "tag_pattern_list is not available in this version of the aws cdk"
119
- )
120
- else:
121
- raise
122
-
110
+ # Note: tag_pattern_list is deprecated and causes circular dependencies in CDK synthesis
111
+ # Only add lifecycle rule for untagged images if configured
112
+
123
113
  if not self.auto_delete_untagged_images_in_days:
124
114
  return None
125
115
 
@@ -143,49 +133,131 @@ class ECRConstruct(Construct, SsmParameterMixin):
143
133
  )
144
134
 
145
135
  def __setup_cross_account_access_permissions(self):
146
- # Cross-account access policy
136
+ """
137
+ Setup cross-account access permissions with flexible configuration support.
138
+
139
+ Supports both legacy (default Lambda access) and new configurable approach.
140
+ """
141
+ # Check if cross-account access is disabled
142
+ if not self.repo.cross_account_enabled:
143
+ logger.info(f"Cross-account access disabled for {self.ecr_name}")
144
+ return
147
145
 
148
- if self.deployment.account == self.deployment.workload.get("devops", {}).get(
149
- "account"
150
- ):
151
- # we're in the same account as the "devops" so we don't need cross account
152
- # permisions
146
+ # Check if we're in the same account as devops
147
+ if self.deployment.account == self.deployment.workload.get("devops", {}).get("account"):
148
+ logger.info(f"Same account as devops, skipping cross-account permissions for {self.ecr_name}")
153
149
  return
154
150
 
155
- ecr = self.ecr or self.__get_ecr()
156
- cross_account_policy_statement = iam.PolicyStatement(
151
+ access_config = self.repo.cross_account_access
152
+
153
+ if access_config and access_config.get("services"):
154
+ # New configurable approach
155
+ logger.info(f"Setting up configurable cross-account access for {self.ecr_name}")
156
+ self.__setup_configurable_access(access_config)
157
+ else:
158
+ # Legacy approach - default Lambda access for backward compatibility
159
+ logger.info(f"Setting up legacy cross-account access (Lambda only) for {self.ecr_name}")
160
+ self.__setup_legacy_lambda_access()
161
+
162
+ def __setup_configurable_access(self, access_config: dict):
163
+ """Setup cross-account access using configuration"""
164
+
165
+ # Get list of accounts (default to deployment account)
166
+ accounts = access_config.get("accounts", [self.deployment.account])
167
+
168
+ # Add account principal policies if accounts are specified
169
+ if accounts:
170
+ self.__add_account_principal_policy(accounts)
171
+
172
+ # Add service-specific policies
173
+ services = access_config.get("services", [])
174
+ for service_config in services:
175
+ self.__add_service_principal_policy(service_config)
176
+
177
+ def __add_account_principal_policy(self, accounts: list):
178
+ """Add policy for AWS account principals"""
179
+ principals = [iam.AccountPrincipal(account) for account in accounts]
180
+
181
+ policy_statement = iam.PolicyStatement(
157
182
  actions=[
158
183
  "ecr:GetDownloadUrlForLayer",
159
184
  "ecr:BatchGetImage",
160
185
  "ecr:BatchCheckLayerAvailability",
161
186
  ],
162
- principals=[
163
- iam.AccountPrincipal(self.deployment.account)
164
- ], # Replace with the account ID of the Lambda function
165
- resources=[ecr.repository_arn],
187
+ principals=principals,
166
188
  effect=iam.Effect.ALLOW,
167
189
  )
168
190
 
169
- # Attach the policy to the ECR repository
170
- response = ecr.add_to_resource_policy(cross_account_policy_statement)
171
-
172
- # fails, we're not adding it this way
173
- assert response.statement_added
174
-
175
- response = self.ecr.add_to_resource_policy(
176
- iam.PolicyStatement(
177
- effect=iam.Effect.ALLOW,
178
- actions=["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"],
179
- principals=[iam.ServicePrincipal("lambda.amazonaws.com")],
180
- conditions={
181
- "StringLike": {
182
- "aws:sourceArn": [
183
- f"arn:aws:lambda:{self.deployment.region}:{self.deployment.account}:function:*"
184
- ]
185
- }
186
- },
187
- resources=[ecr.repository_arn],
188
- )
191
+ response = self.ecr.add_to_resource_policy(policy_statement)
192
+ if not response.statement_added:
193
+ logger.warning(f"Failed to add account principal policy for {', '.join(accounts)}")
194
+ else:
195
+ logger.info(f"Added account principal policy for accounts: {', '.join(accounts)}")
196
+
197
+ def __add_service_principal_policy(self, service_config: dict):
198
+ """Add policy for service principal (Lambda, ECS, CodeBuild, etc.)"""
199
+ service_name = service_config.get("name", "unknown")
200
+ service_principal = service_config.get("service_principal")
201
+ actions = service_config.get("actions", ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"])
202
+ conditions = service_config.get("condition")
203
+
204
+ if not service_principal:
205
+ # Infer service principal from common service names
206
+ service_principal_map = {
207
+ "lambda": "lambda.amazonaws.com",
208
+ "ecs": "ecs-tasks.amazonaws.com",
209
+ "ecs-tasks": "ecs-tasks.amazonaws.com",
210
+ "codebuild": "codebuild.amazonaws.com",
211
+ "codepipeline": "codepipeline.amazonaws.com",
212
+ "ec2": "ec2.amazonaws.com",
213
+ }
214
+ service_principal = service_principal_map.get(service_name.lower())
215
+
216
+ if not service_principal:
217
+ logger.warning(f"Unknown service principal for service: {service_name}")
218
+ return
219
+
220
+ policy_statement = iam.PolicyStatement(
221
+ effect=iam.Effect.ALLOW,
222
+ actions=actions,
223
+ principals=[iam.ServicePrincipal(service_principal)],
224
+ )
225
+
226
+ # Add conditions if specified
227
+ if conditions:
228
+ for condition_key, condition_value in conditions.items():
229
+ policy_statement.add_condition(condition_key, condition_value)
230
+
231
+ response = self.ecr.add_to_resource_policy(policy_statement)
232
+ if not response.statement_added:
233
+ logger.warning(f"Failed to add service principal policy for {service_name}")
234
+ else:
235
+ logger.info(f"Added service principal policy for {service_name} ({service_principal})")
236
+
237
+ def __setup_legacy_lambda_access(self):
238
+ """Legacy method: Setup default Lambda-only cross-account access"""
239
+
240
+ # Add account principal policy
241
+ self.__add_account_principal_policy([self.deployment.account])
242
+
243
+ # Add Lambda service principal policy with default condition
244
+ lambda_policy = iam.PolicyStatement(
245
+ effect=iam.Effect.ALLOW,
246
+ actions=["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"],
247
+ principals=[iam.ServicePrincipal("lambda.amazonaws.com")],
248
+ )
249
+
250
+ lambda_policy.add_condition(
251
+ "StringLike",
252
+ {
253
+ "aws:sourceArn": [
254
+ f"arn:aws:lambda:{self.deployment.region}:{self.deployment.account}:function:*"
255
+ ]
256
+ }
189
257
  )
190
258
 
191
- assert response.statement_added
259
+ response = self.ecr.add_to_resource_policy(lambda_policy)
260
+ if not response.statement_added:
261
+ logger.warning("Failed to add Lambda service principal policy")
262
+ else:
263
+ logger.info("Added legacy Lambda service principal policy")
@@ -246,7 +246,13 @@ class PipelineFactoryStack(cdk.Stack):
246
246
 
247
247
  def _get_steps(self, key: str, stage_config: PipelineStageConfig):
248
248
  """
249
- Gets the build steps from the config.json
249
+ Gets the build steps from the config.json.
250
+
251
+ Commands can be:
252
+ - A list of strings (each string is a separate command)
253
+ - A single multi-line string (treated as a single script block)
254
+
255
+ This allows support for complex shell constructs like if blocks, loops, etc.
250
256
  """
251
257
  shell_steps: List[pipelines.ShellStep] = []
252
258
 
@@ -257,6 +263,12 @@ class PipelineFactoryStack(cdk.Stack):
257
263
  for step in steps:
258
264
  step_id = step.get("id") or step.get("name")
259
265
  commands = step.get("commands", [])
266
+
267
+ # Normalize commands to a list
268
+ # If commands is a single string, wrap it in a list
269
+ if isinstance(commands, str):
270
+ commands = [commands]
271
+
260
272
  shell_step = pipelines.ShellStep(
261
273
  id=step_id,
262
274
  commands=commands,