Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloudformation conditional templateURL

Is there a way to do conditional template urls in cloudformation?

This fails because it is not evaluated until the aws cloudformation deploy step and it errors out saying that the templateURL must be an s3 link. When I hard code in one of the urls it will upload that relative file to s3 and in the packaged final template it will just have the s3 url in place.

This doesn't work (pre aws cloudformation package step)

   Vpc:
    Type: 'AWS::CloudFormation::Stack'
    Properties:
      Parameters:
        AlertingModule: !GetAtt 'Alerting.Outputs.StackName'
        NatGateways: 'true'
      TemplateURL: !If [IsProduction, './default-vpc-module.yml', './production-vpc-module.yml']

When a url is hardcoded in it will package into this (post aws cloudformation pacakge step)

    VpcModule:
          Fn::GetAtt:
          - Vpc
          - Outputs.StackName
        AlertingModule:
          Fn::GetAtt:
          - Alerting
          - Outputs.StackName
        Priority: '2'
        HealthCheckPath: /health-check.php
      TemplateURL: https://s3.amazonaws.com/my-cicd-bucket-/fe556ff9386a28c063c4a110b31b.template
like image 967
Brian McCall Avatar asked Oct 20 '25 03:10

Brian McCall


1 Answers

Yes you absolutely can achieve what your after, the way i did it was reference the s3 url, by using an aws cloudformaiton package but also a s3 cp in the codebuild stage to enforce naming conventions on the url. As long as your template url paths are distinguished differently.

To provide a very flexible example, you could use !Sub with an !If replacement statement on the dynamic name component, which will also allow your to use !Ref inside the !If statement:

Parameters:
  StageProd:
    Description: Environment
    Default: "production"
    Type: String
.......

......
    TemplateURL: !Sub 
        - https://${CfnBucketName}.s3-ap-southeast-2.amazonaws.com/${CfnKeyPrefix}/SomeFileName-${Stage}.yaml
        - { Stage: !If [ IsProduction, !Ref StageProd, "default"]}

The above should meet almost any sort of combination of dynamic naming you want to achieve; however, you could also very much simplify the above with a simple !Sub replacing the stage name.

like image 153
pkarfs Avatar answered Oct 21 '25 17:10

pkarfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!