Optional Parameter in CloudFormation

Michael Wittig – 23 Mar 2016

Sometimes you want a CloudFormation Parameter to be optional. Unfortunately a blank Parameter contains an empty string. If you pass this empty string to e.g. the KeyName Property of an EC2 Instance or Launch Configuration you end up with a validation error.

Imagine the following CloudFormation template:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Optional Parameters in CloudFormation: Problem",
"Parameters": {
"KeyName": {
"Description": "Provides the name of the EC2 key pair",
"Type": "String"
}
},
"Resources": {
"LaunchConfiguration": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Properties": {
"KeyName": {"Ref": "KeyName"}
[...]
}
}
}
}

If you leave the KeyName blank you will get the following error:

==Parameter validation failed: parameter value for parameter name KeyName does not exist. Rollback requested by user.==

The solution is the make use of CloudFormation Conditions, the Condition Function Fn::If and the Pseudo Parameter AWS::NoValue.

{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Optional Parameters in CloudFormation: Solution",
"Parameters": {
"KeyName": {
"Description": "Provides the name of the EC2 key pair",
"Type": "String"
}
},
"Conditions": {
"HasKeyName": {"Fn::Not": [{"Fn::Equals": ["", {"Ref": "KeyName"}]}]}
},
"Resources": {
"LaunchConfiguration": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Properties": {
"KeyName": {"Fn::If": ["HasKeyName", {"Ref": "KeyName"}, {"Ref": "AWS::NoValue"}]}
[...]
}
}
}
}

Now you can leave the KeyName parameter blank to not add a EC2 KeyPair to the LaunchConfiguration.

Michael Wittig

Michael Wittig

I’m the author of Amazon Web Services in Action. I work as a software engineer, and independent consultant focused on AWS and DevOps.

You can contact me via Email, Twitter, and LinkedIn.

Briefcase icon
Hire me
Cover of Rapid Docker on AWS

New book: Rapid Docker on AWS

A rapid way to get your web application up and running on AWS. Made for web developers and DevOps engineers who want to dockerize their web applications and run their containers on Amazon Web Services. Prior knowledge of Docker and AWS is not required.

Buy icon
Buy now
Marbot Logo

Incident Management for Slack

Team up to solve incidents with our chatbot marbot. Never miss a critical alert. Escalate alerts from your AWS infrastructure among your team members. Strong integrations with all parts of your AWS infrastructure: CloudWatch, Elastic Beanstalk, RDS, EC2, ...

Slack icon
Try for free