List of usage examples for com.amazonaws.services.route53.model HostedZone getId
public String getId()
The ID that Amazon Route 53 assigned to the hosted zone when you created it.
From source file:br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsCommand.java
License:Apache License
@Override protected Void executeInternal(BindDomainsContext ctx) throws Exception { Map<String, String> recordsToAssign = new LinkedHashMap<String, String>(); ctx.singleInstance = isSingleInstance(ctx.getCurEnv()); /**/*from www. jav a 2 s.com*/ * Step #2: Validate Parameters */ { for (String domain : ctx.getDomains()) { String key = formatDomain(domain); String value = null; /* * Handle Entries in the form <record>:<zoneid> */ if (-1 != key.indexOf(':')) { String[] pair = key.split(":", 2); key = formatDomain(pair[0]); value = strip(pair[1], "."); } recordsToAssign.put(key, value); } Validate.isTrue(recordsToAssign.size() > 0, "No Domains Supplied!"); if (isInfoEnabled()) { info("Domains to Map to Environment (cnamePrefix='%s')", ctx.getCurEnv().getCNAME()); for (Map.Entry<String, String> entry : recordsToAssign.entrySet()) { String key = entry.getKey(); String zoneId = entry.getValue(); String message = format(" * Domain: %s", key); if (null != zoneId) { message += " (and using zoneId " + zoneId + ")"; } info(message); } } } /** * Step #3: Lookup Domains on Route53 */ Map<String, HostedZone> hostedZoneMapping = new LinkedHashMap<String, HostedZone>(); { Set<String> unresolvedDomains = new LinkedHashSet<String>(); for (Map.Entry<String, String> entry : recordsToAssign.entrySet()) { if (null != entry.getValue()) { continue; } unresolvedDomains.add(entry.getKey()); } for (HostedZone hostedZone : r53.listHostedZones().getHostedZones()) { String id = hostedZone.getId(); String name = hostedZone.getName(); hostedZoneMapping.put(id, hostedZone); if (unresolvedDomains.contains(name)) { if (isInfoEnabled()) { info("Mapping Domain %s to R53 Zone Id %s", name, id); } recordsToAssign.put(name, id); unresolvedDomains.remove(name); } } Validate.isTrue(unresolvedDomains.isEmpty(), "Domains not resolved: " + join(unresolvedDomains, "; ")); } /** * Step #4: Domain Validation */ { for (Map.Entry<String, String> entry : recordsToAssign.entrySet()) { String record = entry.getKey(); String zoneId = entry.getValue(); HostedZone hostedZone = hostedZoneMapping.get(zoneId); Validate.notNull(hostedZone, format("Unknown Hosted Zone Id: %s for Record: %s", zoneId, record)); Validate.isTrue(record.endsWith(hostedZone.getName()), format( "Record %s does not map to zoneId %s (domain: %s)", record, zoneId, hostedZone.getName())); } } /** * Step #5: Get ELB Hosted Zone Id - if appliable */ if (!ctx.singleInstance) { String loadBalancerName = parentMojo.getService() .describeEnvironmentResources(new DescribeEnvironmentResourcesRequest() .withEnvironmentId(ctx.getCurEnv().getEnvironmentId())) .getEnvironmentResources().getLoadBalancers().get(0).getName(); DescribeLoadBalancersRequest req = new DescribeLoadBalancersRequest(asList(loadBalancerName)); List<LoadBalancerDescription> loadBalancers = elb.describeLoadBalancers(req) .getLoadBalancerDescriptions(); Validate.isTrue(1 == loadBalancers.size(), "Unexpected number of Load Balancers returned"); ctx.elbHostedZoneId = loadBalancers.get(0).getCanonicalHostedZoneNameID(); if (isInfoEnabled()) { info(format("Using ELB Canonical Hosted Zone Name Id %s", ctx.elbHostedZoneId)); } } /** * Step #6: Apply Change Batch on Each Domain */ for (Map.Entry<String, String> recordEntry : recordsToAssign.entrySet()) { assignDomain(ctx, recordEntry.getKey(), recordEntry.getValue()); } return null; }
From source file:com.carrotgarden.maven.aws.dns.CarrotRoute53.java
License:BSD License
public List<String> listZone(final String source) { final List<String> nameList = new LinkedList<String>(); final HostedZone zone = findZone(source); if (zone == null) { return nameList; }// w w w .ja v a 2 s. c om final ListResourceRecordSetsRequest request = new ListResourceRecordSetsRequest(); request.setHostedZoneId(zone.getId()); while (true) { final ListResourceRecordSetsResult result = amazonClient.listResourceRecordSets(request); final List<ResourceRecordSet> recordList = result.getResourceRecordSets(); for (final ResourceRecordSet record : recordList) { nameList.add(record.getName()); } if (!result.isTruncated()) { break; } request.setStartRecordName(result.getNextRecordName()); } return nameList; }
From source file:com.carrotgarden.maven.aws.dns.CarrotRoute53.java
License:BSD License
public void ensureCNAME(final String source, final String target) throws Exception { final HostedZone zone = findZone(source); Util.assertNotNull(zone, "missing zone for " + source); final String zoneId = zone.getId(); final boolean isPresent; final ResourceRecordSet recordOld; {/*ww w .j a va2 s. c o m*/ final ResourceRecordSet recordFound = findRecord(zoneId, source); if (recordFound == null) { isPresent = false; recordOld = makeRecordCNAME(source, target); } else { isPresent = true; recordOld = recordFound; } } final ResourceRecordSet recordNew = makeRecordCNAME(source, target); recordNew.setTTL(recordOld.getTTL()); // final Collection<Change> changeList = new LinkedList<Change>(); if (isPresent) { changeList.add(new Change(ChangeAction.DELETE, recordOld)); changeList.add(new Change(ChangeAction.CREATE, recordNew)); } else { changeList.add(new Change(ChangeAction.CREATE, recordNew)); } final ChangeBatch changeRequest = new ChangeBatch(); changeRequest.setComment("updated : " + new Date()); changeRequest.setChanges(changeList); final ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest(); request.setHostedZoneId(zone.getId()); request.setChangeBatch(changeRequest); final ChangeResourceRecordSetsResult result = amazonClient.changeResourceRecordSets(request); final ChangeInfo changeResult = result.getChangeInfo(); logger.info("changeResult : \n{}", changeResult); }
From source file:com.deploymentio.ec2namer.helpers.DnsRegistrar.java
License:Apache License
@Override public boolean validate(NamerRequest req, LambdaContext context) { if (StringUtils.isEmpty(req.getBaseDomain())) { context.log("BaseDomain is missing"); return false; }/* w w w. j av a 2s . c o m*/ if (StringUtils.isEmpty(req.getEnvironment())) { context.log("Environment is missing"); return false; } if (StringUtils.isEmpty(req.getGroup())) { context.log("Group is missing"); return false; } if (StringUtils.isEmpty(req.getInstanceId())) { context.log("InstanceId is missing"); return false; } ListHostedZonesResult result = route53.listHostedZones(); String lookingFor = req.getBaseDomain() + "."; for (HostedZone zone : result.getHostedZones()) { if (lookingFor.equals(zone.getName())) { context.put("hosted-zone", zone.getId()); context.log("Found hosted-zone: Id=" + zone.getId() + " Name=" + zone.getName()); return true; } } context.log("HostedZone is not found: BaseDomain=" + req.getBaseDomain()); return false; }
From source file:com.github.blacklocus.rdsecho.EchoPromote.java
License:Open Source License
@Override boolean traverseStage(DBInstance instance) { LOG.info("Reading current DNS records"); String tld = EchoUtil.getTLD(cfg.promoteCname()) + '.'; HostedZone hostedZone = route53Find.hostedZone(nameEquals(tld)).get(); LOG.info(" Found corresponding HostedZone. name: {} id: {}", hostedZone.getName(), hostedZone.getId()); ResourceRecordSet resourceRecordSet = route53Find .resourceRecordSet(hostedZone.getId(), cnameEquals(cfg.promoteCname())).get(); ResourceRecord resourceRecord = getOnlyElement(resourceRecordSet.getResourceRecords()); LOG.info(" Found CNAME {} with current value {}", resourceRecordSet.getName(), resourceRecord.getValue()); Endpoint endpoint = instance.getEndpoint(); String tagEchoManaged = echo.getTagEchoManaged(); String dbInstanceId = instance.getDBInstanceIdentifier(); if (null == endpoint) { LOG.info("Echo DB instance {} (id: {}) has no address. Is it still initializing?", tagEchoManaged, dbInstanceId);// w w w . jav a2 s .co m return false; } String instanceAddr = endpoint.getAddress(); if (resourceRecord.getValue().equals(instanceAddr)) { LOG.info(" Echo DB instance {} ({}) lines up with CNAME {}. Nothing to do.", tagEchoManaged, instanceAddr, resourceRecordSet.getName()); return false; } else { LOG.info(" Echo DB instance {} ({}) differs from CNAME {}.", tagEchoManaged, instanceAddr, resourceRecordSet.getName()); } if (cfg.interactive()) { String format = "Are you sure you want to promote %s to be the new target of %s? Input %s to confirm."; if (!EchoUtil.prompt(dbInstanceId, format, dbInstanceId, cfg.promoteCname(), dbInstanceId)) { LOG.info("User declined to proceed. Exiting."); return false; } } LOG.info("Updating CNAME {} from {} to {}", cfg.name(), resourceRecord.getValue(), instanceAddr); ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest() .withHostedZoneId(hostedZone.getId()) .withChangeBatch(new ChangeBatch().withChanges( new Change(ChangeAction.UPSERT, new ResourceRecordSet(cfg.promoteCname(), RRType.CNAME) .withResourceRecords(new ResourceRecord(instanceAddr)).withTTL(cfg.promoteTtl())))); route53.changeResourceRecordSets(request); Optional<String[]> promoteTags = cfg.promoteTags(); if (promoteTags.isPresent()) { List<Tag> tags = EchoUtil.parseTags(promoteTags.get()); if (tags.size() > 0) { LOG.info("Applying tags on promote: {}", Arrays.asList(tags)); AddTagsToResourceRequest tagsRequest = new AddTagsToResourceRequest().withResourceName( RdsFind.instanceArn(cfg.region(), cfg.accountNumber(), instance.getDBInstanceIdentifier())); tagsRequest.setTags(tags); rds.addTagsToResource(tagsRequest); } } LOG.info("Searching for any existing promoted instance to demote."); return true; }
From source file:com.msi.dns53.client.DNS53MetadataUtil.java
License:Apache License
public void populateServiceMetadata(final ServletConfig config, String serviceName) { logger.debug("init(): TXT record will be created for this service regarding its port and context path."); String contextPath = config.getServletContext().getContextPath(); String port = Appctx.getBean("TOMCAT_PORT"); String master_passwd = Appctx.getBean("DB_PASSWORD"); final String fqdn = (String) ConfigurationUtil.getConfiguration(Arrays.asList(new String[] { "FQDN" })); final String domain = (String) ConfigurationUtil .getConfiguration(Arrays.asList(new String[] { "FQDN_DOMAIN" })); String txtRecordValue = ":" + port + contextPath; String baseDNSServerURL = "http://localhost:" + port + "/DNS53Server/2012-02-29/"; logger.debug("Tomcat port = " + port + "; FQDN = " + fqdn + "; domain = " + domain + "; TXT Record Value = " + txtRecordValue + "; BaseDNSServerUrl = " + baseDNSServerURL); DNS53Client client = new DNS53Client(baseDNSServerURL + "hostedzone", baseDNSServerURL + "change", "admin", master_passwd);//from ww w . j a v a 2s.co m logger.debug("Service name = " + serviceName); String recordName = serviceName + "-" + fqdn; logger.debug("TXT Record Name: " + recordName); logger.debug("init(): Calling ListHostedZones to find the target zone!"); ListHostedZonesRequest lhzReq = new ListHostedZonesRequest(); lhzReq.setMaxItems("1"); ListHostedZonesResult lhzResult = client.listHostedZones(lhzReq); HostedZone zone = null; List<HostedZone> zones = lhzResult.getHostedZones(); if (zones != null && zones.size() > 0) { for (HostedZone hz : zones) { if (hz.getName().equals(domain + ".") || hz.getName().equals(domain)) { zone = hz; } } } else { logger.error( "BaseAsyncServlet encountered an error while it was trying to find the target hosted zone."); throw ErrorResponse.InternalFailure(); } if (zone == null) { logger.error("BaseAsyncServlet could not find any zone for this TopStackWeb instance."); throw ErrorResponse.InternalFailure(); } // TODO (optional) check for the CNAME record for this service before proceeding logger.debug("init(): Creating a new TXT record for " + recordName + " with \"" + txtRecordValue + "\" as its value!"); String zoneId = zone.getId(); ChangeResourceRecordSetsRequest crrsReq = new ChangeResourceRecordSetsRequest(); crrsReq.setHostedZoneId(zoneId); ChangeBatch cb = new ChangeBatch(); cb.setComment( "BaseAsyncServlet => init(): Registering " + serviceName + " service for Transcend TopStack."); Collection<Change> changes = new LinkedList<Change>(); Change change = new Change(); change.setAction(ChangeAction.CREATE); ResourceRecordSet rrSet = new ResourceRecordSet(); rrSet.setName(recordName); rrSet.setTTL(900L); rrSet.setType(RRType.TXT); Collection<ResourceRecord> rr = new LinkedList<ResourceRecord>(); ResourceRecord record = new ResourceRecord(); record.setValue(txtRecordValue); rr.add(record); rrSet.setResourceRecords(rr); change.setResourceRecordSet(rrSet); changes.add(change); cb.setChanges(changes); crrsReq.setChangeBatch(cb); ChangeResourceRecordSetsResult result = client.changeResourceRecordSets(crrsReq); logger.debug("Result for the last ChangeResourceRecordSets request: " + result.toString()); }
From source file:com.msi.dns53.util.DNS53QueryUtil.java
License:Apache License
public static void marshallHostedZone(HostedZone hostedZone, XMLNode response) { XMLNode hz = QueryUtil.addNode(response, DNS53Constants.HOSTEDZONE); QueryUtil.addNode(hz, DNS53Constants.ID, hostedZone.getId()); QueryUtil.addNode(hz, DNS53Constants.NAME, hostedZone.getName()); QueryUtil.addNode(hz, DNS53Constants.CALLERREFERENCE, hostedZone.getCallerReference()); if (hostedZone.getConfig() != null) { XMLNode config = QueryUtil.addNode(hz, DNS53Constants.CONFIG); QueryUtil.addNode(config, DNS53Constants.COMMENT, hostedZone.getConfig().getComment()); }/*from w w w . ja v a 2 s. com*/ QueryUtil.addNode(hz, DNS53Constants.RESOURCERECORDSETCOUNT, hostedZone.getResourceRecordSetCount()); }
From source file:com.oneops.inductor.AbstractOrderExecutor.java
License:Apache License
/** * Gets dns servers/*from w w w .j a v a 2 s .c om*/ * * @param awsCredentials AWSCredentials * @param zoneDomainName zoneDomainName * @return dns servers */ private List<String> getAuthoritativeServersWithAwsCreds(AWSCredentials awsCredentials, String zoneDomainName) { if (!zoneDomainName.endsWith(".")) { zoneDomainName += "."; } AmazonRoute53 route53 = new AmazonRoute53Client(awsCredentials); ListHostedZonesResult result = route53.listHostedZones(); List<HostedZone> zones = result.getHostedZones(); List<String> dnsServers = new ArrayList<String>(); for (int i = 0; i < zones.size(); i++) { HostedZone hostedZone = zones.get(i); logger.info("zone: " + hostedZone.getName()); if (hostedZone.getName().equalsIgnoreCase(zoneDomainName)) { logger.info("matched zone"); GetHostedZoneResult zone = route53.getHostedZone( new GetHostedZoneRequest().withId(hostedZone.getId().replace("/hostedzone/", ""))); DelegationSet delegationSet = zone.getDelegationSet(); dnsServers = delegationSet.getNameServers(); break; } } logger.info("dnsServer: " + dnsServers.toString()); return dnsServers; }
From source file:fr.xebia.cloud.amazon.aws.tools.AmazonAwsUtils.java
License:Apache License
public static void deleteCnameIfExist(Iterable<String> cnames, HostedZone hostedZone, AmazonRoute53 route53) { // List all/*from w ww . j a va 2s . c om*/ ListResourceRecordSetsRequest listResourceRecordSetsRequest = new ListResourceRecordSetsRequest() // .withStartRecordType(RRType.CNAME) .withHostedZoneId(hostedZone.getId()); ListResourceRecordSetsResult listResourceRecordSetsResult = route53 .listResourceRecordSets(listResourceRecordSetsRequest); if (listResourceRecordSetsResult.isTruncated()) { logger.warn("truncated result"); } Function<ResourceRecordSet, String> cnameExtractor = new Function<ResourceRecordSet, String>() { @Override public String apply(@Nullable ResourceRecordSet resourceRecordSet) { if (resourceRecordSet == null) { return null; } if (!RRType.CNAME.equals(RRType.fromValue(resourceRecordSet.getType()))) { return null; } return resourceRecordSet.getName(); } }; Iterable<ResourceRecordSet> existingCnamesAsResourceRecordSet = Iterables .filter(listResourceRecordSetsResult.getResourceRecordSets(), new Predicate<ResourceRecordSet>() { @Override public boolean apply(@Nullable ResourceRecordSet resourceRecordSet) { return RRType.CNAME.equals(RRType.fromValue(resourceRecordSet.getType())); } }); final ImmutableMap<String, ResourceRecordSet> existingCnames = Maps .uniqueIndex(existingCnamesAsResourceRecordSet, cnameExtractor); Sets.SetView<String> cnamesToDelete = Sets.intersection(Sets.newHashSet(cnames), existingCnames.keySet()); Function<String, Change> cnameToDeleteCnameChange = new Function<String, Change>() { @Override public Change apply(@Nullable String cname) { ResourceRecordSet existingResourceRecordSet = existingCnames.get(cname); return new Change().withAction(ChangeAction.DELETE) .withResourceRecordSet(new ResourceRecordSet().withType(RRType.CNAME).withName(cname) .withTTL(existingResourceRecordSet.getTTL()) .withResourceRecords(existingResourceRecordSet.getResourceRecords())); } }; List<Change> changes = Lists.newArrayList(Iterables.transform(cnamesToDelete, cnameToDeleteCnameChange)); if (changes.isEmpty()) { logger.debug("No CNAME to delete"); return; } logger.info("Delete CNAME changes {}", changes); ChangeResourceRecordSetsRequest changeResourceRecordSetsRequest = new ChangeResourceRecordSetsRequest() .withHostedZoneId(hostedZone.getId()).withChangeBatch(new ChangeBatch().withChanges(changes)); route53.changeResourceRecordSets(changeResourceRecordSetsRequest); }
From source file:fr.xebia.cloud.amazon.aws.tools.AmazonAwsUtils.java
License:Apache License
public static void createCnamesForInstances(Map<String, Instance> cnameToInstances, HostedZone hostedZone, AmazonRoute53 route53) {/*from ww w . ja va2s . c om*/ Function<Map.Entry<String, Instance>, Change> cnameAndInstanceToChange = new Function<Map.Entry<String, Instance>, Change>() { @Override public Change apply(@Nullable Map.Entry<String, Instance> entry) { String cname = entry.getKey(); Instance instance = entry.getValue(); return new Change().withAction(ChangeAction.CREATE).withResourceRecordSet( new ResourceRecordSet().withType(RRType.CNAME).withName(cname).withTTL(300L) .withResourceRecords(new ResourceRecord(instance.getPublicDnsName()))); } }; List<Change> changes = Lists .newArrayList(Iterables.transform(cnameToInstances.entrySet(), cnameAndInstanceToChange)); logger.debug("Create CNAME {}", changes); ChangeResourceRecordSetsRequest changeResourceRecordSetsRequest = new ChangeResourceRecordSetsRequest() .withHostedZoneId(hostedZone.getId()).withChangeBatch(new ChangeBatch().withChanges(changes)); route53.changeResourceRecordSets(changeResourceRecordSetsRequest); }