aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.58k stars 3.88k forks source link

(AWS-Route53): Check exists of a HostedZone by using fromLookUp #14755

Closed Fitmavincent closed 3 years ago

Fitmavincent commented 3 years ago

:question: General Issue

The Question

How do I utilise a error handling or try catch block to do a exist check of a resource.

let zone;
try {
  zone = HostedZone.fromLookup(scope, `${domainName}LookUpHostedZone`, {
    domainName: domainName
  });      
} catch (error) {
  zone = new PublicHostedZone(scope, `${domainName}HostedZone`, {
    zoneName: domainName
  });
}

the fromLookup methods fail immediately and what's the recommendation of performing a try catch block for operation like this?

Environment

Other information

Similar problems for other AWS resources: How to check if a custom VPC already exist using AWS CDK?

NGL321 commented 3 years ago

Hey @Fitmavincent,

The best way to do this is to use the SDK to try to get the HostedZone. This way the existence of the resource is determined not during deploy time but during synth. Additionally, this means that no extraneous Cloudformation actions are taken.

This is our standard method (something I have used a few times). It should look something like the below:

var AWS = require('aws-sdk');
AWS.config.update({region: 'REGION'});
var route53 = new AWS.Route53({apiVersion: '2016-11-15'});

let zone;
let params = {
    Id: 'XXXX'
};

route53.getHostedZone(params, function(err, data) {
  if (err) {
    zone = new PublicHostedZone(scope, `${domainName}HostedZone`, {
        zoneName: domainName
    });
  } else {
    console.log("Zone Exists");
  }
});

I hope that this helps! If this is not helpful guidance, please feel free to reopen and bug us about it again.

😸 😷

github-actions[bot] commented 3 years ago

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.