Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ref inside Fn::Sub in Cloudformation

I am trying to use fn::sub with a Ref inside it.

I have a string "Comment xyz ${NAME}". This string comes as a parameter to the stack. Say the parameter name is "test".

I would now like to replace the ${NAME} in the string using fn::sub function inside the Cloudformation script.

fn::sub:[{"Ref":"test"},{"NAME":"balaji"}]

Expected output is "Comment xyz balaji".

However, this is the error I am getting:

Template validation error: Template error: One or more Fn::Sub intrinsic functions don't specify expected arguments. Specify a string as first argument, and an optional second argument to specify a mapping of values to replace in the string

Let me know what needs to be fixed here.

like image 593
Balaji V Avatar asked Jul 17 '18 11:07

Balaji V


People also ask

What does FN :: sub do?

Short description. You can use the Fn::Sub intrinsic function to substitute supported functions or to substitute variables in an input string with values that you specify.

What is FN :: GetAtt in CloudFormation?

The Fn::GetAtt intrinsic function returns the value of an attribute from a resource in the template. For more information about GetAtt return values for a particular resource, refer to the documentation for that resource in the Resource and property reference.

How do you reference parameters in CloudFormation?

Referencing a parameter within a template You use the Ref intrinsic function to reference a parameter, and AWS CloudFormation uses the parameter's value to provision the stack. You can reference parameters from the Resources and Outputs sections of the same template.

How does Ref work in CloudFormation?

The intrinsic function Ref returns the value of the specified parameter or resource. When you specify a parameter's logical name, it returns the value of the parameter. When you specify a resource's logical name, it returns a value that you can typically use to refer to that resource, such as a physical ID.


1 Answers

According to the docs, the first parameter in Fn::Sub must be:

A string with variables that AWS CloudFormation substitutes with their associated values at runtime. Write variables as ${MyVarName}. Variables can be template parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. If you specify only template parameter names, resource logical IDs, and resource attributes, don't specify a key-value map.

(Emphasis added.)

Thus, it is (at the time of writing) impossible to do this.

If you had a parameter:

"test": {
  "Type": "String",
  "Default": "Comment xyz ${NAME}"
}

And then a substitution:

"Fn::Sub": ["${test}", {"NAME": "balaji"}]

The substitution would yield the literal string Comment xyz ${NAME}.

like image 51
Alex Harvey Avatar answered Sep 19 '22 14:09

Alex Harvey