How to use parameters in AWS CDK?
Tags: cdk
Published: 2022-07-20 06:52:38


## Defining CDK Parameters

Use the optional Parameters section to customize your templates. Parameters enable you to input custom values to your template each time you create or update a stack.

To define a parameter, you use the [CfnParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnParameter.html) construct.

```typescript
// parameter of type String
const applicationPrefix = new CfnParameter(this, 'prefix', {
  description: 'parameter of type String',
  type: 'String',
  allowedPattern: '^[a-z0-9]*$', // allowed pattern for the parameter
  minLength: 3, // minimum length of the parameter
  maxLength: 20, // maximum length of the parameter
}).valueAsString // get the value of the parameter as string

console.log('application Prefix 👉', applicationPrefix)

// parameter of type Number
const applicationPort = new CfnParameter(this, 'port', {
  description: 'parameter of type Number',
  type: 'Number',
  minValue: 1, // minimum value of the parameter
  maxValue: 65535, // maximum value of the parameter
  allowedValues: ['8080', '8081'], // allowed values of the parameter
}).valueAsNumber // get the value of the parameter as number

console.log('application Port 👉', applicationPort)

// parameter of type CommaDelimitedList
const applicationDomains = new CfnParameter(this, 'domains', {
  description: 'parameter of type CommaDelimitedList',
  type: 'CommaDelimitedList',
}).valueAsList // get the value of the parameter as list of strings

console.log('application Domains 👉', applicationDomains)
```

**Note that the name (logical ID) of the parameter will derive from its name and location within the stack. Therefore, it is recommended that parameters are defined at the stack level.**

Let's over go what we did in the code snippet above.

We defined 3 parameters:

- `prefix`: a parameter of type String, with a minimum length of 3 and a maximum length of 20.
- `port`: a parameter of type Number, with a minimum value of 1 and a maximum value of 65535.
- `domains`: a parameter of type CommaDelimitedList.

CloudFormation currently supports the following parameter types:

- String – A literal string
- Number – An integer or float
- List – An array of integers or floats
- CommaDelimitedList – An array of literal strings that are separated by \* commas
- [AWS-specific parameter types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#aws-specific-parameter-types)
- [SSM parameter types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#aws-ssm-parameter-types)

If you try to deploy the stack without defining the parameters, the stack will fail.

`CdkStarterStackStack failed: Error: The following CloudFormation Parameters are missing a value: port, domains`

The parameter `prefix` is not required because it has a default value.

##

## Deploy a stack with parameters

```bash
npx aws-cdk deploy \
    --parameters prefix=demo \
    --parameters port=8081 \
    --parameters domains=www.codewithyou.com,www.freedevtool.com \
    --outputs-file ./cdk-outputs.json
```

Note that we have to use the --parameters flag for every parameter we pass into the template.

Now that we've successfully deployed our CDK application, we can inspect the parameters section in the CloudFormation console:

![Parameters in the CloudFormation console](https://www.codewithyou.com/_next/image?url=%2Fstatic%2Fimages%2Fhow-to-use-parameters-in-aws-cdk%2F1.png&w=1080&q=75)

Or we can use the `cdk-outputs.json` file to get the values of the parameters:

```bash
CdkStarterStackStack.applicationDomains = www.codewithyou.com,www.freedevtool.com
CdkStarterStackStack.applicationPort = 8081
CdkStarterStackStack.applicationPrefix = demo
```

If you are look into the `cdk.out/CdkStarterStackStack.template.json` file, you will see that parameters are defined in the `Parameters` section.

```json
{
  "Parameters": {
    "prefix": {
      "Type": "String",
      "Default": "sample",
      "AllowedPattern": "^[a-z0-9]*$",
      "Description": "parameter of type String",
      "MaxLength": 20,
      "MinLength": 3
    },
    "port": {
      "Type": "Number",
      "AllowedValues": ["8080", "8081"],
      "Description": "parameter of type Number",
      "MaxValue": 65535,
      "MinValue": 1
    },
    "domains": {
      "Type": "CommaDelimitedList",
      "Description": "parameter of type CommaDelimitedList"
    },
    "BootstrapVersion": {
      "Type": "AWS::SSM::Parameter::Value<String>",
      "Default": "/cdk-bootstrap/hnb659fds/version",
      "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]"
    }
  }
}
```

## Cleanup

Don't forget to delete the stack before leaving this article. Thanks for reading!

```bash
npx aws-cdk destroy
```

> **The code for this article is available on [GitHub](https://github.com/buithaibinh/aws-cdk-parameters-example)**