Search code examples
jsonamazon-web-servicesaws-cloudformationamazon-ecs

How to create AWS ECS cluster via AWS Cloudformation only if it DOES NOT exists


I am specifying following block of code in my .json to create a cluster via AWS cloudformation.

"MyCluster": {
      "Type" : "AWS::ECS::Cluster",
      "Properties" : {
      "ClusterName" : {
          "Ref": "EcsCluster"
        }
    }   
}

I would like to provision a exception condition to ignore cluster creation if cluster with a particular name already exists. Any help would be highly appreciated.


Solution

  • You can only conditionally create resources based on Conditions values, and all conditions are evaluated at 'start time' of the template, and based only on simple string and logical operations on your input parameters. So you can't do anything like use a custom resource to check if the cluster already exists and skip creating it if so.

    You could use a Custom Resource to munge the name of the ECS Cluster the stack creates, checking if your preferred name is already 'taken' and returning a different, non-conflicting name if so.

    If you need to eliminate the resource completely, you either need to add a parameter to turn it on or off:

    AWSTemplateFormatVersion: "2010-09-09"
    
    Parameters:
        CreateCluster:
            Type: "String"
            Description: "Whether to create the ECS Cluster"
            AllowedValues: [ "true", "false" ]
            Default: "false"
    ...
    
    Conditions:
        CreateCluster: { "Fn::Equals": [ { Ref: "CreateCluster" }, "true" ] }
    
    ....
    
    Resources:
        MyCluster:
            Type: "AWS::ECS::Cluster"
            Properties:
                ClusterName: { Ref: "EcsCluster" }
           Condition: "CreateCluster"
    

    Or you need to use a Transform to rewrite the template, check whether the cluster exists, and remove the resource definition if so.