CloudFormation Intrinsic Functions - krdheeraj51/aws-labs GitHub Wiki
Overview
AWS CloudFormation provides several intrinsic functions that help you manage your stacks by assigning values to properties that are not available until runtime. These functions can be used in resource properties, outputs, metadata attributes, and update policy attributes.
Common Intrinsic Functions:
Ref:
Returns the value of a specified parameter or resource. Example:
Resources:
MyBucket:
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Ref "BucketNameParameter"
Fn::GetAtt:
Returns the value of an attribute from a resource.
Example:
Resources:
MyInstance:
Type: "AWS::EC2::Instance"
Properties:
InstanceType: "t2.micro"
ImageId: "ami-0abcdef1234567890"
Outputs:
InstancePublicIp:
Description: "Public IP address of the instance"
Value: !GetAtt "MyInstance.PublicIp"
Fn::Join:
Joins a list of values into a single value, separated by a specified delimiter. Example:
Resources:
MyBucket:
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Join [ "-", [ "my-bucket", !Ref "AWS::Region" ] ]
Fn::Sub:
Substitutes variables in an input string with values that you specify. Example:
Resources:
MyBucket:
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub "${AWS::StackName}-bucket"
Fn::FindInMap:
Returns a value from a specific key in a mapping declared in the Mappings section. Example:
Mappings:
RegionMap:
us-east-1:
AMI: "ami-0ff8a91507f77f867"
us-west-1:
AMI: "ami-0bdb828fd58c52235"
Resources:
MyInstance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: !FindInMap [ "RegionMap", !Ref "AWS::Region", "AMI" ]
Fn::If:
Returns one value if the specified condition evaluates to true and another value if it evaluates to false. Example:
Conditions:
CreateProdResources: !Equals [ !Ref "EnvironmentType", "prod" ]
Resources:
MyBucket:
Type: "AWS::S3::Bucket"
Properties:
BucketName: !If [ "CreateProdResources", "prod-bucket", "dev-bucket" ]
Fn::ImportValue: Imports values that are exported from another stack.
Example:
Resources:
MyInstance:
Type: "AWS::EC2::Instance"
Properties:
SecurityGroups: [ !ImportValue "MySecurityGroup" ]
Fn::Select: Returns a single object from a list of objects by index.
Example:
Resources:
MyInstance:
Type: "AWS::EC2::Instance"
Properties:
SubnetId: !Select [ 0, !Ref "SubnetIds" ]
Fn::Split: Splits a string into a list of string values based on a delimiter.
Example:
Resources:
MyInstance:
Type: "AWS::EC2::Instance"
Properties:
SecurityGroups: !Split [ ",", !Ref "SecurityGroupList" ]
Fn::Base64: Returns the Base64 representation of the input string.
Example:
Resources:
MyInstance:
Type: "AWS::EC2::Instance"
Properties:
UserData: !Base64 "echo Hello, World!"
These intrinsic functions provide powerful ways to dynamically configure and manage your CloudFormation stacks.