10

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?

22

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

|improve this answer|||||
0

Since it seems like the PrivateIpAddress property does not support an empty string as it value, I would suggest creating two separate resources of your AWS::EC2::Instance. One of them will have your condition RequestedPrivateIP while the other one should have the same condition but negated, e.g. DidNotRequestPrivateIP.

"InstanceWithPrivateIp": {
    "Type": "AWS::EC2::Instance",
    "Condition": "RequestedPrivateIP",
    "Properties": {
        [...]
    }
},

"InstanceWithoutPrivateIp": {
    "Type": "AWS::EC2::Instance",
    "Condition": "DidNotRequestPrivateIP",
    "Properties": {
        [...]
    }
}
|improve this answer|||||
  • 1
    That's indeed an option but severely breaks the DRY (Don't Repeat Yourself) principle that I'm not keen to do. Besides - there are often other properties that may or may not be set, for instance whether ELB listens on HTTPS based on whether a SSL certificate has been set. Trying to catch all these little variations by repeating all the declarations with a slight change would quickly lead to a massive unmaintainable template. But thanks for suggestion anyway. – MLu Dec 2 '14 at 20:34
  • I totally agree with you @MLu, repeating is never fun. However, from my experience with CloudFormation you're sometime forced to repeat yourself. The other solution I see is to create substacks instead that you include with the conditions I mentioned above and then in those substacks you do stuff that's specific for that condition. – Bazze Dec 3 '14 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.