Home > Back-end >  AWS CDK typescript environment variable value validation
AWS CDK typescript environment variable value validation

Time:07-19

I need to add deployment_env tag with possible value of dev, test, and prod on every resources deployed to AWS under a CDK stack, other than that all the resources should have same properties. I tried to use environment variable of DEPLOYMENT_ENV which is works fine, unless any value other than the possible value still go through and the CDK still can be synth-ed and deployed with any provided value. Not only that, when the environment variable isn't defined the typescript compiler doesn't validate the undefined or null value and error received upon value assignment to the tag of Tag must have a value which is expected to fail earlier. Here's the code

#!/usr/bin/env node
import { App, Tags } from 'aws-cdk-lib';
import { EnvInitStack } from '../lib/foo-stack';

const deploymentEnv : 'dev' | 'test' | 'prod' = process.env.DEPLOYMENT_ENV as 'dev' | 'test' | 'prod';

const app = new App();
const fooStack = new FooStack(app, 'FooStack', {});

Tags.of(envInitStack).add('deployment_env', deploymentEnv as string);
  1. using command DEPLOYMENT_ENV=foo cdk synth the cdk synth-ed and deployed successfully
  2. using command cdk synth error received Error: Tag must have a value

CodePudding user response:

you need to verify your value 'deploymentEnv' value by js code not by type script defintion. try to add:

if (!['dev','test','prod'].includes(deploymentEnv))
    throw ('invalid deploymentEnv tag');
  • Related