Example usage for com.amazonaws.services.route53.model ResourceRecord ResourceRecord

List of usage examples for com.amazonaws.services.route53.model ResourceRecord ResourceRecord

Introduction

In this page you can find the example usage for com.amazonaws.services.route53.model ResourceRecord ResourceRecord.

Prototype

public ResourceRecord(String value) 

Source Link

Document

Constructs a new ResourceRecord object.

Usage

From source file:br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsCommand.java

License:Apache License

protected void assignDomain(BindDomainsContext ctx, String record, String zoneId) {
    ChangeBatch changeBatch = new ChangeBatch();

    changeBatch.setComment(format("Updated for env %s", ctx.getCurEnv().getCNAME()));

    /**//ww w . j ava 2  s  .  c o m
     * Look for Existing Resource Record Sets
     */
    {
        ResourceRecordSet resourceRecordSet = null;

        ListResourceRecordSetsResult listResourceRecordSets = r53
                .listResourceRecordSets(new ListResourceRecordSetsRequest(zoneId));

        for (ResourceRecordSet rrs : listResourceRecordSets.getResourceRecordSets()) {
            if (!rrs.getName().equals(record)) {
                continue;
            }

            boolean matchesTypes = "A".equals(rrs.getType()) || "CNAME".equals(rrs.getType());

            if (!matchesTypes) {
                continue;
            }

            if (isInfoEnabled()) {
                info("Excluding resourceRecordSet %s for domain %s", rrs, record);
            }

            changeBatch.getChanges().add(new Change(ChangeAction.DELETE, rrs));
        }
    }

    /**
     * Then Add Ours
     */
    ResourceRecordSet resourceRecordSet = new ResourceRecordSet();

    resourceRecordSet.setName(record);
    resourceRecordSet.setType(RRType.A);

    if (ctx.singleInstance) {
        final String address = ctx.getCurEnv().getEndpointURL();
        ResourceRecord resourceRecord = new ResourceRecord(address);

        resourceRecordSet.setTTL(60L);
        resourceRecordSet.setResourceRecords(asList(resourceRecord));

        if (isInfoEnabled()) {
            info("Adding resourceRecordSet %s for domain %s mapped to %s", resourceRecordSet, record, address);
        }
    } else {
        AliasTarget aliasTarget = new AliasTarget();

        aliasTarget.setHostedZoneId(ctx.getElbHostedZoneId());
        aliasTarget.setDNSName(ctx.getCurEnv().getEndpointURL());

        resourceRecordSet.setAliasTarget(aliasTarget);

        if (isInfoEnabled()) {
            info("Adding resourceRecordSet %s for domain %s mapped to %s", resourceRecordSet, record,
                    aliasTarget.getDNSName());
        }
    }

    changeBatch.getChanges().add(new Change(ChangeAction.CREATE, resourceRecordSet));

    if (isInfoEnabled()) {
        info("Changes to be sent: %s", changeBatch.getChanges());
    }

    ChangeResourceRecordSetsRequest req = new ChangeResourceRecordSetsRequest(zoneId, changeBatch);

    r53.changeResourceRecordSets(req);
}

From source file:com.carrotgarden.maven.aws.dns.CarrotRoute53.java

License:BSD License

public ResourceRecordSet makeRecordCNAME(final String source, final String target) {

    final Collection<ResourceRecord> resourceList = new ArrayList<ResourceRecord>();
    resourceList.add(new ResourceRecord(target));

    final ResourceRecordSet record = new ResourceRecordSet();
    record.setName(source);//  ww  w. jav a 2s  .co  m
    record.setTTL(60L);
    record.setType("CNAME");
    record.setResourceRecords(resourceList);

    return record;
}

From source file:com.deploymentio.ec2namer.helpers.DnsRegistrar.java

License:Apache License

protected Change createName(NamerRequest req, LambdaContext context, String name) {

    Instance instance = instanceLookup.lookup(context, req.getInstanceId());

    boolean isVpc = req.isAlwaysUsePublicName() ? false : !StringUtils.isEmpty(instance.getVpcId());
    RRType recordType = isVpc ? RRType.A : RRType.CNAME;

    ResourceRecordSet set = new ResourceRecordSet(req.createFqdn(name) + ".", recordType);
    set.withTTL(60l);/*from w  w  w  .  ja va  2 s .co m*/
    set.withResourceRecords(
            new ResourceRecord(isVpc ? instance.getPrivateIpAddress() : instance.getPublicDnsName()));

    return new Change(ChangeAction.UPSERT, set);
}

From source file:com.deploymentio.ec2namer.helpers.DnsRegistrar.java

License:Apache License

protected Change createName(NamerRequest req, LambdaContext context, RequestedName additionalName,
        String assignedName) {//from   ww  w.ja va2s .c  om

    String fullAssignedName = req.createFqdn(assignedName);
    String fullAdditionalName = req.createFqdn(additionalName.getName());

    Instance instance = instanceLookup.lookup(context, req.getInstanceId());
    boolean usePublicHostname = req.isAlwaysUsePublicName() || StringUtils.isEmpty(instance.getVpcId());

    ResourceRecordSet set = new ResourceRecordSet(fullAdditionalName + ".", RRType.CNAME).withTTL(60l)
            .withResourceRecords(
                    new ResourceRecord(usePublicHostname ? instance.getPublicDnsName() : fullAssignedName))
            .withSetIdentifier(fullAssignedName).withWeight(Long.valueOf(additionalName.getWeight()));

    if (additionalName.isHealthChecked()) {

        String uuid = instance.getInstanceId() + "-" + UUID.randomUUID().toString();
        String hcId = null;

        for (int i = 0; i < 5; i++) {
            try {

                if (i > 0) {
                    Thread.sleep(5000);
                }

                CreateHealthCheckResult result = route53.createHealthCheck(
                        new CreateHealthCheckRequest().withCallerReference(uuid).withHealthCheckConfig(
                                new HealthCheckConfig().withFullyQualifiedDomainName(fullAssignedName)
                                        .withIPAddress(instance.getPublicIpAddress())
                                        .withPort(additionalName.getHealthCheckPort())
                                        .withType(additionalName.getHealthCheckType())
                                        .withResourcePath(additionalName.getHealthCheckUri())));

                hcId = result.getHealthCheck().getId();
                context.log("Created health-check: Name=" + fullAdditionalName + " Protocol="
                        + additionalName.getHealthCheckType() + " Port=" + additionalName.getHealthCheckPort()
                        + " Uri=" + additionalName.getHealthCheckUri() + " Id=" + hcId);

                // create tags on health-check
                route53.changeTagsForResource(new ChangeTagsForResourceRequest().withResourceId(hcId)
                        .withResourceType(TagResourceType.Healthcheck).withAddTags(
                                new Tag().withKey("Name").withValue(req.getEnvironment() + ":" + assignedName),
                                new Tag().withKey("InstanceId").withValue(req.getInstanceId())));

                break;

            } catch (Exception e) {
                context.log("Can't create health-check: Attempt= " + (i + 1) + " Name=" + fullAdditionalName
                        + " Protocol=" + additionalName.getHealthCheckType() + " Port="
                        + additionalName.getHealthCheckPort() + " Uri=" + additionalName.getHealthCheckUri()
                        + " Id=" + hcId + " Ref=" + uuid + " Error=" + e.getMessage());
            }
        }

        if (!StringUtils.isEmpty(hcId)) {
            set.setHealthCheckId(hcId);
        }
    }

    return new Change(ChangeAction.UPSERT, set);
}

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  ww  .j a v  a2 s  . c om*/
        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.renatodelgaudio.awsupdate.SimpleRecordService.java

License:Open Source License

@Override
public boolean updateRecord(String ip) {

    String recordName = config.getRecordName();

    ChangeResourceRecordSetsRequest changeRequest = new ChangeResourceRecordSetsRequest();
    changeRequest.setHostedZoneId(config.getZoneId());
    ChangeBatch batch = new ChangeBatch();
    Change change = new Change();

    ResourceRecordSet set = getCurrentRecordSet();
    if (set != null) {
        if (!equalsIgnoreCase("A", set.getType())) {
            log.error("Record already exists but not as Type A. No actions were performed.");
            return false;
        }/*ww w. ja v  a 2  s .com*/
        change.setAction("UPSERT");
        log.info("Record [" + recordName + "] already present on AWS Route 53. Upating it..");
    } else {
        change.setAction("CREATE");
        log.info("Record [" + recordName + "] not present on AWS Route 53. Creating it..");
        set = new ResourceRecordSet().withName(recordName).withType("A");
    }

    set.setTTL(Long.parseLong(config.getTTL()));
    List<ResourceRecord> l = new ArrayList<ResourceRecord>();
    l.add(new ResourceRecord(ip));
    set.setResourceRecords(l);

    change.setResourceRecordSet(set);
    batch.withChanges(change);

    changeRequest.setChangeBatch(batch);

    log.info("Updating DNS " + recordName + " with IP " + ip);

    ChangeResourceRecordSetsResult result = config.getAmazonRoute53Client()
            .changeResourceRecordSets(changeRequest);
    log.info(result.toString());
    return true;
}

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  . j a  va  2  s  .  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);

}

From source file:jp.classmethod.aws.gradle.route53.AmazonRoute53ChangeRecordSetTask.java

License:Apache License

@TaskAction
public void changeResourceRecordSets() {
    // to enable conventionMappings feature
    String hostedZoneId = getHostedZoneId();
    String rrsName = getRrsName();
    String resourceRecord = getResourceRecord();

    AmazonRoute53PluginExtension ext = getProject().getExtensions()
            .getByType(AmazonRoute53PluginExtension.class);
    AmazonRoute53 route53 = ext.getClient();

    route53.changeResourceRecordSets(new ChangeResourceRecordSetsRequest().withHostedZoneId(hostedZoneId)
            .withChangeBatch(new ChangeBatch()
                    .withChanges(new Change(ChangeAction.CREATE, new ResourceRecordSet(rrsName, RRType.CNAME)
                            .withResourceRecords(new ResourceRecord(resourceRecord))))));
    getLogger().info("change {} requested", hostedZoneId);
}

From source file:net.za.slyfox.dyn53.route53.Route53Updater.java

License:Apache License

/**
 * Updates the configured resource record set with the value of an IP address.
 *
 * @param inetAddress the address to update the resource record set with
 *//*w  w w .  jav a  2  s  . c  om*/
@Override
public void accept(InetAddress inetAddress) {
    final String address = inetAddress.getHostAddress();
    logger.info("Updating resource record set {} in hosted zone {} to {}", resourceRecordSetName, hostedZoneId,
            address);

    final ResourceRecordSet resourceRecordSet = new ResourceRecordSet(resourceRecordSetName,
            getResourceRecordType(inetAddress)).withResourceRecords(new ResourceRecord(address))
                    .withTTL(resourceRecordSetTtl);
    final Change change = new Change(ChangeAction.UPSERT, resourceRecordSet);
    final ChangeBatch changeBatch = new ChangeBatch().withChanges(change).withComment("Dyn53 update");

    final ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
            .withHostedZoneId(hostedZoneId).withChangeBatch(changeBatch);

    if (logger.isDebugEnabled()) {
        logger.debug("Requesting change: {}", change);
    }

    final ChangeResourceRecordSetsResult result = route53.changeResourceRecordSets(request);
    if (logger.isInfoEnabled()) {
        logger.info("Result of change request {}: {}", result.getChangeInfo().getId(),
                result.getChangeInfo().getStatus());
    }
}

From source file:org.ofbiz.tenant.amazonaws.AwsServices.java

License:Apache License

/**
 * create Amazon Rout53 resource record set
 * @param ctx//from   www.  j av  a 2 s  . com
 * @param context
 * @return
 */
public static Map<String, Object> createAmazonRoute53ResourceRecordSet(DispatchContext ctx,
        Map<String, Object> context) {
    String hostedZoneId = (String) context.get("hostedZoneId");
    String recordSetName = (String) context.get("recordSetName");
    String recordSetType = (String) context.get("recordSetType");
    List<String> domainNames = UtilGenerics.checkList(context.get("domainNames"));
    String dNSName = (String) context.get("dNSName");
    String resourceRecordSetId = (String) context.get("resourceRecordSetId");
    Long weight = (Long) context.get("weight");
    Long tTL = (Long) context.get("tTL");

    try {
        AmazonRoute53 route53 = AwsFactory.getAmazonRoute53();
        RRType rrType = AwsUtil.getRRType(recordSetType);
        ResourceRecordSet resourceRecordSet = new ResourceRecordSet(recordSetName, rrType);

        // set alias target
        if (UtilValidate.isNotEmpty(dNSName)) {
            AliasTarget aliasTarget = new AliasTarget(hostedZoneId, dNSName);
            resourceRecordSet.setAliasTarget(aliasTarget);
        }

        // set resource record set identifier
        if (UtilValidate.isNotEmpty(resourceRecordSetId)) {
            resourceRecordSet.setSetIdentifier(resourceRecordSetId);
        }

        // set resource records
        List<ResourceRecord> resourceRecords = FastList.newInstance();
        for (String domainName : domainNames) {
            ResourceRecord resourceRecord = new ResourceRecord(domainName);
            resourceRecords.add(resourceRecord);
        }
        resourceRecordSet.setResourceRecords(resourceRecords);

        // set weight
        if (UtilValidate.isEmpty(weight)) {
            weight = 0L;
        }
        resourceRecordSet.setWeight(weight);

        // set TTL
        if (UtilValidate.isEmpty(tTL)) {
            tTL = 300L;
        }
        resourceRecordSet.setTTL(tTL);

        Change change = new Change(ChangeAction.CREATE, resourceRecordSet);
        List<Change> changes = FastList.newInstance();
        changes.add(change);
        ChangeBatch changeBatch = new ChangeBatch(changes);
        ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest(hostedZoneId,
                changeBatch);
        ChangeResourceRecordSetsResult resourceRecordSetsResult = route53.changeResourceRecordSets(request);
        ChangeInfo changeInfo = resourceRecordSetsResult.getChangeInfo();
        String changeId = changeInfo.getId();
        String status = changeInfo.getStatus();
        Date submittedAt = changeInfo.getSubmittedAt();
        String comment = changeInfo.getComment();
        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("changeId", changeId);
        results.put("status", status);
        results.put("submittedAt", submittedAt);
        results.put("comment", comment);
        return results;
    } catch (Exception e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
}