I am trying to create a CloudFormation template that accepts an optional SSH key pair as a parameter. I want to use the AWS::EC2::KeyPair::KeyName
type so the CloudFormation interface gives the user a list of available keys like in the picture.
The problem I'm having is with the optional part. If the user leaves the selection empty, the default value is used but is not considered valid. I get:
Parameter validation failed: parameter value for parameter name SSHKey does not exist. Rollback requested by user.
Is there a way to define a parameter that can be left empty but has a non-generic type?
Here's a sample template that shows the problem:
{
"Parameters": {
"SSHKey": {
"Type": "AWS::EC2::KeyPair::KeyName",
"Description": "Leave empty to disable SSH",
"Default": ""
}
},
"Conditions": {
"EnableSSH": {
"Fn::Not": [
{
"Fn::Equals": [
"",
{
"Ref": "SSHKey"
}
]
}
]
}
},
"Resources": {
"LaunchConfig": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Properties": {
"ImageId": "ami-9eb4b1e5",
"InstanceType": "t2.micro",
"KeyName": {
"Fn::If": [
"EnableSSH",
{
"Ref": "SSHKey"
},
{
"Ref": "AWS::NoValue"
}
]
},
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xvda",
"Ebs": {
"VolumeSize": "8"
}
}
]
}
}
}
}
Kindly find the template based on your condition.
{
"Parameters":{
"SSHKey":{
"Type":"AWS::EC2::KeyPair::KeyName",
"Description":"select the keypair SSH",
"Default":""
},
"KeyPairRequired":{
"Type":"String",
"AllowedValues":[
"yes",
"no"
],
"Description":"Select yes/no whether to Add key pair to instance or not."
}
},
"Conditions":{
"CreateLCWithKeyPair":{
"Fn::Equals":[
{
"Ref":"KeyPairRequired"
},
"yes"
]
},
"CreateLCWithoutKeyPair":{
"Fn::Equals":[
{
"Ref":"KeyPairRequired"
},
"no"
]
}
},
"Resources":{
"LaunchConfigWithKey":{
"Condition":"CreateLCWithKeyPair",
"Type":"AWS::AutoScaling::LaunchConfiguration",
"Properties":{
"ImageId":"ami-9eb4b1e5",
"InstanceType":"t2.micro",
"KeyName":{
"Ref":"SSHKey"
},
"BlockDeviceMappings":[
{
"DeviceName":"/dev/xvda",
"Ebs":{
"VolumeSize":"8"
}
}
]
}
},
"LaunchConfigWithoutKey":{
"Condition":"CreateLCWithoutKeyPair",
"Type":"AWS::AutoScaling::LaunchConfiguration",
"Properties":{
"ImageId":"ami-9eb4b1e5",
"InstanceType":"t2.micro",
"BlockDeviceMappings":[
{
"DeviceName":"/dev/xvda",
"Ebs":{
"VolumeSize":"8"
}
}
]
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With