Helpers

Helper utilities for naming, branch handling, task generation, and CI/CD workflow creation in the AWS CDK Starter Kit.


Overview

Helper functions power the starter kit's environment-aware naming, Projen task generation, and GitHub Actions workflow creation. These utilities live in src/bin/ and are used both at configuration time and runtime.


env-helper.ts

Source: src/bin/env-helper.ts

Utilities for environment-specific task generation, resource naming, and branch handling.

Types

Environment

type Environment = 'sandbox' | 'development' | 'test' | 'staging' | 'production'

EnvironmentConfig

interface EnvironmentConfig {
  accountId: string;
  enableBranchDeploy: boolean;
}

SUPPORTED_CDK_ACTIONS

const SUPPORTED_CDK_ACTIONS = ['synth', 'diff', 'deploy', 'deploy:hotswap', 'destroy', 'ls'] as const

getTaskName

Location: src/bin/env-helper.ts:35-53

Generates consistent task names following the convention <env>[:<branch>]:<action>[:<type>].

getTaskName(
  environment: string,
  action: typeof SUPPORTED_CDK_ACTIONS[number],
  options?: { isBranch?: boolean; taskType?: 'all' | 'stack' }
): string
ParameterTypeDescription
environmentstringEnvironment name (test, production, etc.)
actionCdkActionCDK action (synth, deploy, destroy, diff, ls, deploy:hotswap)
options.isBranchbooleanWhether this is a branch deployment task
options.taskType'all' | 'stack'Target all stacks or specific stack

Returns: Task name string.

Examples:

getTaskName('test', 'synth')
// → 'test:synth'

getTaskName('test', 'deploy', { taskType: 'all' })
// → 'test:deploy:all'

getTaskName('test', 'deploy', { isBranch: true, taskType: 'all' })
// → 'test:branch:deploy:all'

getTaskName('test', 'destroy', { isBranch: true, taskType: 'stack' })
// → 'test:branch:destroy:stack'

addCdkActionTask

Location: src/bin/env-helper.ts:69-116

Generates npm run tasks for all supported CDK actions with environment-specific variables.

addCdkActionTask(
  cdkProject: AwsCdkTypeScriptApp,
  targetAccount: {
    CDK_DEFAULT_ACCOUNT: string;
    CDK_DEFAULT_REGION: string;
    ENVIRONMENT: string;
    GITHUB_DEPLOY_ROLE: string;
    GIT_BRANCH_REF?: string;
  }
): void
ParameterTypeDescription
cdkProjectAwsCdkTypeScriptAppProjen CDK project instance
targetAccountobjectEnvironment configuration

Target account properties:

PropertyTypeRequiredDescription
CDK_DEFAULT_ACCOUNTstringYesAWS account ID
CDK_DEFAULT_REGIONstringYesAWS region
ENVIRONMENTstringYesEnvironment name
GITHUB_DEPLOY_ROLEstringYesIAM role name for OIDC
GIT_BRANCH_REFstringNoBranch reference for branch deployments

Task generation behavior:

ActionVariantsDescription
synth, lsSingle taskOperates on all stacks
deploy, destroy, diff:all and :stack:all runs on all stacks, :stack accepts stack names
deploy:hotswap:all and :stackOnly generated for branch deployments

Example usage in .projenrc.ts:

import { addCdkActionTask } from './src/bin/env-helper';

// Regular environment tasks
addCdkActionTask(project, {
  CDK_DEFAULT_ACCOUNT: '987654321012',
  CDK_DEFAULT_REGION: 'us-east-1',
  ENVIRONMENT: 'test',
  GITHUB_DEPLOY_ROLE: 'GitHubActionsServiceRole',
});

// Branch deployment tasks
addCdkActionTask(project, {
  CDK_DEFAULT_ACCOUNT: '987654321012',
  CDK_DEFAULT_REGION: 'us-east-1',
  ENVIRONMENT: 'test',
  GITHUB_DEPLOY_ROLE: 'GitHubActionsServiceRole',
  GIT_BRANCH_REF: '$(echo ${GIT_BRANCH_REF:-$(git rev-parse --abbrev-ref HEAD)})',
});

extractCleanedBranchName

Location: src/bin/env-helper.ts:124-147

Extracts and sanitizes branch names for use in resource naming.

extractCleanedBranchName(branchRef: string): string | undefined
ParameterTypeDescription
branchRefstringGit branch reference

Returns: Sanitized branch name or undefined for excluded branches.

Sanitization rules:

RuleDescription
Excluded branchesReturns undefined for main, develop, development
Version tagsReturns undefined for tags matching v\d+\.\d+\.\d+
LowercaseConverts to lowercase
Extract segmentExtracts last segment after /
Character filterKeeps only a-z, 0-9, and -
Trim hyphensRemoves trailing hyphens
TruncateLimits to 25 characters

Examples:

extractCleanedBranchName('feature/user-auth')
// → 'user-auth'

extractCleanedBranchName('bugfix/fix-api-123')
// → 'fix-api-123'

extractCleanedBranchName('main')
// → undefined

extractCleanedBranchName('v1.2.3')
// → undefined

createEnvResourceName

Location: src/bin/env-helper.ts:157-180

Creates environment or branch-aware resource names with automatic suffixing.

createEnvResourceName(baseName: string): string
ParameterTypeDescription
baseNamestringBase name for the resource

Returns: Environment or branch-suffixed resource name (max 64 characters).

Behavior:

ConditionFormatExample
GIT_BRANCH_REF set<baseName>-<cleanedBranchName>MyStack-user-auth
Otherwise<baseName>-<environment>MyStack-test

Error handling:

  • Throws error if GIT_BRANCH_REF resolves to main
  • Truncates to 64 characters max
  • Removes trailing non-alphanumeric characters

Examples:

// Regular environment deployment
process.env.ENVIRONMENT = 'test';
createEnvResourceName('MyStack')
// → 'MyStack-test'

// Branch deployment
process.env.GIT_BRANCH_REF = 'feature/user-auth';
createEnvResourceName('MyStack')
// → 'MyStack-user-auth'

// Error case
process.env.GIT_BRANCH_REF = 'main';
createEnvResourceName('MyStack')
// → Throws error

Usage in CDK stacks:

import { createEnvResourceName } from '../bin/env-helper';

// Stack naming
new StarterStack(app, createEnvResourceName('StarterStack'), { env });

// Resource naming
new s3.Bucket(this, 'Bucket', {
  bucketName: createEnvResourceName('my-app-bucket'),
});

cicd-helper.ts

Source: src/bin/cicd-helper.ts

Functions for generating GitHub Actions workflows. See CI/CD Workflows for workflow behavior details.

createCdkDeploymentWorkflows

Location: src/bin/cicd-helper.ts:113-132

Main entry point that orchestrates workflow generation for an environment.

createCdkDeploymentWorkflows(
  gh: GitHub,
  account: string,
  region: string,
  env: string,
  githubDeployRole: string,
  nodeVersion: string,
  deployForBranch: boolean,
  orderedEnvironments: string[]
): void
ParameterTypeDescription
ghGitHubGitHub instance from Projen
accountstringAWS account ID
regionstringAWS region
envstringEnvironment name
githubDeployRolestringIAM role name for OIDC
nodeVersionstringNode.js version for workflows
deployForBranchbooleanWhether to create branch workflows
orderedEnvironmentsstring[]Environments in deployment order

Workflows created:

WorkflowFilenameCondition
Regular deploymentcdk-deploy-<env>.ymlAlways
Branch deploymentcdk-deploy-<env>-branch.ymlIf deployForBranch=true
Branch destroycdk-destroy-<env>-branch.ymlIf deployForBranch=true

createCdkDeploymentWorkflow

Location: src/bin/cicd-helper.ts:146-217

Creates individual deployment workflows for regular and branch-based deployments.

createCdkDeploymentWorkflow(
  gh: GitHub,
  account: string,
  region: string,
  env: string,
  githubDeployRole: string,
  nodeVersion: string,
  isBranchWorkflow: boolean,
  orderedEnvironments: string[]
): void

Trigger behavior:

EnvironmentTrigger
First env in listPush to main
Subsequent envsworkflow_run when previous env completes
Branch workflowPush to feature branches

Workflow settings:

SettingValuePurpose
Concurrencycancel-in-progress: falsePrevents parallel deployments
Permissionscontents: read, id-token: writeOIDC authentication
EnvironmentLinks to GitHub environmentProtection rules

createCdkDestroyWorkflow

Location: src/bin/cicd-helper.ts:235-303

Creates cleanup workflows for branch deployments.

createCdkDestroyWorkflow(
  gh: GitHub,
  account: string,
  region: string,
  env: string,
  githubDeployRole: string,
  nodeVersion: string
): void

Trigger scenarios:

TriggerMethodBranch extraction
Manual dispatchworkflow_dispatchCurrent branch ref
Branch deletiondelete eventGitHub event payload

Safety features:

  • Job-level condition prevents main branch destruction
  • Branch name validation for feature branches only
  • Manual override via workflow_dispatch

createCdkDiffPrWorkflow

Location: src/bin/cicd-helper.ts:29-94

Creates workflow that posts CDK diff as PR comment.

createCdkDiffPrWorkflow(
  gh: GitHub,
  account: string,
  region: string,
  githubDeployRole: string,
  nodeVersion: string,
  orderedEnvironments: string[]
): void

Configuration:

SettingValuePurpose
Triggerpull_request_target on PRs to mainSecure access to secrets
ComparisonPR branch vs highest environmentUsually production
Comment actiontowardsthecloud/aws-cdk-diff-pr-commenter@v1Posts diff as PR comment
Permissionscontents: read, id-token: write, pull-requests: writeCheckout, OIDC, commenting

getCommonWorkflowSteps

Location: src/bin/cicd-helper.ts:362-378

Generates standard workflow steps shared across all deployments.

getCommonWorkflowSteps(
  nodeVersion: string,
  region: string,
  githubDeployRole: string,
  account: string,
  ref?: string
): WorkflowStep[]

Steps generated:

StepActionPurpose
Checkoutactions/checkout@v5Clone repo
Setup Node.jsactions/setup-node@v6Install Node.js with npm caching
Configure AWSaws-actions/configure-aws-credentials@v4OIDC authentication
Install depsnpm ciReproducible installs

git-helper.ts

Source: src/bin/git-helper.ts

getGitRepositoryDetails

Parses Git remote URL to extract owner and repository name.

getGitRepositoryDetails(): { gitOwner: string; gitRepoName: string }

Returns: Object with gitOwner and gitRepoName.

Usage:

Used by FoundationStack to scope OIDC sub claim to repo:<owner>/<repo>:environment:<env>.

import { getGitRepositoryDetails } from '../bin/git-helper';

const { gitOwner, gitRepoName } = getGitRepositoryDetails();
// gitOwner: 'myorg'
// gitRepoName: 'my-cdk-app'

Next steps