Java Code Examples for com.amazonaws.services.ec2.AmazonEC2#describeInstances()
The following examples show how to use
com.amazonaws.services.ec2.AmazonEC2#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: AWSProvider.java From testgrid with Apache License 2.0 | 6 votes |
@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 2
Source File: ExamplePlugin.java From fullstop with Apache License 2.0 | 6 votes |
@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 3
Source File: AWSSdkClient.java From incubator-gobblin with Apache License 2.0 | 6 votes |
/*** * Get list of EC2 {@link Instance}s for a auto scaling group * * @param groupName Auto scaling group name * @param status Instance status (eg. running) * @return List of EC2 instances found for the input auto scaling group */ public List<Instance> getInstancesForGroup(String groupName, String status) { final AmazonEC2 amazonEC2 = getEc2Client(); final DescribeInstancesResult instancesResult = amazonEC2.describeInstances(new DescribeInstancesRequest() .withFilters(new Filter().withName("tag:aws:autoscaling:groupName").withValues(groupName))); final List<Instance> instances = new ArrayList<>(); for (Reservation reservation : instancesResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (null == status|| null == instance.getState() || status.equals(instance.getState().getName())) { instances.add(instance); LOGGER.info("Found instance: " + instance + " which qualified filter: " + status); } else { LOGGER.info("Found instance: " + instance + " but did not qualify for filter: " + status); } } } return instances; }
Example 4
Source File: EC2ClientActions.java From cloudbreak with Apache License 2.0 | 6 votes |
public List<String> getInstanceVolumeIds(List<String> instanceIds) { AmazonEC2 ec2Client = buildEC2Client(); DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds)); Map<String, Set<String>> instanceIdVolumeIdMap = describeInstancesResult.getReservations() .stream() .map(Reservation::getInstances) .flatMap(Collection::stream) .collect(Collectors.toMap(Instance::getInstanceId, instance -> instance.getBlockDeviceMappings() .stream() .filter(dev -> !"/dev/xvda".equals(dev.getDeviceName())) .map(InstanceBlockDeviceMapping::getEbs) .map(EbsInstanceBlockDevice::getVolumeId) .collect(Collectors.toSet()) )); instanceIdVolumeIdMap.forEach((instanceId, volumeIds) -> Log.log(LOGGER, format(" Attached volume IDs are %s for [%s] EC2 instance ", volumeIds.toString(), instanceId))); return instanceIdVolumeIdMap .values() .stream() .flatMap(Collection::stream) .collect(Collectors.toList()); }
Example 5
Source File: EC2Utils.java From amazon-kinesis-connectors with Apache License 2.0 | 6 votes |
/** * Return the DNS name of one Amazon EC2 instance with the provided filter name and value. * * @param ec2Client * an Amazon EC2 instance * @param filterName * the name of the filter * @param filterValue * the value of the filter * @return the public DNS name of an instance with the filter name and value. Null if none exist. */ public static String getEndpointForFirstActiveInstanceWithTag(AmazonEC2 ec2Client, String filterName, String filterValue) { DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withFilters(new Filter().withName(filterName).withValues(filterValue)); DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest); List<Reservation> reservations = describeInstancesResult.getReservations(); for (Reservation reservation : reservations) { List<Instance> ec2Instances = reservation.getInstances(); for (Instance ec2Instance : ec2Instances) { if (InstanceStateName.Running.toString().equals(ec2Instance.getState().getName())) { return ec2Instance.getPublicDnsName(); } } } return null; }
Example 6
Source File: InventoryUtil.java From pacbot with Apache License 2.0 | 5 votes |
/** * Fetch instances. * * @param temporaryCredentials the temporary credentials * @param skipRegions the skip regions * @param accountId the accountId * @param accountName the account name * @param ec2Filters the ec 2 filters * @return the map */ public static Map<String,List<Instance>> fetchInstances(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName,String ec2Filters){ Map<String,List<Instance>> instanceMap = new LinkedHashMap<>(); AmazonEC2 ec2Client ; String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"EC2\" , \"region\":\"" ; List<String> stateNameFilters = Arrays.asList(ec2Filters.split(",")); for(Region region : RegionUtils.getRegions()) { try{ if(!skipRegions.contains(region.getName())){ ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build(); List<Instance> instanceList = new ArrayList<>(); DescribeInstancesResult descInstResult ; String nextToken = null; do{ descInstResult = ec2Client.describeInstances(new DescribeInstancesRequest().withNextToken(nextToken)); descInstResult.getReservations().forEach( reservation -> instanceList.addAll(reservation.getInstances().stream().filter(instance->stateNameFilters.contains(instance.getState().getName())).collect(Collectors.toList()))); nextToken = descInstResult.getNextToken(); }while(nextToken!=null); if(!instanceList.isEmpty() ) { log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 "+ region.getName()+" >> " + instanceList.size()); instanceMap.put(accountId+delimiter+accountName+delimiter+region.getName(), instanceList); } } }catch(Exception e){ log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}"); ErrorManageUtil.uploadError(accountId,region.getName(),"ec2",e.getMessage()); } } return instanceMap; }
Example 7
Source File: AWSProvider.java From testgrid with Apache License 2.0 | 5 votes |
private static DescribeInstancesResult getDescribeInstancesResult(String stackName, String region) { final AmazonEC2 amazonEC2 = getAmazonEC2(region); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.withFilters( new Filter("tag:" + STACK_NAME_TAG_KEY).withValues(stackName)); return amazonEC2.describeInstances(request); }
Example 8
Source File: AWSProvider.java From testgrid with Apache License 2.0 | 5 votes |
/** * 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 9
Source File: DescribeInstances.java From aws-doc-sdk-examples with Apache License 2.0 | 5 votes |
public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); boolean done = false; DescribeInstancesRequest request = new DescribeInstancesRequest(); while(!done) { DescribeInstancesResult response = ec2.describeInstances(request); for(Reservation reservation : response.getReservations()) { for(Instance instance : reservation.getInstances()) { System.out.printf( "Found instance with id %s, " + "AMI %s, " + "type %s, " + "state %s " + "and monitoring state %s", instance.getInstanceId(), instance.getImageId(), instance.getInstanceType(), instance.getState().getName(), instance.getMonitoring().getState()); } } request.setNextToken(response.getNextToken()); if(response.getNextToken() == null) { done = true; } } }
Example 10
Source File: AwsInstanceConnector.java From cloudbreak with Apache License 2.0 | 5 votes |
private Collection<String> instanceIdsWhichAreNotInCorrectState(List<CloudInstance> vms, AmazonEC2 amazonEC2Client, String state) { Set<String> instances = vms.stream().map(CloudInstance::getInstanceId).collect(Collectors.toCollection(HashSet::new)); DescribeInstancesResult describeInstances = amazonEC2Client.describeInstances( new DescribeInstancesRequest().withInstanceIds(instances)); for (Reservation reservation : describeInstances.getReservations()) { for (Instance instance : reservation.getInstances()) { if (state.equalsIgnoreCase(instance.getState().getName())) { instances.remove(instance.getInstanceId()); } } } return instances; }
Example 11
Source File: EC2Api.java From ec2-spot-jenkins-plugin with Apache License 2.0 | 4 votes |
private static void describeInstancesBatch( final AmazonEC2 ec2, final Map<String, Instance> described, final List<String> batch) { // we are going to modify list, so copy final List<String> copy = new ArrayList<>(batch); // just to simplify debug by having consist order Collections.sort(copy); // because instances could be terminated at any time we do multiple // retry to get status and all time remove from request all non found instances if any while (copy.size() > 0) { try { final DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds(copy); DescribeInstancesResult result; do { result = ec2.describeInstances(request); request.setNextToken(result.getNextToken()); for (final Reservation r : result.getReservations()) { for (final Instance instance : r.getInstances()) { // if instance not in terminated state, add it to described if (!TERMINATED_STATES.contains(instance.getState().getName())) { described.put(instance.getInstanceId(), instance); } } } } while (result.getNextToken() != null); // all good, clear request batch to stop copy.clear(); } catch (final AmazonEC2Exception exception) { // if we cannot find instance, that's fine assume them as terminated // remove from request and try again if (exception.getErrorCode().equals(NOT_FOUND_ERROR_CODE)) { final List<String> notFoundInstanceIds = parseInstanceIdsFromNotFoundException(exception.getMessage()); if (notFoundInstanceIds.isEmpty()) { // looks like we cannot parse correctly, rethrow throw exception; } copy.removeAll(notFoundInstanceIds); } } } }
Example 12
Source File: FindRunningInstances.java From aws-doc-sdk-examples with Apache License 2.0 | 4 votes |
public static void main(String[] args) { // snippet-start:[ec2.java1.running_instances.main] AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); try { //Create the Filter to use to find running instances Filter filter = new Filter("instance-state-name"); filter.withValues("running"); //Create a DescribeInstancesRequest DescribeInstancesRequest request = new DescribeInstancesRequest(); request.withFilters(filter); // Find the running instances DescribeInstancesResult response = ec2.describeInstances(request); for (Reservation reservation : response.getReservations()){ for (Instance instance : reservation.getInstances()) { //Print out the results System.out.printf( "Found reservation with id %s, " + "AMI %s, " + "type %s, " + "state %s " + "and monitoring state %s", instance.getInstanceId(), instance.getImageId(), instance.getInstanceType(), instance.getState().getName(), instance.getMonitoring().getState()); } } System.out.print("Done"); } catch (SdkClientException e) { e.getStackTrace(); } // snippet-end:[ec2.java1.running_instances.main] }
Example 13
Source File: EC2Application.java From tutorials with MIT License | 4 votes |
public static void main(String[] args) { // Set up the client AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.US_EAST_1) .build(); // Create a security group CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup") .withDescription("Baeldung Security Group"); ec2Client.createSecurityGroup(createSecurityGroupRequest); // Allow HTTP and SSH traffic IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0"); IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) .withIpProtocol("tcp") .withFromPort(80) .withToPort(80); IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) .withIpProtocol("tcp") .withFromPort(22) .withToPort(22); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName("BaeldungSecurityGroup") .withIpPermissions(ipPermission1, ipPermission2); ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); // Create KeyPair CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() .withKeyName("baeldung-key-pair"); CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest); String privateKey = createKeyPairResult .getKeyPair() .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key // See what key-pairs you've got DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest); // Launch an Amazon Instance RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html .withMinCount(1) .withMaxCount(1) .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance .withSecurityGroups("BaeldungSecurityGroup"); String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId(); // Start an Instance StartInstancesRequest startInstancesRequest = new StartInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.startInstances(startInstancesRequest); // Monitor Instances MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.monitorInstances(monitorInstancesRequest); UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.unmonitorInstances(unmonitorInstancesRequest); // Reboot an Instance RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.rebootInstances(rebootInstancesRequest); // Stop an Instance StopInstancesRequest stopInstancesRequest = new StopInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.stopInstances(stopInstancesRequest) .getStoppingInstances() .get(0) .getPreviousState() .getName(); // Describe an Instance DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest); System.out.println(response.getReservations() .get(0) .getInstances() .get(0) .getKernelId()); }