Java Code Examples for com.amazonaws.services.ec2.model.DescribeInstancesRequest#setInstanceIds()

The following examples show how to use com.amazonaws.services.ec2.model.DescribeInstancesRequest#setInstanceIds() . 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: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
   * Gets the instance details for ec 2.
   *
   * @param clientMap the client map
   * @param resourceId the resource id
   * @return the instance details for ec 2
   * @throws Exception the exception
   */
  public static Instance getInstanceDetailsForEc2(Map<String,Object> clientMap,String resourceId) throws Exception {
  	AmazonEC2 ec2Client = (AmazonEC2) clientMap.get("client");
  	DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setInstanceIds(Arrays.asList(resourceId));


RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
RetryRegistry registry = RetryRegistry.of(config);

Retry retry = registry.retry(describeInstancesRequest.toString());
 		
Function<Integer, Instance> decorated
  =  Retry.decorateFunction(retry, (Integer s) -> {
	  DescribeInstancesResult  describeInstancesResult =  ec2Client.describeInstances(describeInstancesRequest);
	  List<Reservation> reservations = describeInstancesResult.getReservations();
		Reservation reservation = reservations.get(0);
		List<Instance> instances = reservation.getInstances();
		return instances.get(0);
    });
return decorated.apply(1);
	
  }
 
Example 2
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<String> getInstanceName(String region, String instanceId) {
    final AmazonEC2 amazonEC2 = AmazonEC2ClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();

    List<String> instanceIds = new ArrayList<>();
    instanceIds.add(instanceId);

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);

    DescribeInstancesResult result = amazonEC2.describeInstances(request);
    Optional<String> tagOptional = result.getReservations()
            .stream()
            .flatMap(reservation -> reservation.getInstances().stream())
            .flatMap(instance -> instance.getTags().stream())
            .filter(tag -> NAME_ENTRY.equals(tag.getKey()))
            .findFirst()
            .map(Tag::getValue);
    return tagOptional;
}
 
Example 3
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
// @HystrixCommand(fallback = my coole exception)
// command for account id and client type -> generate new credentials
public void processEvent(final CloudTrailEvent event) {

    final String parameters = event.getEventData().getRequestParameters();
    final String instanceId = getFromParameters(parameters);

    final AmazonEC2 client = getClientForAccount(
            event.getEventData().getUserIdentity().getAccountId(),
            Region.getRegion(Regions.fromName(event.getEventData().getAwsRegion())));

    final DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(Collections.singleton(instanceId));

    // try
    final DescribeInstancesResult result = client.describeInstances(request);
    // catch credentials are old
    // throw new my coole exception ( account id, CLIENTTYPE.EC2, exception) -> this will trigger hystrix

    LOG.info("SAVING RESULT INTO MAGIC DB", result);
}
 
Example 4
Source File: BaseTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Describe instances.
 *
 * @param instanceIds            instances' IDs
 * @param enableLogging            log to standard out
 * @return list of instances
 */
protected final List<Instance> describeInstances(
        final Collection<String> instanceIds, final boolean enableLogging) {
    if (enableLogging) {
        log.info("Describe instances:" + toString(instanceIds));
    }
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);
    DescribeInstancesResult result = amazonEC2Client
            .describeInstances(request);
    Assert.assertTrue(result.getReservations().size() > 0);

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

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

        if (null != instances) {
            for (Instance i : instances) {
                instanceList.add(i);
            }
        }
    }

    return instanceList;
}
 
Example 5
Source File: Ec2TableProvider.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Calls DescribeInstances on the AWS EC2 Client returning all instances that match the supplied predicate and attempting
 * to push down certain predicates (namely queries for specific ec2 instance) to EC2.
 *
 * @See TableProvider
 */
@Override
public void readWithConstraint(BlockSpiller spiller, ReadRecordsRequest recordsRequest, QueryStatusChecker queryStatusChecker)
{
    boolean done = false;
    DescribeInstancesRequest request = new DescribeInstancesRequest();

    ValueSet idConstraint = recordsRequest.getConstraints().getSummary().get("instance_id");
    if (idConstraint != null && idConstraint.isSingleValue()) {
        request.setInstanceIds(Collections.singletonList(idConstraint.getSingleValue().toString()));
    }

    while (!done) {
        DescribeInstancesResult response = ec2.describeInstances(request);

        for (Reservation reservation : response.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                instanceToRow(instance, spiller);
            }
        }

        request.setNextToken(response.getNextToken());

        if (response.getNextToken() == null || !queryStatusChecker.isQueryRunning()) {
            done = true;
        }
    }
}
 
Example 6
Source File: AWSProvider.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 *  This method will retrieve the instance username that is used to log into the instance via ssh.
 *  E.g Ubuntu instance has username ubuntu
 *  CentOS instance has username centos
 *  The username must be present in the ami as a TAG with key USERNAME.
 *
 * @param region The aws region where instance is located
 * @param instanceId ID value for the instance
 * @return The username extracted from the TAG
 */
public Optional<String> getInstanceUserName(String region, String instanceId) {

    final AmazonEC2 amazonEC2 = AmazonEC2ClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();

    List<String> instanceIds = new ArrayList<>();
    instanceIds.add(instanceId);
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);
    DescribeInstancesResult result = amazonEC2.describeInstances(request);
    //Get instance id from the results
    Optional<String> imageId = result.getReservations().stream()
            .flatMap(reservation -> reservation.getInstances().stream())
            .findFirst()
            .map(Instance::getImageId);

    if (imageId.isPresent()) {
        List<String> imageIds = new ArrayList<>();
        imageIds.add(imageId.get());
        //get ami from the instance ID
        DescribeImagesRequest imageReq = new DescribeImagesRequest();
        imageReq.setImageIds(imageIds);
        //Get the Tag containing the username from the ami
        DescribeImagesResult describeImagesResult = amazonEC2.describeImages(imageReq);
        Optional<String> userName = describeImagesResult.getImages().stream()
                .flatMap(image -> image.getTags().stream())
                .filter(tag -> USERNAME_ENTRY.equals(tag.getKey()))
                .findFirst()
                .map(Tag::getValue);
        return userName;
    }
    return Optional.empty();
}
 
Example 7
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
/**
 * Get an EC2 instance from the instance id. It gets the Reservation and loop through the
 * instances
 * under the reservation for find the instane has the given id
 *
 * @param instanceId
 * @return EC2 instance
 * @throws Exception
 */
@Override
public Instance getInstance(String instanceId)
    throws Exception {
  Preconditions.checkNotNull(instanceId);
  Preconditions.checkNotNull(defaultClient);
  OperationStats ops = new OperationStats("es2InstanceStore", "getInstance");
  try {
    awsRateLimiter.acquire();
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(Arrays.asList(instanceId));
    DescribeInstancesResult result = defaultClient.describeInstances(request);

    for (Reservation reservation : result.getReservations()) {
      //Reservation refers to one launch command in EC2. Most time it should
      //only contain one instance
      for (Instance inst : reservation.getInstances()) {
        if (StringUtils.equals(inst.getInstanceId(), instanceId)) {
          ops.succeed();
          return inst;
        }
      }
    }
  } catch (Exception ex) {
    ops.failed();
    throw ex;
  }
  return null;
}
 
Example 8
Source File: Ec2MachineConfigurator.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether a VM is known (i.e. all the EC2 parts know it).
 * @return true if the VM is know, false otherwise
 */
private boolean checkVmIsKnown() {

	DescribeInstancesRequest dis = new DescribeInstancesRequest();
	dis.setInstanceIds(Collections.singletonList(this.machineId));

	DescribeInstancesResult disresult = this.ec2Api.describeInstances(dis);
	return disresult.getReservations().size() > 0
			&& disresult.getReservations().get( 0 ).getInstances().size() > 0;
}
 
Example 9
Source File: Ec2MachineConfigurator.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether a VM is started or not (which is stronger than {@link #checkVmIsKnown()}).
 * @return true if the VM is started, false otherwise
 */
private boolean checkVmIsStarted() {

	DescribeInstancesRequest dis = new DescribeInstancesRequest();
	dis.setInstanceIds(Collections.singletonList(this.machineId));

	DescribeInstancesResult disresult = this.ec2Api.describeInstances( dis );
	// Obtain availability zone (for later use, eg. volume attachment).
	// Necessary if no availability zone is specified in configuration
	// (because volumes must be attached to instances in the same availability zone).
	this.availabilityZone = disresult.getReservations().get(0).getInstances().get(0).getPlacement().getAvailabilityZone();
	return "running".equalsIgnoreCase( disresult.getReservations().get(0).getInstances().get(0).getState().getName());
}
 
Example 10
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe non terminated instances.
 *
 * @param instanceIds
 *            instances' IDs
 * @return list of non terminated instances
 */
protected final List<Instance> describeNonTerminatedInstances(
        final List<Instance> instanceIds) {
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(getInstanceIds(instanceIds));

    // set the request filter
    Filter nonTerminatedFilter = getNonTerminatedInstancesFilter();
    request.getFilters().add(nonTerminatedFilter);

    DescribeInstancesResult result = amazonEC2Client
            .describeInstances(request);
    Assert.assertTrue(result.getReservations().size() > 0);

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

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

        if (null != instances) {
            for (Instance i : instances) {
                instanceList.add(i);
            }
        }
    }

    return instanceList;
}