Search in sources :

Example 16 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project aws-doc-sdk-examples by awsdocs.

the class DescribeInstances method describeEC2Instances.

// snippet-start:[ec2.java2.describe_instances.main]
public static void describeEC2Instances(Ec2Client ec2) {
    boolean done = false;
    String nextToken = null;
    try {
        do {
            DescribeInstancesRequest request = DescribeInstancesRequest.builder().maxResults(6).nextToken(nextToken).build();
            DescribeInstancesResponse response = ec2.describeInstances(request);
            for (Reservation reservation : response.reservations()) {
                for (Instance instance : reservation.instances()) {
                    System.out.println("Instance Id is " + instance.instanceId());
                    System.out.println("Image id is " + instance.imageId());
                    System.out.println("Instance type is " + instance.instanceType());
                    System.out.println("Instance state name is " + instance.state().name());
                    System.out.println("monitoring information is " + instance.monitoring().state());
                }
            }
            nextToken = response.nextToken();
        } while (nextToken != null);
    } catch (Ec2Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
Also used : Reservation(software.amazon.awssdk.services.ec2.model.Reservation) Instance(software.amazon.awssdk.services.ec2.model.Instance) Ec2Exception(software.amazon.awssdk.services.ec2.model.Ec2Exception) DescribeInstancesRequest(software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest) DescribeInstancesResponse(software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse)

Example 17 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project aws-doc-sdk-examples by awsdocs.

the class FindRunningInstances method findRunningEC2Instances.

// snippet-start:[ec2.java2.running_instances.main]
public static void findRunningEC2Instances(Ec2Client ec2) {
    try {
        String nextToken = null;
        do {
            Filter filter = Filter.builder().name("instance-state-name").values("running").build();
            DescribeInstancesRequest request = DescribeInstancesRequest.builder().filters(filter).build();
            DescribeInstancesResponse response = ec2.describeInstances(request);
            for (Reservation reservation : response.reservations()) {
                for (Instance instance : reservation.instances()) {
                    System.out.printf("Found Reservation with id %s, " + "AMI %s, " + "type %s, " + "state %s " + "and monitoring state %s", instance.instanceId(), instance.imageId(), instance.instanceType(), instance.state().name(), instance.monitoring().state());
                    System.out.println("");
                }
            }
            nextToken = response.nextToken();
        } while (nextToken != null);
    } catch (Ec2Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
Also used : Reservation(software.amazon.awssdk.services.ec2.model.Reservation) Filter(software.amazon.awssdk.services.ec2.model.Filter) Instance(software.amazon.awssdk.services.ec2.model.Instance) Ec2Exception(software.amazon.awssdk.services.ec2.model.Ec2Exception) DescribeInstancesRequest(software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest) DescribeInstancesResponse(software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse)

Example 18 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project aws-doc-sdk-examples by awsdocs.

the class DescribeInstances method main.

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;
        }
    }
}
Also used : DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) Reservation(com.amazonaws.services.ec2.model.Reservation) Instance(com.amazonaws.services.ec2.model.Instance) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest)

Example 19 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project aws-doc-sdk-examples by awsdocs.

the class FindRunningInstances method main.

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]
}
Also used : DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) Reservation(com.amazonaws.services.ec2.model.Reservation) SdkClientException(com.amazonaws.SdkClientException) Filter(com.amazonaws.services.ec2.model.Filter) Instance(com.amazonaws.services.ec2.model.Instance) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest)

Example 20 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project crate by crate.

the class AwsEc2SeedHostsProvider method fetchDynamicNodes.

private List<TransportAddress> fetchDynamicNodes() {
    final List<TransportAddress> dynamicHosts = new ArrayList<>();
    final DescribeInstancesResult descInstances;
    try (AmazonEc2Reference clientReference = awsEc2Service.client()) {
        // Query EC2 API based on AZ, instance state, and tag.
        // NOTE: we don't filter by security group during the describe instances request for two reasons:
        // 1. differences in VPCs require different parameters during query (ID vs Name)
        // 2. We want to use two different strategies: (all security groups vs. any security groups)
        descInstances = clientReference.client().describeInstances(buildDescribeInstancesRequest());
    } catch (final AmazonClientException e) {
        LOGGER.info("Exception while retrieving instance list from AWS API: {}", e.getMessage());
        LOGGER.debug("Full exception:", e);
        return dynamicHosts;
    }
    LOGGER.trace("finding seed nodes...");
    for (final Reservation reservation : descInstances.getReservations()) {
        for (final Instance instance : reservation.getInstances()) {
            // lets see if we can filter based on groups
            if (!groups.isEmpty()) {
                final List<GroupIdentifier> instanceSecurityGroups = instance.getSecurityGroups();
                final List<String> securityGroupNames = new ArrayList<>(instanceSecurityGroups.size());
                final List<String> securityGroupIds = new ArrayList<>(instanceSecurityGroups.size());
                for (final GroupIdentifier sg : instanceSecurityGroups) {
                    securityGroupNames.add(sg.getGroupName());
                    securityGroupIds.add(sg.getGroupId());
                }
                if (bindAnyGroup) {
                    // We check if we can find at least one group name or one group id in groups.
                    if (disjoint(securityGroupNames, groups) && disjoint(securityGroupIds, groups)) {
                        LOGGER.trace("filtering out instance {} based on groups {}, not part of {}", instance.getInstanceId(), instanceSecurityGroups, groups);
                        // continue to the next instance
                        continue;
                    }
                } else {
                    // We need tp match all group names or group ids, otherwise we ignore this instance
                    if (!(securityGroupNames.containsAll(groups) || securityGroupIds.containsAll(groups))) {
                        LOGGER.trace("filtering out instance {} based on groups {}, does not include all of {}", instance.getInstanceId(), instanceSecurityGroups, groups);
                        // continue to the next instance
                        continue;
                    }
                }
            }
            String address = null;
            if (hostType.equals(PRIVATE_DNS)) {
                address = instance.getPrivateDnsName();
            } else if (hostType.equals(PRIVATE_IP)) {
                address = instance.getPrivateIpAddress();
            } else if (hostType.equals(PUBLIC_DNS)) {
                address = instance.getPublicDnsName();
            } else if (hostType.equals(PUBLIC_IP)) {
                address = instance.getPublicIpAddress();
            } else if (hostType.startsWith(TAG_PREFIX)) {
                // Reading the node host from its metadata
                final String tagName = hostType.substring(TAG_PREFIX.length());
                LOGGER.debug("reading hostname from [{}] instance tag", tagName);
                final List<Tag> tags = instance.getTags();
                for (final Tag tag : tags) {
                    if (tag.getKey().equals(tagName)) {
                        address = tag.getValue();
                        LOGGER.debug("using [{}] as the instance address", address);
                    }
                }
            } else {
                throw new IllegalArgumentException(hostType + " is unknown for discovery.ec2.host_type");
            }
            if (address != null) {
                try {
                    final TransportAddress[] addresses = transportService.addressesFromString(address);
                    for (int i = 0; i < addresses.length; i++) {
                        LOGGER.trace("adding {}, address {}, transport_address {}", instance.getInstanceId(), address, addresses[i]);
                        dynamicHosts.add(addresses[i]);
                    }
                } catch (final Exception e) {
                    final String finalAddress = address;
                    LOGGER.warn((Supplier<?>) () -> new ParameterizedMessage("failed to add {}, address {}", instance.getInstanceId(), finalAddress), e);
                }
            } else {
                LOGGER.trace("not adding {}, address is null, host_type {}", instance.getInstanceId(), hostType);
            }
        }
    }
    LOGGER.debug("using dynamic transport addresses {}", dynamicHosts);
    return dynamicHosts;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) TransportAddress(org.elasticsearch.common.transport.TransportAddress) AmazonClientException(com.amazonaws.AmazonClientException) ArrayList(java.util.ArrayList) Collections.disjoint(java.util.Collections.disjoint) AmazonClientException(com.amazonaws.AmazonClientException) GroupIdentifier(com.amazonaws.services.ec2.model.GroupIdentifier) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) Reservation(com.amazonaws.services.ec2.model.Reservation) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Tag(com.amazonaws.services.ec2.model.Tag)

Aggregations

Reservation (com.amazonaws.services.ec2.model.Reservation)39 Instance (com.amazonaws.services.ec2.model.Instance)35 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)23 ArrayList (java.util.ArrayList)21 DescribeInstancesRequest (com.amazonaws.services.ec2.model.DescribeInstancesRequest)16 Filter (com.amazonaws.services.ec2.model.Filter)11 CloudInstance (com.sequenceiq.cloudbreak.cloud.model.CloudInstance)8 Test (org.junit.Test)8 Tag (com.amazonaws.services.ec2.model.Tag)7 Function (com.google.common.base.Function)6 AwsCredentialView (com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView)6 CloudVmMetaDataStatus (com.sequenceiq.cloudbreak.cloud.model.CloudVmMetaDataStatus)6 AmazonAutoScalingClient (com.amazonaws.services.autoscaling.AmazonAutoScalingClient)5 AmazonCloudFormationClient (com.amazonaws.services.cloudformation.AmazonCloudFormationClient)5 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)5 CreateTagsRequest (com.amazonaws.services.ec2.model.CreateTagsRequest)5 AuthenticatedContext (com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext)5 InstanceAuthentication (com.sequenceiq.cloudbreak.cloud.model.InstanceAuthentication)5 InstanceTemplate (com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate)5 Volume (com.sequenceiq.cloudbreak.cloud.model.Volume)5