Conditional Property in AWS CloudFormation

amazon-cloudformationamazon-web-services

We've got an AWS CloudFormation template for creating some EC2 instances. Some of those however require a specific PrivateIpAddress and I'm struggling to figure out how to incorporate that to the template.

For now I've got a template parameter PrivateIP and a creating a Condition RequestedPrivateIP. So far so good. However I can't figure out how to incorporate it to the AWS::EC2::Instance resource specification. I tried this:

    "PrivateIpAddress": {
        "Fn::If": [ "RequestedPrivateIP",
            { "Ref": "PrivateIP" },
            ""                            <-- This doesn't work
        ]
    },

But that fails when RequestedPrivateIP is false with

CREATE_FAILED    AWS::EC2::Instance    NodeInstance    Invalid addresses: []

Any idea how to optionally assign a static Private IP and if not specified leave it to AWS to set a dynamic one?

Best Answer

i would change the structure to:

"PrivateIpAddress": {
    "Fn::If": [ "RequestedPrivateIP",
        { "Ref": "PrivateIP" },
        {"Ref" : "AWS::NoValue" }
    ]
}

the AWS::NoValue is there to give you the else option for your if statement. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html