'Template format error: Unresolved resource dependencies [ECSCluster] in the Resources block of the template

I have a condition to create or not the ECS Cluster and when I choose not to create it, indicating the boolean value false, Cloudformation returns the following error: Template format error: Unresolved resource dependencies [ECSCluster] in the Resources block of the template.

Below is a snippet of my code for this error:

Parameters:
  
  NameNewECSCluster:
    Type: String

  NameOldECSCluster:
    Type: String

  CreationECSCluster: 
    Type: String
    AllowedValues: [true, false]

Conditions:
  CreationECSClusterSelected: !Equals [!Ref CreationECSCluster, true]

  ECSCluster:
    Type: AWS::ECS::Cluster
    Condition: CreationECSClusterSelected
    Properties:
      ClusterName: !Ref NameNewECSCluster
      CapacityProviders:
        - FARGATE
        - FARGATE_SPOT
      Tags:
        - Key: CLUSTER
          Value: !Ref NameNewECSCluster

  ECSService:
    Type: AWS::ECS::Service
    DependsOn: ListenerHTTPforALB
    Properties:
      ServiceName: !Sub ${ApplicationName}-${Environment}
      Cluster: !If [CreationECSClusterSelected, !Ref ECSCluster, !Ref NameOldECSCluster]

The problem only occurs when I refer to a Cluster already created, when I create the Cluster inside the template it does not.

Does anyone have an idea how to resolve this?



Solution 1:[1]

If CreationECSClusterSelected is false, then ECSCluster does not exist and !Ref ECSCluster will result in the error. It does not matter the you have !If. Both false and true alternatives of your If must be valid as If gets executed after validation of your If statement. You can try with:

 Cluster: !If [CreationECSClusterSelected, !Ref NameNewECSCluster, !Ref NameOldECSCluster]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin