12

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?

2 Answers 2

23

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

0
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": { [...] } } 
2
  • 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. Commented Dec 2, 2014 at 20:34
  • 1
    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. Commented Dec 3, 2014 at 7:47

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.