List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client setEndpoint
@Deprecated public void setEndpoint(String endpoint) throws IllegalArgumentException
From source file:Aws.Profile.java
public void SetEndEndpoint(AmazonEC2Client ec2, Map<String, String> region) { String key = getClientname(); if (region.toString().contains(key)) { ec2.setEndpoint("ec2." + region.get(key).trim() + ".amazonaws.com"); }/*w ww . ja va 2 s. c o m*/ }
From source file:ch.admin.isb.hermes5.tools.deploysupport.DeploySupport.java
License:Apache License
private AmazonEC2 ec2() { AmazonEC2Client ec2 = new AmazonEC2Client(credentials()); ec2.setEndpoint(ec2RegionEndpoint); return ec2; }
From source file:com.axemblr.yab.YaB.java
License:Apache License
/** * Constructs a new YaB client by fetching credentials in this order: * <p>/*from w w w.j a va 2s . co m*/ * - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY * - Java System Properties - aws.accessKeyId and aws.secretKey * - Instance profile credentials delivered through the Amazon EC2 metadata service * </p> */ public static YaB createWithEnvironmentCredentials(String region) { AmazonEC2Client client = new AmazonEC2Client(); boolean regionFound = false; DescribeRegionsResult result = client.describeRegions(); for (Region candidate : result.getRegions()) { if (candidate.getRegionName().equals(region)) { client.setEndpoint(candidate.getEndpoint()); regionFound = true; break; } } if (!regionFound) { throw new IllegalArgumentException("No region found with this name: " + region); } return new YaB(client); }
From source file:com.cloudera.director.aws.ec2.EC2Provider.java
License:Apache License
/** * Configures the specified EC2 client./*from w ww . j a v a 2s . c om*/ * * @param configuration the provider configuration * @param accumulator the exception accumulator * @param client the EC2 client * @param providerLocalizationContext the resource provider localization context * @param verify whether to verify the configuration by making an API call * @return the configured client * @throws InvalidCredentialsException if the supplied credentials are invalid * @throws TransientProviderException if a transient exception occurs communicating with the * provider * @throws UnrecoverableProviderException if an unrecoverable exception occurs communicating with * the provider */ protected static AmazonEC2Client configureClient(Configured configuration, PluginExceptionConditionAccumulator accumulator, AmazonEC2Client client, LocalizationContext providerLocalizationContext, boolean verify) { checkNotNull(client, "client is null"); try { String regionEndpoint = configuration.getConfigurationValue(REGION_ENDPOINT, providerLocalizationContext); if (regionEndpoint != null) { LOG.info("<< Using configured region endpoint for EC2 client: {}", regionEndpoint); } else { String region = configuration.getConfigurationValue(REGION, providerLocalizationContext); regionEndpoint = getEndpointForRegion(client, region); } client.setEndpoint(regionEndpoint); if (verify) { // Attempt to use client, to validate credentials and connectivity client.describeRegions(); } } catch (AmazonClientException e) { throw AWSExceptions.propagate(e); } catch (IllegalArgumentException e) { accumulator.addError(REGION.unwrap().getConfigKey(), e.getMessage()); } return client; }
From source file:com.dtolabs.rundeck.ec2.NodeGenerator.java
License:Apache License
private static Set<Instance> performQuery(AWSCredentials credentials, final String endPoint, final ArrayList<String> filterParams) { AmazonEC2Client ec2 = new AmazonEC2Client(credentials); if (null != endPoint && !"".equals(endPoint) && !"-".equals(endPoint)) { ec2.setEndpoint(endPoint); }/*from w ww.j a v a 2 s . co m*/ //create "running" filter ArrayList<Filter> filters = new ArrayList<Filter>(); Filter filter = new Filter("instance-state-name").withValues(InstanceStateName.Running.toString()); filters.add(filter); if (null != filterParams) { for (final String filterParam : filterParams) { String[] x = filterParam.split("=", 2); if (!"".equals(x[0]) && !"".equals(x[1])) { filters.add(new Filter(x[0]).withValues(x[1])); } } } DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(filters); DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(request); List<Reservation> reservations = describeInstancesRequest.getReservations(); Set<Instance> instances = new HashSet<Instance>(); for (final Reservation reservation : reservations) { instances.addAll(reservation.getInstances()); } return instances; }
From source file:com.dtolabs.rundeck.plugin.resources.ec2.InstanceToNodeMapper.java
License:Apache License
/** * Perform the query and return the set of instances * *///from w w w . j a va 2 s.com public INodeSet performQuery() { final NodeSetImpl nodeSet = new NodeSetImpl(); final AmazonEC2Client ec2; if (null != credentials) { ec2 = new AmazonEC2Client(credentials, clientConfiguration); } else { ec2 = new AmazonEC2Client(clientConfiguration); } if (null != getEndpoint()) { ec2.setEndpoint(getEndpoint()); } final ArrayList<Filter> filters = buildFilters(); final Set<Instance> instances = query(ec2, new DescribeInstancesRequest().withFilters(filters)); mapInstances(nodeSet, instances); return nodeSet; }
From source file:com.liferay.amazontools.BaseAMIBuilder.java
License:Open Source License
protected AmazonEC2Client getAmazonEC2Client(String accessKey, String secretKey, String endpoint) { AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(awsCredentials); amazonEC2Client.setEndpoint(endpoint); return amazonEC2Client; }
From source file:com.netflix.ice.basic.BasicReservationService.java
License:Apache License
private void pollAPI() throws Exception { long currentTime = new DateMidnight().getMillis(); DescribeReservedInstancesOfferingsRequest req = new DescribeReservedInstancesOfferingsRequest().withFilters( new com.amazonaws.services.ec2.model.Filter().withName("marketplace").withValues("false")); String token = null;//w w w. j a va 2s .co m boolean hasNewPrice = false; AmazonEC2Client ec2Client = new AmazonEC2Client(AwsUtils.awsCredentialsProvider, AwsUtils.clientConfig); for (Region region : Region.getAllRegions()) { ec2Client.setEndpoint("ec2." + region.name + ".amazonaws.com"); do { if (!StringUtils.isEmpty(token)) req.setNextToken(token); DescribeReservedInstancesOfferingsResult offers = ec2Client.describeReservedInstancesOfferings(req); token = offers.getNextToken(); for (ReservedInstancesOffering offer : offers.getReservedInstancesOfferings()) { if (offer.getProductDescription().indexOf("Amazon VPC") >= 0) continue; ReservationUtilization utilization = ReservationUtilization.get(offer.getOfferingType()); Ec2InstanceReservationPrice.ReservationPeriod term = offer.getDuration() / 24 / 3600 > 366 ? Ec2InstanceReservationPrice.ReservationPeriod.threeyear : Ec2InstanceReservationPrice.ReservationPeriod.oneyear; if (term != this.term) continue; double hourly = offer.getUsagePrice(); if (hourly <= 0) { for (RecurringCharge recurringCharge : offer.getRecurringCharges()) { if (recurringCharge.getFrequency().equals("Hourly")) { hourly = recurringCharge.getAmount(); break; } } } UsageType usageType = getUsageType(offer.getInstanceType(), offer.getProductDescription()); hasNewPrice = setPrice(utilization, currentTime, Zone.getZone(offer.getAvailabilityZone()).region, usageType, offer.getFixedPrice(), hourly) || hasNewPrice; logger.info("Setting RI price for " + Zone.getZone(offer.getAvailabilityZone()).region + " " + utilization + " " + usageType + " " + offer.getFixedPrice() + " " + hourly); } } while (!StringUtils.isEmpty(token)); } ec2Client.shutdown(); if (hasNewPrice) { for (ReservationUtilization utilization : files.keySet()) { File file = files.get(utilization); DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); try { Serializer.serialize(out, this.ec2InstanceReservationPrices.get(utilization)); AwsUtils.upload(config.workS3BucketName, config.workS3BucketPrefix, file); } finally { out.close(); } } } }
From source file:com.netflix.ice.processor.ReservationCapacityPoller.java
License:Apache License
@Override protected void poll() throws Exception { ProcessorConfig config = ProcessorConfig.getInstance(); // read from s3 if not exists File file = new File(config.localDir, "reservation_capacity.txt"); if (!file.exists()) { logger.info("downloading " + file + "..."); AwsUtils.downloadFileIfNotExist(config.workS3BucketName, config.workS3BucketPrefix, file); logger.info("downloaded " + file); }//www. j a va 2 s. co m // read from file Map<String, ReservedInstances> reservations = Maps.newTreeMap(); if (file.exists()) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); String accountId = tokens[0]; String region = tokens[1]; String reservationId = tokens[2]; String zone = tokens[3]; Long start = Long.parseLong(tokens[4]); long duration = Long.parseLong(tokens[5]); String instanceType = tokens[6]; String productDescription = tokens[7]; int instanceCount = Integer.parseInt(tokens[8]); String offeringType = tokens[9]; String state = tokens[10]; Long end = tokens.length > 11 ? Long.parseLong(tokens[11]) : null; float fixedPrice = tokens.length > 12 ? Float.parseFloat(tokens[12]) : 0; float usagePrice = tokens.length > 13 ? Float.parseFloat(tokens[13]) : 0; ReservedInstances reservation = new ReservedInstances().withAvailabilityZone(zone) .withStart(new Date(start)).withDuration(duration).withInstanceType(instanceType) .withProductDescription(productDescription).withInstanceCount(instanceCount) .withOfferingType(offeringType).withState(state).withFixedPrice(fixedPrice) .withUsagePrice(usagePrice); if (end != null) reservation.setEnd(new Date(end)); else reservation.setEnd(new Date(start + duration * 1000)); reservations.put(accountId + "," + region + "," + reservationId, reservation); } } catch (Exception e) { logger.error("error in reading " + file, e); } finally { if (reader != null) try { reader.close(); } catch (Exception e) { } } } logger.info("read " + reservations.size() + " reservations."); for (Account account : config.accountService.getReservationAccounts().keySet()) { try { AmazonEC2Client ec2Client; String assumeRole = config.accountService.getReservationAccessRoles().get(account); if (assumeRole != null) { String externalId = config.accountService.getReservationAccessExternalIds().get(account); final Credentials credentials = AwsUtils.getAssumedCredentials(account.id, assumeRole, externalId); ec2Client = new AmazonEC2Client(new AWSSessionCredentials() { public String getAWSAccessKeyId() { return credentials.getAccessKeyId(); } public String getAWSSecretKey() { return credentials.getSecretAccessKey(); } public String getSessionToken() { return credentials.getSessionToken(); } }); } else ec2Client = new AmazonEC2Client(AwsUtils.awsCredentialsProvider.getCredentials(), AwsUtils.clientConfig); for (Region region : Region.getAllRegions()) { ec2Client.setEndpoint("ec2." + region.name + ".amazonaws.com"); try { DescribeReservedInstancesResult result = ec2Client.describeReservedInstances(); for (ReservedInstances reservation : result.getReservedInstances()) { String key = account.id + "," + region.name + "," + reservation.getReservedInstancesId(); reservations.put(key, reservation); if (reservation.getEnd() == null) reservation.setEnd(new Date( reservation.getStart().getTime() + reservation.getDuration() * 1000L)); if (reservation.getFixedPrice() == null) reservation.setFixedPrice(0f); if (reservation.getUsagePrice() == null) reservation.setUsagePrice(0f); } } catch (Exception e) { logger.error("error in describeReservedInstances for " + region.name + " " + account.name, e); } } ec2Client.shutdown(); } catch (Exception e) { logger.error("Error in describeReservedInstances for " + account.name, e); } } config.reservationService.updateEc2Reservations(reservations); updatedConfig = true; // archive to disk BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); for (String key : reservations.keySet()) { ReservedInstances reservation = reservations.get(key); String[] line = new String[] { key, reservation.getAvailabilityZone(), reservation.getStart().getTime() + "", reservation.getDuration().toString(), reservation.getInstanceType(), reservation.getProductDescription(), reservation.getInstanceCount().toString(), reservation.getOfferingType(), reservation.getState(), reservation.getEnd().getTime() + "", reservation.getFixedPrice() + "", reservation.getUsagePrice() + "", }; writer.write(StringUtils.join(line, ",")); writer.newLine(); } } catch (Exception e) { logger.error("", e); } finally { if (writer != null) try { writer.close(); } catch (Exception e) { } } logger.info("archived " + reservations.size() + " reservations."); // archive to s3 logger.info("uploading " + file + "..."); AwsUtils.upload(config.workS3BucketName, config.workS3BucketPrefix, config.localDir, file.getName()); logger.info("uploaded " + file); }
From source file:com.noctarius.hazelcast.aws.HazelcastAwsDiscoveryStrategy.java
License:Open Source License
private void configureEndpoint(AmazonEC2Client client) { String region = getOrDefault(AwsProperties.REGION, EC2_US_EAST_1_REGION); // Set default endpoint for first request client.setEndpoint(EC2_US_EAST_1_ENDPOINT); if (EC2_US_EAST_1_REGION.equals(region)) { Map<String, String> regionLookup = buildRegionLookup(client); String endpoint = regionLookup.get(region); if (endpoint == null) { throw new RuntimeException("Amazon EC2 regions couldn't be retrieved"); }/*from www .j av a 2s . co m*/ client.setEndpoint(endpoint); } }