CloudFormation Resource Creation if not exist

ColossusMark1 picture ColossusMark1 · Mar 5, 2019 · Viewed 10k times · Source

I want to create Route53 HostedZone with CloudFormation so I want to check some information in Route53 about HostedZone is exist.

In logic of my case I need check if resource is exist, ignore the resource creation. How I can handle this problem.

My CloudFormation template show at below.

"myDNSRecord" : {
  "Type" : "AWS::Route53::RecordSet",
  "Properties" : {
    "HostedZoneName" : { "Ref" : "HostedZoneResource" },
    "Comment" : "DNS name for my instance.",  
    "Name" : {
      "Fn::Join" : [ "", [
        {"Ref" : "Ec2Instance"}, ".",
        {"Ref" : "AWS::Region"}, ".",
        {"Ref" : "HostedZone"} ,"."
      ] ]
    },
    "Type" : "A",
    "TTL" : "900",
    "ResourceRecords" : [
      { "Fn::GetAtt" : [ "Ec2Instance", "PublicIp" ] }
    ]
  }
}

Answer

asr9 picture asr9 · Mar 5, 2019

This is not exactly the answer you need. But in general, you can use Conditions for this. In you template, you define your condition in Conditions section and use it to conditionally create the resource. e.g.

Parameters:
  EnvironmentSize:
    Type: String
    Default: Micro
    AllowedValues:
      - Micro
      - Small
      - Medium
      - AuroraCluster
Conditions:
  isntAuroraCluster:
    !Not [!Equals [!Ref EnvironmentSize, "AuroraCluster"]]
DBInstance:
  Type: AWS::RDS::DBInstance
  Condition: isntAuroraCluster
  Properties:
    DBInstanceClass: !FindInMap [InstanceSize, !Ref EnvironmentSize, DB]
    <Rest of properties>

Here my RDS DBinstance is only created if my environment size is not AuroraCluster.

If you don't find a better solution, you could take that as user input (whether to create a record set or not) & use that as condition to create your resource. Hope it helps.