Example usage for com.amazonaws.services.ec2 AmazonEC2 associateAddress

List of usage examples for com.amazonaws.services.ec2 AmazonEC2 associateAddress

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2 associateAddress.

Prototype

AssociateAddressResult associateAddress(AssociateAddressRequest associateAddressRequest);

Source Link

Document

Associates an Elastic IP address with an instance or a network interface.

Usage

From source file:aws.example.ec2.AllocateAddress.java

License:Open Source License

public static void main(String[] args) {
    final String USAGE = "To run this example, supply an instance id\n" + "Ex: AllocateAddress <instance_id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);/* w  w  w .  j a  va 2s . co  m*/
    }

    String instance_id = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    AllocateAddressRequest allocate_request = new AllocateAddressRequest().withDomain(DomainType.Vpc);

    AllocateAddressResult allocate_response = ec2.allocateAddress(allocate_request);

    String allocation_id = allocate_response.getAllocationId();

    AssociateAddressRequest associate_request = new AssociateAddressRequest().withInstanceId(instance_id)
            .withAllocationId(allocation_id);

    AssociateAddressResult associate_response = ec2.associateAddress(associate_request);

    System.out.printf("Successfully associated Elastic IP address %s " + "with instance %s",
            associate_response.getAssociationId(), instance_id);
}

From source file:com.appdynamics.connectors.AWSConnector.java

License:Apache License

private void setElasticIp(IMachine machine, String elasticIp, AmazonEC2 connector) throws ConnectorException {
    try {/*from w ww .  j  a  v  a  2 s. co  m*/
        connector.associateAddress(new AssociateAddressRequest(machine.getName(), elasticIp));

        machine.setIpAddress(elasticIp);
    } catch (AmazonServiceException e) {
        throw new ConnectorException(e);
    } catch (AmazonClientException e) {
        throw new ConnectorException(e);
    }
}

From source file:com.netflix.eureka.aws.EIPManager.java

License:Apache License

/**
 * Checks if an EIP is bound and optionally binds the EIP.
 *
 * The list of EIPs are arranged with the EIPs allocated in the zone first
 * followed by other EIPs.//from  w w  w .  j  a  va2 s . c o  m
 *
 * If an EIP is already bound to this instance this method simply returns. Otherwise, this method tries to find
 * an unused EIP based on information from AWS. If it cannot find any unused EIP this method, it will be retried
 * for a specified interval.
 *
 * One of the following scenarios can happen here :
 *
 *  1) If the instance is already bound to an EIP as deemed by AWS, no action is taken.
 *  2) If an EIP is already bound to another instance as deemed by AWS, that EIP is skipped.
 *  3) If an EIP is not already bound to an instance and if this instance is not bound to an EIP, then
 *     the EIP is bound to this instance.
 */
public void bindEIP() {
    InstanceInfo myInfo = applicationInfoManager.getInfo();
    String myInstanceId = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.instanceId);
    String myZone = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.availabilityZone);

    Collection<String> candidateEIPs = getCandidateEIPs(myInstanceId, myZone);

    AmazonEC2 ec2Service = getEC2Service();
    boolean isMyinstanceAssociatedWithEIP = false;
    Address selectedEIP = null;

    for (String eipEntry : candidateEIPs) {
        try {
            String associatedInstanceId;

            // Check with AWS, if this EIP is already been used by another instance
            DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest()
                    .withPublicIps(eipEntry);
            DescribeAddressesResult result = ec2Service.describeAddresses(describeAddressRequest);
            if ((result.getAddresses() != null) && (!result.getAddresses().isEmpty())) {
                Address eipAddress = result.getAddresses().get(0);
                associatedInstanceId = eipAddress.getInstanceId();
                // This EIP is not used by any other instance, hence mark it for selection if it is not
                // already marked.
                if (((associatedInstanceId == null) || (associatedInstanceId.isEmpty()))) {
                    if (selectedEIP == null) {
                        selectedEIP = eipAddress;
                    }
                } else if (isMyinstanceAssociatedWithEIP = (associatedInstanceId.equals(myInstanceId))) {
                    // This EIP is associated with an instance, check if this is the same as the current instance.
                    // If it is the same, stop searching for an EIP as this instance is already associated with an
                    // EIP
                    selectedEIP = eipAddress;
                    break;
                } else {
                    // The EIP is used by some other instance, hence skip it
                    logger.warn("The selected EIP {} is associated with another instance {} according to AWS,"
                            + " hence skipping this", eipEntry, associatedInstanceId);
                }
            }
        } catch (Throwable t) {
            logger.error("Failed to bind elastic IP: {} to {}", eipEntry, myInstanceId, t);
        }
    }
    if (null != selectedEIP) {
        String publicIp = selectedEIP.getPublicIp();
        // Only bind if the EIP is not already associated
        if (!isMyinstanceAssociatedWithEIP) {

            AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest()
                    .withInstanceId(myInstanceId);

            String domain = selectedEIP.getDomain();
            if ("vpc".equals(domain)) {
                associateAddressRequest.setAllocationId(selectedEIP.getAllocationId());
            } else {
                associateAddressRequest.setPublicIp(publicIp);
            }

            ec2Service.associateAddress(associateAddressRequest);
            logger.info("\n\n\nAssociated {} running in zone: {} to elastic IP: {}", myInstanceId, myZone,
                    publicIp);
        }
        logger.info("My instance {} seems to be already associated with the EIP {}", myInstanceId, publicIp);
    } else {
        logger.info("No EIP is free to be associated with this instance. Candidate EIPs are: {}",
                candidateEIPs);
    }
}

From source file:com.netflix.eureka.util.EIPManager.java

License:Apache License

/**
 * Checks if an EIP is bound and optionally binds the EIP.
 *
 * The list of EIPs are arranged with the EIPs allocated in the zone first
 * followed by other EIPs.//from   www. jav a2s  .c  om
 *
 * If an EIP is already bound to this instance this method simply returns. Otherwise, this method tries to find
 * an unused EIP based on information from AWS. If it cannot find any unused EIP this method, it will be retried
 * for a specified interval.
 *
 * One of the following scenarios can happen here :
 *
 *  1) If the instance is already bound to an EIP as deemed by AWS, no action is taken.
 *  2) If an EIP is already bound to another instance as deemed by AWS, that EIP is skipped.
 *  3) If an EIP is not already bound to an instance and if this instance is not bound to an EIP, then
 *     the EIP is bound to this instance.
 */
public void bindEIP() {
    InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo();
    String myInstanceId = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.instanceId);
    String myZone = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.availabilityZone);

    Collection<String> candidateEIPs = getCandidateEIPs(myInstanceId, myZone);

    AmazonEC2 ec2Service = getEC2Service();
    boolean isMyinstanceAssociatedWithEIP = false;
    Address selectedEIP = null;

    for (String eipEntry : candidateEIPs) {
        try {
            String associatedInstanceId;

            // Check with AWS, if this EIP is already been used by another instance
            DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest()
                    .withPublicIps(eipEntry);
            DescribeAddressesResult result = ec2Service.describeAddresses(describeAddressRequest);
            if ((result.getAddresses() != null) && (!result.getAddresses().isEmpty())) {
                Address eipAddress = result.getAddresses().get(0);
                associatedInstanceId = eipAddress.getInstanceId();
                // This EIP is not used by any other instance, hence mark it for selection if it is not
                // already marked.
                if (((associatedInstanceId == null) || (associatedInstanceId.isEmpty()))) {
                    if (selectedEIP == null) {
                        selectedEIP = eipAddress;
                    }
                } else if (isMyinstanceAssociatedWithEIP = (associatedInstanceId.equals(myInstanceId))) {
                    // This EIP is associated with an instance, check if this is the same as the current instance.
                    // If it is the same, stop searching for an EIP as this instance is already associated with an
                    // EIP
                    selectedEIP = eipAddress;
                    break;
                } else {
                    // The EIP is used by some other instance, hence skip it
                    logger.warn(
                            "The selected EIP {} is associated with another instance {} according to AWS, hence "
                                    + "skipping this",
                            eipEntry, associatedInstanceId);
                }
            }
        } catch (Throwable t) {
            logger.error("Failed to bind elastic IP: " + eipEntry + " to " + myInstanceId, t);
        }
    }
    if (null != selectedEIP) {
        String publicIp = selectedEIP.getPublicIp();
        // Only bind if the EIP is not already associated
        if (!isMyinstanceAssociatedWithEIP) {

            AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest()
                    .withInstanceId(myInstanceId);

            String domain = selectedEIP.getDomain();
            if ("vpc".equals(domain)) {
                associateAddressRequest.setAllocationId(selectedEIP.getAllocationId());
            } else {
                associateAddressRequest.setPublicIp(publicIp);
            }

            ec2Service.associateAddress(associateAddressRequest);
            logger.info("\n\n\nAssociated " + myInstanceId + " running in zone: " + myZone + " to elastic IP: "
                    + publicIp);
        }
        logger.info("My instance {} seems to be already associated with the EIP {}", myInstanceId, publicIp);
    } else {
        logger.info("No EIP is free to be associated with this instance. Candidate EIPs are: " + candidateEIPs);
    }
}

From source file:com.urbancode.terraform.tasks.aws.helpers.AWSHelper.java

License:Apache License

/**
 * Assigns an elasticIp to an instance via the allocationId. Will return the public IP.
 *
 * @param instanceId//from   w  w  w . j av  a  2  s  . co m
 * @param allocationId
 * @param ec2Client
 * @return publicIp
 */
public String assignElasticIp(String instanceId, String allocationId, AmazonEC2 ec2Client) {
    AssociateAddressRequest assAddReq = new AssociateAddressRequest().withInstanceId(instanceId)
            .withAllocationId(allocationId);
    @SuppressWarnings("unused")
    AssociateAddressResult res = ec2Client.associateAddress(assAddReq);

    DescribeAddressesRequest req = new DescribeAddressesRequest().withAllocationIds(allocationId);
    String publicIp = ec2Client.describeAddresses(req).getAddresses().get(0).getPublicIp();

    log.info("Ip ( " + publicIp + " ) assigned to:" + instanceId);

    return publicIp;
}

From source file:ec2.AllocateAddress.java

License:Open Source License

public static void main(String[] args) {

    final String USAGE = "To run this example, supply an instance id\n" + "Ex: AllocateAddress <instance-id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);/*from  w ww.j  av  a 2s .c  o  m*/
    }

    String instanceId = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    AllocateAddressRequest allocateAddressRequest = new AllocateAddressRequest().withDomain(DomainType.Vpc);

    AllocateAddressResult allocateAddressResponsee = ec2.allocateAddress(allocateAddressRequest);

    String allocationId = allocateAddressResponsee.getAllocationId();

    AssociateAddressRequest request = new AssociateAddressRequest().withInstanceId(instanceId)
            .withAllocationId(allocationId);

    AssociateAddressResult response = ec2.associateAddress(request);

    System.out.printf("Successfully associated elastic ip address %s with instance %s",
            response.getAssociationId(), instanceId);
}

From source file:edu.umass.cs.aws.support.AWSEC2.java

License:Apache License

/**
 *
 * @param ec2/*from ww  w  .j a  va  2 s .c  o  m*/
 * @param ip
 * @param instance
 */
public static void associateAddress(AmazonEC2 ec2, String ip, Instance instance) {
    Address address;
    if ((address = findElasticIP(ec2, ip)) != null) {
        if (address.getDomain().equals("vpc")) {
            System.out.println("VPC Elastic IP:  " + ip);
            ec2.associateAddress(new AssociateAddressRequest().withInstanceId(instance.getInstanceId())
                    .withAllocationId(address.getAllocationId()));
        } else {
            System.out.println("EC2 Classic Elastic IP:  " + ip);
            ec2.associateAddress(new AssociateAddressRequest(instance.getInstanceId(), ip));
        }
    }
}

From source file:fr.xebia.workshop.continuousdelivery.CreateNexusInstance.java

License:Apache License

@Override
public void execute(AmazonEC2 ec2, WorkshopInfrastructure workshopInfrastructure) throws Exception {
    logger.info("STARTING CREATE NEXUS SERVER");

    // TERMINATE EXISTING NEXUS SERVERS IF EXIST
    AmazonAwsUtils.terminateInstancesByRole(TeamInfrastructure.ROLE_NEXUS, ec2);

    // CREATE NEXUS INSTANCE
    String cloudConfigFilePath = "fr/xebia/workshop/continuousdelivery/cloud-config-amzn-linux-nexus.txt";
    String userData = CloudInitUserDataBuilder.start().addCloudConfigFromFilePath(cloudConfigFilePath)
            .buildBase64UserData();/*from   ww w . j  a  v  a 2  s. c o m*/

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest() //
            .withInstanceType(InstanceType.T1Micro.toString()) //
            .withImageId(AmazonAwsUtils.AMI_AMZN_LINUX_EU_WEST) //
            .withMinCount(1) //
            .withMaxCount(1) //
            .withSecurityGroupIds("accept-all") //
            .withKeyName(KEY_PAIR_NAME) //
            .withUserData(userData);

    // START NEXUS INSTANCE
    List<Instance> nexusInstances = AmazonAwsUtils.reliableEc2RunInstances(runInstancesRequest, ec2);
    Instance nexusInstance = Iterables.getOnlyElement(nexusInstances);

    // TAG NEXUS INSTANCES
    CreateTagsRequest createTagsRequest = new CreateTagsRequest();
    createTagsRequest.withResources(nexusInstance.getInstanceId()) //
            .withTags(//
                    new Tag("Name", "nexus"), //
                    new Tag("Workshop", "continuous-delivery-workshop"), //
                    new Tag("Role", TeamInfrastructure.ROLE_NEXUS));
    ec2.createTags(createTagsRequest);

    // first waits for Nexus availability, otherwise the following elastic IP assignment will break its installation
    waitForNexusAvailability(nexusInstance);

    final String publicIp = workshopInfrastructure.getNexusPublicIp();

    // ASSOCIATE NEXUS INSTANCE WITH PUBLIC IP
    Address address = Iterables.getOnlyElement(
            ec2.describeAddresses(new DescribeAddressesRequest().withPublicIps(publicIp)).getAddresses());
    String currentlyAssociatedId = address.getInstanceId();
    if (currentlyAssociatedId == null) {
        logger.debug("Public IP {} is not currently associated with an instance", publicIp);
    } else {
        logger.info("Public IP {} is currently associated instance '{}'. Disassociate it first.", publicIp,
                currentlyAssociatedId);
        ec2.disassociateAddress(new DisassociateAddressRequest(publicIp));
    }

    ec2.associateAddress(new AssociateAddressRequest(nexusInstance.getInstanceId(), publicIp));

    try {
        AmazonAwsUtils.awaitForHttpAvailability(workshopInfrastructure.getNexusUrlWithIp());
        AmazonAwsUtils.awaitForHttpAvailability(workshopInfrastructure.getNexusUrlWithDomainName());
    } catch (Exception e) {
        logger.warn("Silently skipped " + e, e);
    }

    logger.info("1 NEXUS SERVER {} SUCCESSFULLY CREATED AND ASSOCIATED WITH {}: {}",
            new Object[] { nexusInstance.getInstanceId(), publicIp, nexusInstance });
}