Java Code Examples for com.amazonaws.services.ec2.AmazonEC2Client#describeInstances()

The following examples show how to use com.amazonaws.services.ec2.AmazonEC2Client#describeInstances() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SubnetPlugin.java    From fullstop with Apache License 2.0 6 votes vote down vote up
private List<Reservation> fetchReservations(final AmazonEC2Client amazonEC2Client, final CloudTrailEvent event, final List<String> instanceIds){
    final DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();


    DescribeInstancesResult describeInstancesResult = null;
    try {
        describeInstancesResult = amazonEC2Client
                .describeInstances(describeInstancesRequest.withInstanceIds(instanceIds));
    }
    catch (final AmazonServiceException e) {

        LOG.warn("Subnet plugin: {}", e.getErrorMessage());
        return null;
    }

    return describeInstancesResult.getReservations();

}
 
Example 2
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public List<Instance> getInstancesForZone(AvailabilityZone zone, AmazonEC2Client client)
    throws Exception {
  OperationStats op = new OperationStats("ec2InstanceStore", "getInstancesForZone");
  try {
    List<Instance> ret = new ArrayList<>();
    DescribeInstancesRequest request = new DescribeInstancesRequest()
        .withMaxResults(1000)
        .withFilters(new Filter("availability-zone", Arrays.asList(zone.getZoneName())))
        .withSdkClientExecutionTimeout(
            600 * 1000) //10 minutes time out for total execution including retries
        .withSdkRequestTimeout(300 * 1000); //5 minutes time out for a single request

    List<Reservation> reservations = new ArrayList<>();
    DescribeInstancesResult result = client.describeInstances(request);
    while (result != null) {
      reservations.addAll(result.getReservations());
      if (result.getNextToken() != null) {
        request.setNextToken(result.getNextToken());
        result = client.describeInstances(request);
      } else {
        result = null;
      }
    }

    for (Reservation reservation : reservations) {
      //Reservation refers to one launch command in EC2. Most time it should
      //only contains one instance
      for (Instance inst : reservation.getInstances()) {
        ret.add(inst);
      }
    }
    op.succeed();
    return ret;
  } catch (Exception ex) {
    op.failed();
    throw ex;
  }
}
 
Example 3
Source File: AwsTaggingService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void tagRootVolumes(AuthenticatedContext ac, AmazonEC2Client ec2Client, List<CloudResource> instanceResources, Map<String, String> userDefinedTags) {
    String stackName = ac.getCloudContext().getName();
    LOGGER.debug("Fetch AWS instances to collect all root volume ids for stack: {}", stackName);
    List<String> instanceIds = instanceResources.stream().map(CloudResource::getInstanceId).collect(Collectors.toList());
    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds));

    List<Instance> instances = describeInstancesResult.getReservations().stream().flatMap(res -> res.getInstances().stream()).collect(Collectors.toList());
    List<String> rootVolumeIds = instances.stream()
            .map(this::getRootVolumeId)
            .filter(Optional::isPresent)
            .map(blockDeviceMapping -> blockDeviceMapping.get().getEbs().getVolumeId())
            .collect(Collectors.toList());

    int instanceCount = instances.size();
    int volumeCount = rootVolumeIds.size();
    if (instanceCount != volumeCount) {
        LOGGER.debug("Did not find all root volumes, instanceResources: {}, found root volumes: {} for stack: {}", instanceCount, volumeCount, stackName);
    } else {
        LOGGER.debug("Found all ({}) root volumes for stack: {}", volumeCount, stackName);
    }

    AtomicInteger counter = new AtomicInteger();
    Collection<List<String>> volumeIdChunks = rootVolumeIds.stream()
            .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / MAX_RESOURCE_PER_REQUEST)).values();

    Collection<Tag> tags = prepareEc2Tags(ac, userDefinedTags);
    for (List<String> volumeIds : volumeIdChunks) {
        LOGGER.debug("Tag {} root volumes for stack: {}", volumeIds.size(), stackName);
        ec2Client.createTags(new CreateTagsRequest().withResources(volumeIds).withTags(tags));
    }
}
 
Example 4
Source File: AwsMetadataCollector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private List<Instance> collectInstancesForGroup(AuthenticatedContext ac, AmazonAutoScalingRetryClient amazonASClient,
        AmazonEC2Client amazonEC2Client, AmazonCloudFormationRetryClient amazonCFClient, String group) {

    LOGGER.debug("Collect aws instances for group: {}", group);

    String asGroupName = cloudFormationStackUtil.getAutoscalingGroupName(ac, amazonCFClient, group);
    List<String> instanceIds = cloudFormationStackUtil.getInstanceIds(amazonASClient, asGroupName);

    DescribeInstancesRequest instancesRequest = cloudFormationStackUtil.createDescribeInstancesRequest(instanceIds);
    DescribeInstancesResult instancesResult = amazonEC2Client.describeInstances(instancesRequest);

    return instancesResult.getReservations().stream()
            .flatMap(reservation -> reservation.getInstances().stream())
            .collect(Collectors.toList());
}
 
Example 5
Source File: BeanstalkConnector.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Collection<String> getEnvIPs(String envName, int timeout) {
    DescribeEnvironmentResourcesRequest request = new DescribeEnvironmentResourcesRequest()
            .withEnvironmentName(envName);
    List<Instance> instances = null;
    System.out.print("Waiting for environment ips");
    while(timeout-->0){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(BeanstalkConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.print("-");
        DescribeEnvironmentResourcesResult res = beanstalkClient.describeEnvironmentResources(request);
        instances = res.getEnvironmentResources().getInstances();
        if(instances.size()==0)
            continue;
        AmazonEC2Client ec2 = new AmazonEC2Client(awsCredentials);
        ec2.setEndpoint(beanstalkEndpoint.replace("elasticbeanstalk", "ec2"));
        List<String> instanceIds = new ArrayList<String>();
        for (Instance instance : instances) {
            instanceIds.add(instance.getId());
        }
        List<String> ips = new ArrayList<String>();
        DescribeInstancesRequest desins = new DescribeInstancesRequest().withInstanceIds(instanceIds);
        DescribeInstancesResult desinres = ec2.describeInstances(desins);
        for (Reservation reservation : desinres.getReservations()) {
            for (com.amazonaws.services.ec2.model.Instance ins : reservation.getInstances()) {
                String ip = ins.getPublicIpAddress();
                if(ip!=null && ip.length()>0)
                    ips.add(ip);
            }
        }
        if(ips.size()>0)
            return ips;

    }
    return Collections.EMPTY_LIST;
}
 
Example 6
Source File: EC2.java    From h2o-2 with Apache License 2.0 5 votes vote down vote up
private List<Instance> wait(AmazonEC2Client ec2, List<String> ids) {
  System.out.println("Establishing ssh connections, make sure security group '" //
      + securityGroup + "' allows incoming TCP 22.");
  boolean tagsDone = false;
  for( ;; ) {
    try {
      if( !tagsDone ) {
        CreateTagsRequest createTagsRequest = new CreateTagsRequest();
        createTagsRequest.withResources(ids).withTags(new Tag("Name", NAME));
        ec2.createTags(createTagsRequest);
        tagsDone = true;
      }
      DescribeInstancesRequest request = new DescribeInstancesRequest();
      request.withInstanceIds(ids);
      DescribeInstancesResult result = ec2.describeInstances(request);
      List<Reservation> reservations = result.getReservations();
      List<Instance> instances = new ArrayList<Instance>();
      for( Reservation reservation : reservations )
        for( Instance instance : reservation.getInstances() )
          if( ip(instance) != null )
            instances.add(instance);
      if( instances.size() == ids.size() ) {
        // Try to connect to SSH port on each box
        if( canConnect(instances) )
          return instances;
      }
    } catch( AmazonServiceException xe ) {
      // Ignore and retry
    }
    try {
      Thread.sleep(500);
    } catch( InterruptedException e ) {
      throw Log.errRTExcept(e);
    }
  }
}
 
Example 7
Source File: DescribeInstancesExample.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe all mock instances within aws-mock.
 *
 * @return a list of all instances
 */
public static List<Instance> describeAllInstances() {
    // pass any credentials as aws-mock does not authenticate them at all
    AWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    // the mock endpoint for ec2 which runs on your computer
    String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/";
    amazonEC2Client.setEndpoint(ec2Endpoint);

    DescribeInstancesResult response = amazonEC2Client.describeInstances();
    List<Reservation> reservations = response.getReservations();

    List<Instance> ret = new ArrayList<Instance>();

    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();

        if (null != instances) {

            for (Instance i : instances) {
                ret.add(i);
            }
        }
    }

    return ret;
}
 
Example 8
Source File: DescribeInstancesExample.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe specified instances within aws-mock.
 *
 * @param instanceIDs
 *            a list of instance IDs to describe
 * @return a list of specified instances
 */
public static List<Instance> describeInstances(final List<String> instanceIDs) {
    // pass any credentials as aws-mock does not authenticate them at all
    AWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    // the mock endpoint for ec2 which runs on your computer
    String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/";
    amazonEC2Client.setEndpoint(ec2Endpoint);

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.withInstanceIds(instanceIDs);

    DescribeInstancesResult response = amazonEC2Client.describeInstances(request);
    List<Reservation> reservations = response.getReservations();

    List<Instance> ret = new ArrayList<Instance>();

    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();

        if (null != instances) {

            for (Instance i : instances) {
                ret.add(i);
            }
        }
    }

    return ret;
}
 
Example 9
Source File: SimpleInstanceService.java    From sequenceiq-samples with Apache License 2.0 4 votes vote down vote up
@Override
public List<Reservation> describeInstances(AWSCredentials crendentials) {
	AmazonEC2Client client = amazonEC2ClientFactory.createAmazonEC2Client(crendentials);
	DescribeInstancesResult describeInstancesResult = client.describeInstances();
	return describeInstancesResult.getReservations();
}