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:
Service: Type: 'AWS::ECS::Service' DependsOn: - LogGroup Properties: Role: !If - CreateTargetGroup - !ImportValue 'Fn::Sub': '${ClusterStackName}-EcsServiceRole' - !Ref "AWS::NoValue" TaskDefinition: !Ref TaskDefinition DesiredCount: !Ref AppDesiredCount LoadBalancers: !If - CreateTargetGroup - - TargetGroupArn: !Ref TargetGroup ContainerPort: !Ref AppContainerPort ContainerName: !Ref AppName - !Ref "AWS::NoValue" Cluster: !ImportValue 'Fn::Sub': '${ClusterStackName}-ClusterName' PlacementStrategies: - Field: 'attribute:ecs.availability-zone' Type: spread - Field: instanceId Type: spread