Why use CloudFormation’s Transform Function?
There are two good reasons for using CloudFormation’s “Transform” function to include files. These two reasons are described below:
- By including a snippet in each and every CloudFormation template – you’ll ensure that the included code is the same, stack to stack.
- Code reuse.
- You won’t need to update code across multiple stacks when you need to make changes. You will need to update stacks to get changes made to the included files – but you won’t have to update the actual code in each stack.
How to do this?
Creating a CloudFormation File that uses an Include.
You need to include a Fn::Transform statement where the given file is to be included. An example included is below:
Fn::Transform: Name: AWS::Include Parameters: Location : s3://187376578462-fn-transform-include/ubuntu_ami.yaml
An example of an include in the “Mappings” section of a CloudFormation template would look like:
Mappings: Fn::Transform: Name: AWS::Include Parameters: Location : s3://187376578462-fn-transform-include/ubuntu_ami.yaml
Lastly, here is a screenshot of a CloudFormation file that uses an include – see line 29.
Creating the Included File
You will need to create a file that will be included in a given CloudFormation stack. This file is going to be inserted where the Fn::Transform statement is – this is akin to “import” or “include” in a programming language or “catting” two files together in a *nix Operating System.
The included file should look akin to the following:
AWSRegionArch2AMI: us-east-1: '64': ami-ddf13fb0 us-west-1: '64': ami-b20542d2 us-west-2: '64': ami-b9ff39d9
Uploading the Included File
The file that _will be_ included needs to be uploaded to S3. You can do this using the aws s3 command – see below:
aws s3 cp ubuntu_ami.yaml s3://$ubuntu_ami_file_s3_path --region us-west-2
Creating the CloudFormation Stack with an Include
You’ll need to use the “aws cloudformation deploy” command to deploy or update the given template. An example is below:
aws cloudformation deploy --stack-name FunctionTransformInclude --template-file autoscaling_with_yaml_userdata.yaml --parameter-overrides ubuntuAMISMapping3Location=s3://$ubuntu_ami_file_s3_path --region us-west-2
I’m planning on using for AMI mappings in particular, as well as for including sections of CloudFormation that might be better generated using code (for instance, user-data might be a consideration). I’ve yet to consider the use of “Fn::Transform / Include” to improve the security of stacks by removing passwords.
If you have questions or comments – reach me at firstname.lastname@example.org.