Reputation: 1419
My goal is to dynamically name resources to allow for multiple environments. For example, a "dev-accounts" table, and a "prod-accounts" table.
The issue I am facing is Code Build cannot dynamically name resources, whilst local can. Following the example above, I am receiving "undefined-accounts" when viewing the logs in Code Build.
Code to obtain the environment by branch name:
export const getContext = (app: App): Promise<CDKContext> => {
return new Promise(async (resolve, reject) => {
try {
const currentBranch = await gitBranch();
const environment = app.node.tryGetContext("environments").find((e: any) => e.branchName === currentBranch);
const globals = app.node.tryGetContext("globals");
return resolve({...globals, ...environment});
}
catch (error) {
return reject("Cannot get context from getContext()");
}
})
}
Further Explanation:
In the bin/template.ts
file, I am using console.log
to log the context, after calling const context = await getContext(app);
Local CLI outcome:
{
appName: 'appName',
region: 'eu-west-1',
accountId: '000000000',
environment: 'dev',
branchName: 'dev'
}
Code Build outcome:
{
appName: 'appName',
region: 'eu-west-1',
accountId: '000000000'
}
Note I've removed sensitive information.
This is my Code Pipeline built in the CDK:
this.codePipeline = new CodePipeline(this, `${environment}-${appName}-`, {
pipelineName: `${environment}-${appName}-`,
selfMutation: true,
crossAccountKeys: false,
role: this.codePipelineRole,
synth: new ShellStep("Deployment", {
input: CodePipelineSource.codeCommit(this.codeRepository, environment, {
codeBuildCloneOutput: true
}),
installCommands: ["npm i -g npm@latest"],
commands: [
"cd backend",
"npm ci",
"npm run build",
"cdk synth",
],
primaryOutputDirectory: "backend/cdk.out",
})
});
By using the key/value codeBuildCloneOutput: true
, I believe I am completing a full clone of Code Commit repository, and thus the git metadata.
Upvotes: 0
Views: 534
Reputation: 25819
CodeBuild exposes the CODEBUILD_SOURCE_VERSION
environment variable. For CodeCommit, this is "the commit ID or branch name associated with the version of the source code to be built".
const currentBranch = process.env.CODEBUILD_SOURCE_VERSION ?? await gitBranch();
Upvotes: 1