Cloudformation: Optional Resource Parameters

When creating Cloudformation templates, occasionally, you come across situations where you only want to remove parameters from a Resource when on certain conditions. As an example, for an ECS Service resource, the parameters ‘LoadBalancers’ and ‘Role’ are both required only if you want your service to be serviced by a loadbalancer. However, you may not want to create two templates to serve these two use cases: 1. Service with LB registration, and 2. Service without LB registration.

In such cases, you can make use of Cloudformation’s conditions, conditionals, and pseudo parameters. This use-case is defined in AWS documentation, but it can be hard to end up on that page via a Google search for terms such as ‘Cloudformation optional parameter turn off’

Here’s a quick example to achieve this in Yaml:

    Type: 'AWS::ECS::Service'
      - LogGroup
          - CreateTargetGroup
            'Fn::Sub': '${ClusterStackName}-EcsServiceRole'
          - !Ref "AWS::NoValue"
      TaskDefinition: !Ref TaskDefinition
      DesiredCount: !Ref AppDesiredCount
          - CreateTargetGroup
            - TargetGroupArn: !Ref TargetGroup
              ContainerPort: !Ref AppContainerPort
              ContainerName: !Ref AppName
          - !Ref "AWS::NoValue"
      Cluster: !ImportValue
        'Fn::Sub': '${ClusterStackName}-ClusterName'
        - Field: 'attribute:ecs.availability-zone'
          Type: spread
        - Field: instanceId
          Type: spread
This entry was posted in Amazon Web Services, DevOps and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s