amazon-web-servicesamazon-s3aws-cloudformation

How to loop through values in a CloudFormation template


I am trying to pass a list of comma separated parameters in an AWS CloudFormation template and create multiple Amazon S3 buckets based on those values.

I have a requirement where I will be passing a comma separated- list of country names and then the CloudFormation template would build that many S3 buckets (based on the names of countries passed in parameters).

For example, if I pass fr,us,gb in a parameter, the stack should create fr_myprod_bucket, us_myprod_bucket, gb_myprod_bucket.

I know there is no for loop in CloudFormation, so not sure how I can achieve this?


Solution

  • https://palletsprojects.com/p/jinja/ is another option for for-loops in CloudFormation templates. Render Jinja templates before passing them to CloudFormation, as CloudFormation itself cannot currently process Jinja.

      {% for country in ["fr", "us", "gb"] %}
      {{country}}_myprod_bucket:
        Type: AWS::S3::Bucket
      {% endfor %}
    

    That Jinja snippet produces:

      fr_myprod_bucket:
        Type: AWS::S3::Bucket
      
      us_myprod_bucket:
        Type: AWS::S3::Bucket
      
      gb_myprod_bucket:
        Type: AWS::S3::Bucket