I have multiple parameter values stored in the AWS Systems Manager Parameter Store. I want to use these parameters dynamically in an AWS CloudFormation stack based on my requirements.
Short description
The following resolution uses Microsoft Windows and Linux as example environments to demonstrate how to use different parameters dynamically in a CloudFormation stack.
Important: When you use the following commands and template, make sure to replace Windows and Linux with your requirements.
Resolution
1. Open the AWS Systems Manager console.
2. In the navigation pane, choose Parameter Store.
3. Create Systems Manager parameters as type String to store Amazon Machine Image (AMI) IDs for Linux or Windows.
Linux:
LinuxAmiId - AMI-Id-for-Linux-resources
-or-
Windows:
WindowsAmiId - AMI-Id-for-Windows-resources
Note: Replace AMI-Id-for-Linux-resources and AMI-Id-for-Windows-resources with the AMI IDs for your resources.
4. Use the following example CloudFormation template to create the parameter that selects which AMI to use for deployment:
"Parameters": {
"AmiToUse": {
"Type": "String",
"AllowedValues": [
"windows",
"linux"
]
}
},
"Conditions": {
"CreateWindowsResources": {
"Fn::Equals": [
"windows",
{
"Ref": "AmiToUse"
}
]
}
},
"Resources": {
"EC2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": {
"Fn::If": [
"CreateWindowsResources",
"{{resolve:ssm:WindowsAmiId:1}}",
"{{resolve:ssm:LinuxAmiId:1}}"
]
}
}
}
}
Note: In the preceding template, if AmiToUse is selected as windows, then the CreateWindowsResources condition evaluates to true. CloudFormation uses the value stored at WindowsAmiId to provision the AWS::EC2::Instance resource. For Linux, the condition evaluates to false, and CloudFormation uses the value stored at LinuxAmiId to provision the AWS::EC2::Instance resource.
For more information on dynamic referencing, see Use dynamic references to specify template values.
Related information
CloudFormation Workshop: Dynamic reference lab