本文整理汇总了Java中com.amazonaws.services.ec2.AmazonEC2.describeInstances方法的典型用法代码示例。如果您正苦于以下问题:Java AmazonEC2.describeInstances方法的具体用法?Java AmazonEC2.describeInstances怎么用?Java AmazonEC2.describeInstances使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.amazonaws.services.ec2.AmazonEC2
的用法示例。
在下文中一共展示了AmazonEC2.describeInstances方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: findInstanceByName
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
/**
* Search Ec2 Instance by Name tag.
*
* @param ec2
* @param targetName
* Search Keyword for Name tag
* @return Instance with Name tag equals targetName. If it does't found,
* then return null.
*/
public static Instance findInstanceByName(AmazonEC2 ec2, String targetName) {
DescribeInstancesResult instanceResult = ec2.describeInstances();
List<Reservation> reservations = instanceResult.getReservations();
for (Reservation reservation : reservations) {
List<Instance> instances = reservation.getInstances();
for (Instance instance : instances) {
List<Tag> tagList = instance.getTags();
String name = "";
for (Tag tag : tagList) {
String tagKey = tag.getKey();
String tagValue = tag.getValue();
if (tagKey.contains("Name")) {
name = tagValue;
if (targetName.equals(name)) {
return instance;
}
break;
}
}
}
}
return null;
}
示例2: doTestConnection
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
protected FormValidation doTestConnection(URL ec2endpoint,
boolean useInstanceProfileForCredentials, String accessId, String secretKey, String privateKey) throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint);
ec2.describeInstances();
if (privateKey == null) {
return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one.");
}
if (privateKey.trim().length() > 0) {
// check if this key exists
EC2PrivateKey pk = new EC2PrivateKey(privateKey);
if (pk.find(ec2) == null) {
return FormValidation.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is " + pk.getFingerprint() + ")");
}
}
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
示例3: getInstancesForGroup
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
/***
* 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;
}
示例4: checkTagsAws
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
protected static void checkTagsAws(Regions region, List<String> instanceIdList, Map<String, String> tagsToCheckMap) {
Map<String, String> extractedTagsToCheck = new HashMap<>();
List<Tag> extractedTags;
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).build();
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.withInstanceIds(instanceIdList);
DescribeInstancesResult describeInstancesResultAll = ec2.describeInstances(describeInstancesRequest);
List<Reservation> reservationsAll = describeInstancesResultAll.getReservations();
for (Reservation reservation : reservationsAll) {
for (Instance instance : reservation.getInstances()) {
extractedTags = instance.getTags();
Assert.assertNotNull(extractedTags);
for (Tag tag : extractedTags) {
extractedTagsToCheck.put(tag.getKey(), tag.getValue());
}
checkTags(tagsToCheckMap, extractedTagsToCheck);
extractedTags.clear();
}
}
}
示例5: getEc2Instance
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
private Instance getEc2Instance(IMachine machine, AmazonEC2 connector) throws ConnectorException {
DescribeInstancesResult describeInstancesResult = null;
try {
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesResult = connector.describeInstances(describeInstancesRequest.withInstanceIds(machine.getName()));
List<Reservation> reservations = describeInstancesResult.getReservations();
if (reservations.size() == 0) {
// machine not found MUST have been terminated
return null;
}
// always it will be in the first reservation as the query is on
// only one machine
List<Instance> instances = reservations.get(0).getInstances();
for (Instance instance : instances) {
if (instance.getInstanceId().equals(machine.getName())) {
// found the machine
return instance;
}
}
} catch (Exception e) {
throw new ConnectorException(e);
}
return null;
}
示例6: describeReservations
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
@Override
public List<AbstractResource<?>> describeReservations(Account account, Region region, DateTime dt, Ec2Filter... filters) {
AmazonEC2 ec2 = findClient(account, region);
DescribeInstancesRequest req = new DescribeInstancesRequest();
for (Ec2Filter filter : filters) {
Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues());
req.withFilters(f);
}
log.debug("start describing instances for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region);
DescribeInstancesResult res = ec2.describeInstances(req);
List<Map<String, Ec2InstanceAttribute>> attributes = new ArrayList<>();
for (Reservation r : res.getReservations()) {
Map<String, Ec2InstanceAttribute> attribute = new HashMap<>();
for (Instance i : r.getInstances()) {
Boolean terminationProtection = findTerminationProtection(account, region, i.getInstanceId());
String shutdownBehavior = findShutdownBehavior(account, region, i.getInstanceId());
String userData = findUserData(account, region, i.getInstanceId());
Ec2InstanceAttribute ia = new Ec2InstanceAttribute(terminationProtection, shutdownBehavior, userData);
attribute.put(i.getInstanceId(), ia);
}
attributes.add(attribute);
}
return converter.toEc2Reservations(res.getReservations(), attributes, account.getId(), region, dt);
}
示例7: describeInstance
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
/**
* @inheritDoc
*/
@Override
public WorkerInstance describeInstance( String instanceId, Identity identity )
{
AmazonEC2 ec2 =
ActivityUtils.createClient( AmazonEC2Client.class, identity );
DescribeInstancesResult result =
ec2.describeInstances( new DescribeInstancesRequest().withInstanceIds( instanceId ) );
if ( result.getReservations().isEmpty() )
{
return null;
}
Reservation resv = result.getReservations().get( 0 );
if ( resv.getInstances().isEmpty() )
{
return null;
}
Instance ins = resv.getInstances().get( 0 );
WorkerInstance wi = new WorkerInstance();
wi.setInstanceId( ins.getInstanceId() );
wi.setInstanceStatus( ins.getState().getName() );
wi.setPublicIpAddress( ins.getPublicIpAddress() );
return wi;
}
示例8: getOwnIP
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
public static String getOwnIP()
{
AWSCredentials credentials = null;
try
{
credentials = new ProfileCredentialsProvider().getCredentials();
}
catch(Exception e){}
AmazonEC2 ec2 = new AmazonEC2Client(credentials);
ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");
DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
List<Reservation> reservations = describeInstancesResult.getReservations();
ArrayList<Instance> listOfInstances = new ArrayList<Instance>();
for(Reservation reservation : reservations)
listOfInstances.addAll(reservation.getInstances());
String ownIP = null;
String ownInstanceID = checkInstanceId();
for(Instance instance: listOfInstances)
{
if(instance.getInstanceId().equals(ownInstanceID))
ownIP = instance.getPublicIpAddress();
}
return ownIP;
}
示例9: startInstance
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
public static InstanceObject startInstance(AmazonEC2 ec2)
{
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.withImageId("ami-f6ed6785")
.withMonitoring(true)
.withInstanceType("t2.micro")
.withMinCount(1)
.withMaxCount(1)
.withKeyName("CNV-lab-AWS")
.withSecurityGroups("CNV-ssh+http");
RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
List<Reservation> reservations = describeInstancesResult.getReservations();
ArrayList<Instance> auxListOfInstances = new ArrayList<Instance>();
for (Reservation reservation : reservations) {
auxListOfInstances.addAll(reservation.getInstances());
}
InstanceObject instanceObject = null;
for (Instance instance : auxListOfInstances) {
if(instance.getInstanceId().equals(runInstancesResult.getReservation().getInstances().get(0).getInstanceId())) //id do load balancer, nao adicionamos este as instancias
instanceObject = new InstanceObject(instance);
}
//retornamos a instance criada
return instanceObject;
}
示例10: lookupElligibleInstances
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
public static List<Instance> lookupElligibleInstances( AmazonEC2 ec2Client, String namePrefix, String nameRegex ) {
// We only care about those EC2 instance that have a Name tag
DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters( new Filter().withName( "tag-key" ).withValues( "Name" ) );
// Make the request
DescribeInstancesResult result = ec2Client.describeInstances( request );
// Process the results building up a list of EC2 instances that match the criteria
List<Instance> instances = new ArrayList<>();
for ( Reservation reservation : result.getReservations() ) {
for ( Instance instance : reservation.getInstances() ) {
// We don't want EC2 instances that are part of Elastic Beanstalk since they fall under the Elastic Beanstalk logic
String environmentName = EC2Util.getTagValue( instance, "elasticbeanstalk:environment-name" );
if ( !environmentName.isEmpty() ) {
continue;
}
// Check to see if the instance is eligible and add it to the list if so
if ( EC2Util.isInstanceEligible( instance, namePrefix, nameRegex ) ) {
instances.add( instance );
}
}
}
return instances;
}
示例11: main
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
public static void main(String[] args)
{
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
boolean done = false;
while(!done) {
DescribeInstancesRequest request = new DescribeInstancesRequest();
DescribeInstancesResult response = ec2.describeInstances(request);
for(Reservation reservation : response.getReservations()) {
for(Instance instance : reservation.getInstances()) {
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());
}
}
request.setNextToken(response.getNextToken());
if(response.getNextToken() == null) {
done = true;
}
}
}
示例12: translatePrivateIpToPublicHostNames
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
/**
* Fetch the public DNS names for the corresponding private Ips. SolrCloud defaults to private ips for all
* interactions. If you want to run HAFT locally to copy data across 2 different zookeeper clusters, then we need
* public IP translations to access the index. This method helps achieve that.
*
* @return {@link #getZkClusterData()} with private Ip to Public DNS Mapping based on EC2 api.
*/
public ZkClusterData translatePrivateIpToPublicHostNames() {
AWSCredentials credentials = new BasicAWSCredentials(AwsConfigReader.fetchAccessKey(), AwsConfigReader.fetchSecretyKey());
AmazonEC2 ec2 = new AmazonEC2Client(credentials);
Set<String> publicDnsNameHosts = new HashSet<String>();
Map<String, String> privateIptoPublicHostNames = new HashMap<String, String>();
if (allSolrNodes.isEmpty()) {
logger.info("No valid solr hosts are found. Cannot do any mapping");
return zkClusterData;
}
//Describe Filter with private-ips matching all solr nodes
DescribeInstancesRequest request = new DescribeInstancesRequest()
.withFilters(new Filter("private-ip-address").withValues(allSolrNodes));
DescribeInstancesResult describeInstancesResult = ec2.describeInstances(request);
List<Reservation> reservations = describeInstancesResult.getReservations();
//Iterate over all instances and map their private Ip to Public Host Name
logger.info("Fetching Public HostNames....");
for (Reservation reservation : reservations) {
List<Instance> instances = reservation.getInstances();
for (Instance instance : instances) {
logger.info("Private to Public Name of the Host is " + instance.getPrivateIpAddress() + " => " + instance.getPublicDnsName());
publicDnsNameHosts.add(instance.getPublicDnsName());
privateIptoPublicHostNames.put(instance.getPrivateIpAddress(), instance.getPublicDnsName());
}
}
//Point all zk data to point to the public dns names
zkClusterData.updateSolrNodes(publicDnsNameHosts);
//Set the data in a map so that it doesn't need to get recomputed by every function needing hostnames
zkClusterData.setPrivateIpToPublicHostNameMap(privateIptoPublicHostNames);
return zkClusterData;
}
示例13: listHosts
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
private List<HostAndPort> listHosts(AmazonEC2 client) throws Exception {
List<HostAndPort> hosts = newArrayList();
DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(_filters);
String nextToken = null;
LOG.log(FINER, "Discovering instances: filters={0}", new Object[]{_filters});
do {
DescribeInstancesResult result = client.describeInstances(request.withNextToken(nextToken));
for (Reservation reservation : result.getReservations()) {
for (Instance instance : reservation.getInstances()) {
LOG.log(FINER, "Instance state: {0} {1}", new Object[]{instance.getInstanceId(), instance.getState().getName()});
if ("running".equalsIgnoreCase(instance.getState().getName())) {
List<InstanceNetworkInterface> networkInterfaces = instance.getNetworkInterfaces();
if (networkInterfaces.size() < 1) {
LOG.log(WARNING, "No network interface found on instance {0}", instance.getInstanceId());
} else {
InstanceNetworkInterface nic = networkInterfaces.get(0);
String ip;
if (_usePublicIP) {
ip = nic.getAssociation().getPublicIp();
} else {
ip = nic.getPrivateIpAddress();
}
hosts.add(HostAndPort.fromString(ip));
}
}
}
}
nextToken = result.getNextToken();
} while (nextToken != null);
return hosts;
}
示例14: execute
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) {
@SuppressWarnings("unchecked")
List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS);
checkNotNull(instanceIds, "%s not found as a process variable", ProcessVariables.INSTANCE_IDS);
LOG.info(">> Describing instances {}", instanceIds);
DescribeInstancesResult result = client.describeInstances(new DescribeInstancesRequest()
.withInstanceIds(instanceIds));
LOG.info("<< Got the following reservations: {}", result.getReservations());
List<Instance> instances = collectInstancesFromReservations(result.getReservations());
List<Machine> machines = Lists.transform(instances,
new Function<Instance, Machine>() {
@Override
public Machine apply(Instance instance) {
return Machine.builder()
.externalId(instance.getInstanceId())
.publicDnsName(instance.getPublicDnsName())
.publicIp(instance.getPublicIpAddress())
.privateDnsName(instance.getPrivateDnsName())
.privateIp(instance.getPrivateIpAddress())
.createMachine();
}
});
/* Create a new ArrayList to force evaluation for lazy collections */
execution.setVariable(CoreProcessVariables.MACHINES, Lists.newArrayList(machines));
}
示例15: execute
import com.amazonaws.services.ec2.AmazonEC2; //导入方法依赖的package包/类
@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) {
@SuppressWarnings("unchecked")
Optional<List<String>> instanceIds =
Optional.fromNullable((List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS));
if (!instanceIds.isPresent()) {
LOG.warn("<< Process variable '{}' not found", ProcessVariables.INSTANCE_IDS);
return;
} else if (instanceIds.get().size() == 0) {
LOG.info(">> No instances are currently registered in the process.");
return;
}
try {
DescribeInstancesResult result = client.describeInstances(new DescribeInstancesRequest()
.withInstanceIds(instanceIds.get()));
List<Instance> instances = collectInstancesFromReservations(result.getReservations());
if (Iterables.all(instances, predicate)) {
LOG.info(">> All {} instances match predicate {} ", instanceIds, predicate);
execution.setVariable(resultVariable, true);
} else {
LOG.info("<< Not all instances {} match predicate {}", instanceIds, predicate);
execution.setVariable(resultVariable, false);
}
} catch (AmazonServiceException exception) {
if (exception.getErrorCode().equalsIgnoreCase("InvalidInstanceID.NotFound")) {
LOG.warn("<< Got error InvalidInstanceID.NotFound. Assuming predicate {} is false", predicate);
execution.setVariable(resultVariable, false);
} else {
throw Throwables.propagate(exception);
}
}
}