AWS CloudFormation Concepts Intrinsic Functions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(48 intermediate revisions by the same user not shown)
Line 6: Line 6:


* [[AWS CloudFormation Concepts#Intrinsic_Functions|AWS CloudFormation Concepts]]
* [[AWS CloudFormation Concepts#Intrinsic_Functions|AWS CloudFormation Concepts]]
* [[AWS CloudFormation Concepts Condition Functions|Condition Functions]]


=Ref=
=Overview=
 
All intrinsic functions have full function name:
Fn::ImportValue: ''stack_output_export_name
and a short form:
!ImportValue ''stack_output_export_name
 
Note that because of ":" presence in the full function syntax, the full function forms cannot be used as YAML map values, as such:
 
<syntaxhighlight lang='yaml'>
  ...
  SomeKey: Fn::ImportValue: something
</syntaxhighlight>
 
The template validation will fail with:
 
<syntaxhighlight lang='text'>
An error occurred (ValidationError) when calling the CreateStack operation: Template format error: YAML not well-formed. (line 15, column 24)
</syntaxhighlight>
 
To use the full function form, the value must be placed on a subsequent line, and indented as such:
 
<syntaxhighlight lang='yaml'>
  ...
  SomeKey:
    Fn::ImportValue: something
</syntaxhighlight>
 
There are situations when two short function names cannot be used together. The following will generate an invalid result:
 
<syntaxhighlight lang='yaml'>
  ...
  LogGroupName: !Join [ "-", [!Sub ${SomeParameter}, !ImportValue SomeOutput]]
</syntaxhighlight>
 
A solution to this is to combine full function form and short function form:
 
<syntaxhighlight lang='yaml'>
  ...
  LogGroupName:
    Fn::Join:
      - "-"
      -
        - !Sub ${SomeParameter}
        - !ImportValue SomeOutput
</syntaxhighlight>
 
For a more complex example, see [[AWS_CloudFormation_Concepts_Intrinsic_Functions#Combining_Join.2C_ImportValue_and_Sub|Combining Join, ImportValue and Sub]] below.
 
=<span id='Ref'></span>Ref:, !Ref=


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html Ref]}}
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html Ref]}}


The intrinsic function Ref returns the value of the object it refers to, such as a [[AWS_CloudFormation_Concepts#Input_Parameters|parameter]] or [[AWS_CloudFormation_Concepts#Resources|resource]]. When a parameter logical name is specified, it returns the value of the parameter. When a resource logical name is specified, it returns a value that can be typically used to refer to that resource, such as a physical ID.
The intrinsic function Ref: returns the value of the object it refers to, such as a [[AWS_CloudFormation_Concepts#Input_Parameters|parameter]] or [[AWS_CloudFormation_Concepts#Resources|resource]]. When a parameter logical name is specified, it returns the value of the parameter. When a resource logical name is specified, it returns a value that can be typically used to refer to that resource, such as a physical ID.
 
The '''full form''' of the function is:
 
Ref: ''reference''
 
Note that Ref is the only intrinsic function that does not have a Fn::''Name'': as full form.
 
The '''short form''' of the function is:
 
!Ref ''reference''
 
Note that no "${...}" should be used around the reference, the parser will actually detect that as syntax error.
 
Examples:


  !Ref AWS::StackName
  !Ref AWS::StackName
Line 17: Line 81:
  !Ref MyResourceName
  !Ref MyResourceName


=GetAtt=
=<span id='Sub'>Fn::Sub:, !Sub=
 
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html Sub]}}
 
The intrinsic function Fn::Sub: substitutes variables in an input string with specified values.
 
The '''full form''' of the function is:
 
Fn::Sub: ${''reference1''} is a ${''reference2''}
 
The '''short form''' of the function is:
 
!Sub ${''reference1''} is a ${''reference2''}
 
If only [[AWS_CloudFormation_Concepts#Template_Parameters|template parameters]], [[AWS_CloudFormation_Concepts#Resource_Logical_ID|resource logical IDs]] and [[AWS_CloudFormation_Concepts#Resource_Attributes|resource attributes]] are substituted in the String parameter, no variable map is required:
 
!Sub '${TemplateParameterA} is a ${TemplateParameterB}'
!Sub '${AWS::Region}-something'
 
Fn::Sub: can be used as a replacement for [[#GetAtt|Fn::GetAtt:]], as it seems to extract the attributes of a resource and place them in a string just fine. This is an example of how to obtain the ARN of a resource created in the same template:
 
===Using Sub to Configure the ARN of a Resource Created by the Template===
 
<syntaxhighlight lang='yaml'>
Resources:
 
  # this resource has an ARN
  AccessLogGroup:
    ...
 
  ...
 
  # this resource needs the ARN
  Stage:
    Type: AWS::ApiGateway::Stage
    Properties:
      ...
      AccessLogSetting:
        DestinationArn: !Sub '${AccessLogGroup.Arn}'
        ...
</syntaxhighlight>
 
=<span id='GetAtt'></span>Fn::GetAtt:, !GetAtt=


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html GetAtt]}}
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html GetAtt]}}
Line 44: Line 150:
</syntaxhighlight>
</syntaxhighlight>


=Join=
=<span id='ImportValue'></span>Fn::ImportValue:, !ImportValue=
 
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html ImportValue]}}
 
The Fn::ImportValue: returns the value of an [[AWS_CloudFormation_Concepts#Output|output]] exported by another stack. The function is used to create [[AWS_CloudFormation_Concepts#Cross-Stack_References|cross-stack references]].
 
The '''full form''' of the function is:
 
Fn::ImportValue: ''source-stack-export-name''
 
The '''short form''' of the function is:
 
!ImportValue ''source-stack-export-name''
 
Fn:: ImportValue: Can be used as a key in a YAML structure:
 
...
ServiceRole:
  Fn::ImportValue: ...
 
or a value:
 
...
EnvironmentVariables:
  - Name: TARGET_BUCKET
      Value:
        Fn::ImportValue: !Sub '${AWS::Region}-BuildBucket'
 
=<span id='Join'></span>Fn::Join:, !Join=


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-join.html Join]}}
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-join.html Join]}}


The Fn::Join function takes two parameters, a delimiter that separates the values you want to concatenate and an array of values in the order that you want them to appear.  
The Fn::Join function takes two parameters, a delimiter that separates the values to be joined (concatenated) and an array of values to be concatenated, in the order in which they should appear in the result.
 
The '''full form''' of the function is:
 
Fn::Join:
  - '<font color=teal>''delimiter''</font>'
  -
    - '<font color=teal>''first-value''</font>'
    - '<font color=teal>''second-value''</font>'
    - '<font color=teal>''third-value''</font>'
 
The '''short form''' of the function is:


  !Join [ <font color=teal>''delimiter''</font>, [ <font color=teal>''comma-delimited list of values''</font> ] ]
  !Join [ <font color=teal>''delimiter''</font>, [ <font color=teal>''comma-delimited list of values''</font> ] ]
Examples:


  !Join ['-', [ a, b, c ]]
  !Join ['-', [ a, b, c ]]
!Join ['-', !Split ['/', !Sub '${something}-something-else']]


returns "a:b:c"
returns "a:b:c"


=Split=
=<span id='Split'></span>Fn::Split:, !Spit=


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-split.html Split]}}
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-split.html Split]}}


  !Split ['.', "www.example.com"]
  !Split ['.', "www.example.com"]
!Split ['/', !Sub '${something}-something-else']


returns ["www", "example", "com"].
returns ["www", "example", "com"].


=Select=
=<span id='Select'></span>Fn::Select:, !Select=


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-select.html Select]}}
{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-select.html Select]}}


=Sub=
=<span id='FindInMap'></span>Fn::FindInMap:, !FindInMap=


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html Sub]}}
!FindInMap [ <font color=teal>''MapName''</font>, <font color=teal>''TopLevelKey''</font>, <font color=teal>''SecondLevelKey''</font> ]


Sub substitutes variables in an input string with specified values.
=Examples=


If only [[AWS_CloudFormation_Concepts#Template_Parameters|template parameters]], [[AWS_CloudFormation_Concepts#Resource_Logical_ID|resource logical IDs]] and [[AWS_CloudFormation_Concepts#Resource_Attributes|resource attributes]] are substituted in the String parameter, no variable map is required:
==Combining Join, ImportValue and Sub==


!Sub '${TemplateParameterA} is a ${TemplateParameterB}'
Exporter Stack:
!Sub '${AWS::Region}-something'
<syntaxhighlight lang='yaml'>
...
Outputs:
  SomeOuput:
    Value: square
    Export:
      Name: a-export
...
</syntaxhighlight>
Consumer Stack:
<syntaxhighlight lang='yaml'>
...
Parameters:
  SomeParameter:
    Type: String
    Default: a
Resources:
  TestLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName:
        Fn::Join:
          - "-"
          -
            - 'blue'
            - Fn::ImportValue:
                !Sub ${SomeParameter}-export
</syntaxhighlight>


=ImportValue=
The log group name will be "blue-square".


{{External|[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html ImportValue]}}
<syntaxhighlight lang='yaml'>
 
TaskDefinition:
The Fn::ImportValue returns the value of an [[AWS_CloudFormation_Concepts#Output|output]] exported by another stack. The function is used to create [[AWS_CloudFormation_Concepts#Cross-Stack_References|cross-stack references]].
  Properties:
 
    ...
Can be used as a key in a YAML structure:
    ContainerDefinitions:
 
        ...
...
        Environment:
ServiceRole:
          - Name: SPRING_DATASOURCE_URL
  Fn::ImportValue: ...
            Value:
 
              Fn::Join:
or a value:
                - '/'
 
                -
...
                  - 'jdbc:postgresql:'
EnvironmentVariables:
                  - ''
  - Name: TARGET_BUCKET
                  - Fn::ImportValue:
      Value:
                      !Sub ${MicroworldName}-${EnvironmentName}-postgres-endpoint-address
        Fn::ImportValue: !Sub '${AWS::Region}-BuildBucket'
                  - !Sub ${EnvironmentName}01
 
          - Name: SPRING_DATASOURCE_USERNAME
=FindInMap=
            Value:
 
              Fn::ImportValue:
!FindInMap [ <font color=teal>''MapName''</font>, <font color=teal>''TopLevelKey''</font>, <font color=teal>''SecondLevelKey''</font> ]
                !Sub ${MicroworldName}-${EnvironmentName}-postgres-username
          - Name: SPRING_DATASOURCE_PASSWORD
            Value:
              Fn::ImportValue:
                !Sub ${MicroworldName}-${EnvironmentName}-postgres-password
</syntaxhighlight>

Latest revision as of 21:49, 26 April 2019

External

Intrinsic Function Reference

Internal

Overview

All intrinsic functions have full function name:

Fn::ImportValue: stack_output_export_name

and a short form:

!ImportValue stack_output_export_name

Note that because of ":" presence in the full function syntax, the full function forms cannot be used as YAML map values, as such:

  ...
  SomeKey: Fn::ImportValue: something

The template validation will fail with:

An error occurred (ValidationError) when calling the CreateStack operation: Template format error: YAML not well-formed. (line 15, column 24)

To use the full function form, the value must be placed on a subsequent line, and indented as such:

  ...
  SomeKey:
    Fn::ImportValue: something

There are situations when two short function names cannot be used together. The following will generate an invalid result:

  ...
  LogGroupName: !Join [ "-", [!Sub ${SomeParameter}, !ImportValue SomeOutput]]

A solution to this is to combine full function form and short function form:

  ...
  LogGroupName:
    Fn::Join:
      - "-"
      -
        - !Sub ${SomeParameter}
        - !ImportValue SomeOutput

For a more complex example, see Combining Join, ImportValue and Sub below.

Ref:, !Ref

Ref

The intrinsic function Ref: returns the value of the object it refers to, such as a parameter or resource. When a parameter logical name is specified, it returns the value of the parameter. When a resource logical name is specified, it returns a value that can be typically used to refer to that resource, such as a physical ID.

The full form of the function is:

Ref: reference

Note that Ref is the only intrinsic function that does not have a Fn::Name: as full form.

The short form of the function is:

!Ref reference

Note that no "${...}" should be used around the reference, the parser will actually detect that as syntax error.

Examples:

!Ref AWS::StackName
!Ref MyParameter
!Ref MyResourceName

Fn::Sub:, !Sub

Sub

The intrinsic function Fn::Sub: substitutes variables in an input string with specified values.

The full form of the function is:

Fn::Sub: ${reference1} is a ${reference2}

The short form of the function is:

!Sub ${reference1} is a ${reference2}

If only template parameters, resource logical IDs and resource attributes are substituted in the String parameter, no variable map is required:

!Sub '${TemplateParameterA} is a ${TemplateParameterB}'
!Sub '${AWS::Region}-something'

Fn::Sub: can be used as a replacement for Fn::GetAtt:, as it seems to extract the attributes of a resource and place them in a string just fine. This is an example of how to obtain the ARN of a resource created in the same template:

Using Sub to Configure the ARN of a Resource Created by the Template

Resources:

  # this resource has an ARN
  AccessLogGroup:
    ...

  ...
  
  # this resource needs the ARN
  Stage:
    Type: AWS::ApiGateway::Stage
    Properties:
      ...
      AccessLogSetting:
        DestinationArn: !Sub '${AccessLogGroup.Arn}'
        ...

Fn::GetAtt:, !GetAtt

GetAtt

An intrinsic function that returns arbitrary attributes of a resource (Ref returns just important value associated with the resource). The function takes two parameters: the logical name of the resource and the attribute to be retrieved, as an array.

Using GetAtt to Configure the ARN of a Resource Created by the Template

Resources:

  # this resource has an ARN
  AccessLogGroup:
    ...

  ...
  
  # this resource needs the ARN
  Stage:
    Type: AWS::ApiGateway::Stage
    Properties:
      ...
      AccessLogSetting:
        DestinationArn: !GetAtt AccessLogGroup.Arn
        ...

Fn::ImportValue:, !ImportValue

ImportValue

The Fn::ImportValue: returns the value of an output exported by another stack. The function is used to create cross-stack references.

The full form of the function is:

Fn::ImportValue: source-stack-export-name

The short form of the function is:

!ImportValue source-stack-export-name

Fn:: ImportValue: Can be used as a key in a YAML structure:

...
ServiceRole:
  Fn::ImportValue: ...

or a value:

...
EnvironmentVariables:
  - Name: TARGET_BUCKET
     Value:
       Fn::ImportValue: !Sub '${AWS::Region}-BuildBucket'

Fn::Join:, !Join

Join

The Fn::Join function takes two parameters, a delimiter that separates the values to be joined (concatenated) and an array of values to be concatenated, in the order in which they should appear in the result.

The full form of the function is:

Fn::Join:
  - 'delimiter'
  -
    - 'first-value'
    - 'second-value'
    - 'third-value'

The short form of the function is:

!Join [ delimiter, [ comma-delimited list of values ] ]

Examples:

!Join ['-', [ a, b, c ]]
!Join ['-', !Split ['/', !Sub '${something}-something-else']]

returns "a:b:c"

Fn::Split:, !Spit

Split
!Split ['.', "www.example.com"]
!Split ['/', !Sub '${something}-something-else']

returns ["www", "example", "com"].

Fn::Select:, !Select

Select

Fn::FindInMap:, !FindInMap

!FindInMap [ MapName, TopLevelKey, SecondLevelKey ]

Examples

Combining Join, ImportValue and Sub

Exporter Stack:

... 
Outputs:
  SomeOuput:
    Value: square
    Export:
      Name: a-export
...

Consumer Stack:

...
Parameters:
  SomeParameter:
    Type: String
    Default: a
Resources:
  TestLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName:
        Fn::Join:
          - "-"
          -
            - 'blue'
            - Fn::ImportValue:
                !Sub ${SomeParameter}-export

The log group name will be "blue-square".

TaskDefinition:
  Properties:
    ...
    ContainerDefinitions:
        ...
        Environment:
          - Name: SPRING_DATASOURCE_URL
            Value:
              Fn::Join:
                - '/'
                -
                  - 'jdbc:postgresql:'
                  - ''
                  - Fn::ImportValue:
                      !Sub ${MicroworldName}-${EnvironmentName}-postgres-endpoint-address
                  - !Sub ${EnvironmentName}01
          - Name: SPRING_DATASOURCE_USERNAME
            Value:
              Fn::ImportValue:
                !Sub ${MicroworldName}-${EnvironmentName}-postgres-username
          - Name: SPRING_DATASOURCE_PASSWORD
            Value:
              Fn::ImportValue:
                !Sub ${MicroworldName}-${EnvironmentName}-postgres-password