Skip to content

Commit 5783b69

Browse files
committed
refactor: apply simplify review findings
Reuse and altitude reviewers both flagged the deploy role name being retyped in .projenrc.py while the construct kept its own default. Two sides must agree on it: FoundationStack creates the role and the generated workflows put its ARN in role-to-assume. env_helper now owns DEFAULT_GITHUB_DEPLOY_ROLE_NAME and both import it. DEFAULT_ENVIRONMENT gets the same treatment. That required env_helper to stop importing projen at runtime, since the CDK app imports it for create_env_resource_name. The annotation moves under TYPE_CHECKING, so synthesis no longer drags the build tool in. Also from the reviews: - .projenrc.py builds the task env dict once instead of repeating four of five keys for the branch variant. - TRAILING_HYPHENS and TRAILING_NON_ALPHANUMERIC collapse into one TRAILING_SEPARATORS pattern; every string they trim is drawn from the same alphabet, so they did the same job. - _create_cdk_deployment_workflow drops chained_on_previous_environment, which only duplicated whether triggers carries workflow_run, and the unreachable -1 fallback on the environment index. - BucketPublicAccessAspect flattens its nested if/else into guard clauses matching the rest of the function. - app.py tags branch deploys with extract_cleaned_branch_name directly rather than calling create_env_resource_name("b") for its suffix logic. The tag is now "add-api" rather than "b-add-api". Generated workflows are byte-identical, confirming the cicd_helper changes are behavior-preserving.
1 parent 076f658 commit 5783b69

6 files changed

Lines changed: 58 additions & 39 deletions

File tree

‎.projenrc.py‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@
1414
create_cdk_diff_pr_workflow,
1515
create_release_workflow,
1616
)
17-
from src.bin.env_helper import EnvironmentConfig, add_cdk_action_task
17+
from src.bin.env_helper import (
18+
DEFAULT_GITHUB_DEPLOY_ROLE_NAME,
19+
EnvironmentConfig,
20+
add_cdk_action_task,
21+
)
1822

1923
# Define the python module name and set the python version
2024
project_name = "aws-cdk-python-starter-kit"
@@ -32,8 +36,9 @@
3236
aws_region = os.getenv("AWS_REGION", "us-east-1")
3337

3438
# Name of the GitHub deploy role created by the FoundationStack. Set as an environment variable
35-
# for the projen tasks so the CDK app and the workflows agree on one name.
36-
github_role = "GitHubActionsServiceRole"
39+
# for the projen tasks so the CDK app and the workflows agree on one name. Sourced from
40+
# env_helper rather than retyped, because the construct falls back to the same constant.
41+
github_role = DEFAULT_GITHUB_DEPLOY_ROLE_NAME
3742

3843
project = AwsCdkPythonApp(
3944
author_email="danny@towardsthecloud.com",
@@ -219,26 +224,22 @@
219224
create_release_workflow(gh, python_version)
220225

221226
for config in environment_configs:
227+
task_environment = {
228+
"CDK_DEFAULT_ACCOUNT": config.account_id,
229+
"CDK_DEFAULT_REGION": aws_region,
230+
"ENVIRONMENT": config.name,
231+
"GITHUB_DEPLOY_ROLE": github_role,
232+
}
233+
222234
# Adds `uv run projen` commands for executing cdk synth, diff, deploy, destroy and ls
223-
add_cdk_action_task(
224-
project,
225-
{
226-
"CDK_DEFAULT_ACCOUNT": config.account_id,
227-
"CDK_DEFAULT_REGION": aws_region,
228-
"ENVIRONMENT": config.name,
229-
"GITHUB_DEPLOY_ROLE": github_role,
230-
},
231-
)
235+
add_cdk_action_task(project, task_environment)
232236

233237
# If branch deployment is enabled for this environment, add the GIT_BRANCH_REF tasks
234238
if config.enable_branch_deploy:
235239
add_cdk_action_task(
236240
project,
237241
{
238-
"CDK_DEFAULT_ACCOUNT": config.account_id,
239-
"CDK_DEFAULT_REGION": aws_region,
240-
"ENVIRONMENT": config.name,
241-
"GITHUB_DEPLOY_ROLE": github_role,
242+
**task_environment,
242243
"GIT_BRANCH_REF": "$(echo ${GIT_BRANCH_REF:-$(git rev-parse --abbrev-ref HEAD)})",
243244
},
244245
)

‎src/app.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@
22

33
import aws_cdk as cdk
44

5-
from bin.env_helper import create_env_resource_name
5+
from bin.env_helper import (
6+
DEFAULT_ENVIRONMENT,
7+
create_env_resource_name,
8+
extract_cleaned_branch_name,
9+
)
610
from stacks.foundation_stack import FoundationStack
711
from stacks.starter_stack import StarterStack
812

913
# Inherit environment variables from the `uv run projen` commands (see .projen/tasks.json)
10-
environment = os.environ.get("ENVIRONMENT", "dev")
14+
environment = os.environ.get("ENVIRONMENT", DEFAULT_ENVIRONMENT)
1115
aws_environment = cdk.Environment(
1216
account=os.getenv("CDK_DEFAULT_ACCOUNT"), region=os.getenv("CDK_DEFAULT_REGION")
1317
)
@@ -38,8 +42,9 @@
3842
cdk.Tags.of(app).add("environment", environment)
3943

4044
# Tag branch based deploys with the branch name to easily identify the branch in the AWS console
41-
if os.environ.get("GIT_BRANCH_REF"):
42-
cdk.Tags.of(app).add("branch", create_env_resource_name("b"))
45+
branch_name = extract_cleaned_branch_name(os.environ.get("GIT_BRANCH_REF"))
46+
if branch_name:
47+
cdk.Tags.of(app).add("branch", branch_name)
4348

4449
# Synthesize the CDK app
4550
app.synth()

‎src/aspects/s3_aspect.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,15 @@ def visit(self, node: IConstruct) -> None:
5858
except ValueError:
5959
return
6060

61+
# Only a bucket with no configuration at all falls through to the correction below.
6162
if configuration is not None:
6263
if Tokenization.is_resolvable(configuration):
6364
return
64-
if isinstance(
65+
if not isinstance(
6566
configuration, s3.CfnBucket.PublicAccessBlockConfigurationProperty
6667
):
67-
if configuration.block_public_acls is True:
68-
return
69-
else:
68+
return
69+
if configuration.block_public_acls is True:
7070
return
7171

7272
Annotations.of(node).add_warning(

‎src/bin/cicd_helper.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -505,14 +505,11 @@ def _create_cdk_deployment_workflow(
505505
)
506506

507507
triggers: dict[str, Any] = {"workflow_dispatch": {}}
508-
chained_on_previous_environment = False
509508

510509
if deploy_for_branch:
511510
triggers["push"] = {"branches": _branch_filter()}
512511
else:
513-
current_index = (
514-
ordered_environments.index(env) if env in ordered_environments else -1
515-
)
512+
current_index = ordered_environments.index(env)
516513
if current_index == 0:
517514
triggers["push"] = {"branches": ["main"]}
518515
elif current_index > 0:
@@ -522,7 +519,6 @@ def _create_cdk_deployment_workflow(
522519
"workflows": [f"cdk-deploy-{previous_env}"],
523520
"types": ["completed"],
524521
}
525-
chained_on_previous_environment = True
526522

527523
workflow.on(**triggers)
528524

@@ -548,7 +544,7 @@ def _create_cdk_deployment_workflow(
548544
"steps": steps,
549545
}
550546

551-
if chained_on_previous_environment:
547+
if "workflow_run" in triggers:
552548
# workflow_run fires on completion regardless of outcome, so a failed test deploy would
553549
# otherwise promote straight to production.
554550
job["if"] = "github.event.workflow_run.conclusion == 'success'"

‎src/bin/env_helper.py‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,40 @@
1+
from __future__ import annotations
2+
13
import os
24
import re
35
from dataclasses import dataclass
4-
from typing import Literal
6+
from typing import TYPE_CHECKING, Literal
57

6-
from projen.awscdk import AwsCdkPythonApp
8+
if TYPE_CHECKING:
9+
# Only needed to annotate `add_cdk_action_task`. Importing projen at runtime would drag the
10+
# build tool into the CDK app, which imports this module for `create_env_resource_name`.
11+
from projen.awscdk import AwsCdkPythonApp
712

813
Environment = Literal["sandbox", "development", "test", "staging", "production"]
914
"""The deployment environments this project supports."""
1015

1116
SUPPORTED_CDK_ACTIONS = ("synth", "diff", "deploy", "deploy:hotswap", "destroy", "ls")
1217
"""CDK actions that get a generated projen task."""
1318

19+
DEFAULT_ENVIRONMENT = "dev"
20+
"""Environment assumed when `ENVIRONMENT` is unset, as it is on a bare `cdk synth`."""
21+
22+
DEFAULT_GITHUB_DEPLOY_ROLE_NAME = "GitHubActionsServiceRole"
23+
"""Name of the role GitHub Actions assumes.
24+
25+
Owned here because two sides must agree on it: `FoundationStack` creates the role, and the
26+
generated workflows put its ARN in `role-to-assume`. A rename in only one of them leaves CI
27+
requesting a role that does not exist.
28+
"""
29+
1430
# A resource name longer than this breaks the strictest AWS naming constraints.
1531
MAX_RESOURCE_NAME_LENGTH = 64
1632
# Longer branch names push the resource name over the limit once a base name is prepended.
1733
MAX_BRANCH_NAME_LENGTH = 25
1834

1935
GIT_TAG_PATTERN = re.compile(r"v\d+\.\d+\.\d+$")
2036
NON_RESOURCE_NAME_CHARACTERS = re.compile(r"[^a-zA-Z0-9-]")
21-
TRAILING_HYPHENS = re.compile(r"-+$")
22-
TRAILING_NON_ALPHANUMERIC = re.compile(r"[^a-zA-Z0-9]+$")
37+
TRAILING_SEPARATORS = re.compile(r"[^a-zA-Z0-9]+$")
2338

2439
# Deploying a branch stack from one of these would collide with the shared environment stacks.
2540
LONG_LIVED_BRANCHES = frozenset({"main", "develop", "development"})
@@ -172,7 +187,9 @@ def extract_cleaned_branch_name(git_branch_ref: str | None) -> str | None:
172187
if last_part in LONG_LIVED_BRANCHES:
173188
return None
174189

175-
cleaned = TRAILING_HYPHENS.sub("", NON_RESOURCE_NAME_CHARACTERS.sub("", last_part))
190+
cleaned = TRAILING_SEPARATORS.sub(
191+
"", NON_RESOURCE_NAME_CHARACTERS.sub("", last_part)
192+
)
176193
return cleaned[:MAX_BRANCH_NAME_LENGTH]
177194

178195

@@ -190,7 +207,7 @@ def create_env_resource_name(base_name: str) -> str:
190207
collide with the shared environment stacks.
191208
"""
192209
branch_name = os.environ.get("GIT_BRANCH_REF")
193-
environment = os.environ.get("ENVIRONMENT", "dev")
210+
environment = os.environ.get("ENVIRONMENT", DEFAULT_ENVIRONMENT)
194211

195212
if branch_name and branch_name.lower() == "main":
196213
raise ValueError(
@@ -205,4 +222,4 @@ def create_env_resource_name(base_name: str) -> str:
205222
return resource_name
206223

207224
# Truncating can leave a trailing hyphen, which most AWS resource names reject.
208-
return TRAILING_NON_ALPHANUMERIC.sub("", resource_name[:MAX_RESOURCE_NAME_LENGTH])
225+
return TRAILING_SEPARATORS.sub("", resource_name[:MAX_RESOURCE_NAME_LENGTH])

‎src/custom_constructs/github_actions_oidc_construct.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
)
1111
from constructs import Construct
1212

13+
from bin.env_helper import DEFAULT_GITHUB_DEPLOY_ROLE_NAME
1314
from bin.git_helper import (
1415
GitHubRepositoryReference,
1516
build_github_actions_oidc_subject,
@@ -18,7 +19,6 @@
1819
)
1920

2021
GITHUB_DOMAIN = "token.actions.githubusercontent.com"
21-
DEFAULT_ROLE_NAME = "GitHubActionsServiceRole"
2222

2323

2424
class GitHubActionsOidcConstruct(Construct):
@@ -104,5 +104,5 @@ def __init__(
104104
],
105105
max_session_duration=max_session_duration or Duration.hours(2),
106106
role_name=role_name
107-
or os.environ.get("GITHUB_DEPLOY_ROLE", DEFAULT_ROLE_NAME),
107+
or os.environ.get("GITHUB_DEPLOY_ROLE", DEFAULT_GITHUB_DEPLOY_ROLE_NAME),
108108
)

0 commit comments

Comments
 (0)