Thursday, November 14, 2024

AWS CDK Get Parameter Store Value

Problem:

There are multiple ways to get a parameter store value. Which one should I use?

Solution:

1. Resolve at deploy time with no extra synth:

Use this pattern when you need the parameter value to resolve at deployment time rather than during `cdk synth`. This avoids CDK context lookups, cached values, and "double synth" behavior when parameters differ per environment.

const value = ssm.StringParameter
  .fromStringParameterAttributes(this, 'Param', {
    parameterName: '/my/plain/parameter',
  }).stringValue;

Secure:
const value = cdk.SecretValue.secretsManager('/my/secure/parameter');

2. Resolve at synth time:

Use this syntax when you need a fixed, environment-specific value at synthesis time instead of at deployment. This retrieves the actual SSM parameter value during cdk synth and stores it in the cdk.context.json file. Use this approach when conditional logic in your CDK code requires the literal value (e.g., if/else branching to decide which stacks or resources to include).

const value = ssm.StringParameter.valueForStringParameter(this, 'my-parameter-name');

Secure:
const value = cdk.SecretValue.ssmParameter('my-parameter-name');

3. Synthesis-time value (lookup)

Use this when you need the actual parameter value at synthesis time (not deployment). CDK will resolve it during `cdk synth`, cache it in `cdk.context.json`, and reuse it until refreshed. Ideal for feature flags or conditional logic that must run before deployment. Avoid for frequently changing values—requires re-synth to update.

const value = ssm.StringParameter.valueFromLookup(this, 'my-parameter-name');

https://docs.aws.amazon.com/cdk/v2/guide/get_ssm_value.html