public static AmazonEC2 getEC2SynchronousClient(AuthCredentialsServiceState credentials, String region) { ClientConfiguration configuration = new ClientConfiguration(); configuration.withRetryPolicy(new RetryPolicy(new CustomRetryCondition(), DEFAULT_BACKOFF_STRATEGY, DEFAULT_MAX_ERROR_RETRY, true)); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( new BasicAWSCredentials(credentials.privateKeyId, EncryptionUtils.decrypt(credentials.privateKey))); AmazonEC2ClientBuilder ec2ClientBuilder = AmazonEC2ClientBuilder.standard() .withCredentials(awsStaticCredentialsProvider) .withRegion(region) .withClientConfiguration(configuration); return ec2ClientBuilder.build(); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an instance id\n" + "Ex: RebootInstnace <instance_id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String instance_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); RebootInstancesRequest request = new RebootInstancesRequest() .withInstanceIds(instance_id); RebootInstancesResult response = ec2.rebootInstances(request); System.out.printf( "Successfully rebooted instance %s", instance_id); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a security group id\n" + "Ex: DeleteSecurityGroup <security-group-id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String group_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest() .withGroupId(group_id); DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request); System.out.printf( "Successfully deleted security group with id %s", group_id); }
public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeAddressesResult response = ec2.describeAddresses(); for(Address address : response.getAddresses()) { System.out.printf( "Found address with public IP %s, " + "domain %s, " + "allocation id %s " + "and NIC id %s", address.getPublicIp(), address.getDomain(), address.getAllocationId(), address.getNetworkInterfaceId()); } }
public static void main(String[] args) { final String USAGE = "To run this example, supply a key pair name\n" + "Ex: CreateKeyPair <key-pair-name>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String key_name = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); CreateKeyPairRequest request = new CreateKeyPairRequest() .withKeyName(key_name); CreateKeyPairResult response = ec2.createKeyPair(request); System.out.printf( "Successfulyl created key pair named %s", key_name); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an allocation ID.\n" + "Ex: ReleaseAddress <allocation_id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String alloc_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); ReleaseAddressRequest request = new ReleaseAddressRequest() .withAllocationId(alloc_id); ReleaseAddressResult response = ec2.releaseAddress(request); System.out.printf( "Successfully released elastic IP address %s", alloc_id); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a key pair name\n" + "Ex: DeleteKeyPair <key-pair-name>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String key_name = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteKeyPairRequest request = new DeleteKeyPairRequest() .withKeyName(key_name); DeleteKeyPairResult response = ec2.deleteKeyPair(request); System.out.printf( "Successfully deleted key pair named %s", key_name); }
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(); } } }
@Bean public AmazonEC2 amazonEC2Client(final AWSCredentialsProvider awsCredentialsProvider, final ClientConfiguration awsClientConfig, final Region awsRegion) { return AmazonEC2ClientBuilder.standard() .withCredentials(awsCredentialsProvider) .withClientConfiguration(awsClientConfig) .withRegion(awsRegion.getName()) .build(); }
public AAWSTest() { super(); if (Config.has(Config.Key.IAM_ROLE_ARN)) { final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build(); this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(sts).build(); } else { this.credentialsProvider = new DefaultAWSCredentialsProviderChain(); } this.ec2 = AmazonEC2ClientBuilder.standard().withCredentials(this.credentialsProvider).build(); this.iam = AmazonIdentityManagementClientBuilder.standard().withCredentials(this.credentialsProvider).build(); }
public EBMetricsFetcher() throws CandlestackException { super( EBUtil.TYPE_NAME, GlobalAWSProperties.getEBMetricsFetcherSleep() ); environmentNamePrefix = GlobalAWSProperties.getEBEnvrionmentNamePrefix(); environmentNameRegex = GlobalAWSProperties.getEBEnvrionmentNameRegex(); ec2CloudWatchMetrics = GlobalAWSProperties.getEC2CloudwatchMetricsToFetch(); ebCloudWatchMetrics = GlobalAWSProperties.getEBCloudwatchMetricsToFetch(); String region = GlobalAWSProperties.getRegion(); beanstalkClient = AWSElasticBeanstalkClientBuilder.standard().withRegion( region ).build(); ec2Client = AmazonEC2ClientBuilder.standard().withRegion( region ).build(); cloudWatchAccessor = CloudWatchAccessor.getInstance(); }
public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeRegionsResult regions_response = ec2.describeRegions(); for(Region region : regions_response.getRegions()) { System.out.printf( "Found region %s " + "with endpoint %s", region.getRegionName(), region.getEndpoint()); } DescribeAvailabilityZonesResult zones_response = ec2.describeAvailabilityZones(); for(AvailabilityZone zone : zones_response.getAvailabilityZones()) { System.out.printf( "Found availability zone %s " + "with status %s " + "in region %s", zone.getZoneName(), zone.getState(), zone.getRegionName()); } }
public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeKeyPairsResult response = ec2.describeKeyPairs(); for(KeyPairInfo key_pair : response.getKeyPairs()) { System.out.printf( "Found key pair with name %s " + "and fingerprint %s", key_pair.getKeyName(), key_pair.getKeyFingerprint()); } }
public static void main(String[] args) { final String USAGE = "To run this example, supply a group id\n" + "Ex: DescribeSecurityGroups <group-id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String group_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest() .withGroupIds(group_id); DescribeSecurityGroupsResult response = ec2.describeSecurityGroups(request); for(SecurityGroup group : response.getSecurityGroups()) { System.out.printf( "Found security group with id %s, " + "vpc id %s " + "and description %s", group.getGroupId(), group.getVpcId(), group.getDescription()); } }
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; } } }
public static void main(String[] args) { final String USAGE = "To run this example, supply an instance id\n" + "Ex: AllocateAddress <instance_id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String instance_id = args[0]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); AllocateAddressRequest allocate_request = new AllocateAddressRequest() .withDomain(DomainType.Vpc); AllocateAddressResult allocate_response = ec2.allocateAddress(allocate_request); String allocation_id = allocate_response.getAllocationId(); AssociateAddressRequest associate_request = new AssociateAddressRequest() .withInstanceId(instance_id) .withAllocationId(allocation_id); AssociateAddressResult associate_response = ec2.associateAddress(associate_request); System.out.printf( "Successfully associated Elastic IP address %s " + "with instance %s", associate_response.getAssociationId(), instance_id); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an instance name and AMI image id\n" + "Ex: CreateInstance <instance-name> <ami-image-id>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String name = args[0]; String ami_id = args[1]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); RunInstancesRequest run_request = new RunInstancesRequest() .withImageId(ami_id) .withInstanceType(InstanceType.T1Micro) .withMaxCount(1) .withMinCount(1); RunInstancesResult run_response = ec2.runInstances(run_request); String instance_id = run_response.getReservation().getReservationId(); Tag tag = new Tag() .withKey("Name") .withValue(name); CreateTagsRequest tag_request = new CreateTagsRequest() .withTags(tag); CreateTagsResult tag_response = ec2.createTags(tag_request); System.out.printf( "Successfully started EC2 instance %s based on AMI %s", instance_id, ami_id); }
public AAWSTest() { super(); if (Config.has(Config.Key.IAM_ROLE_ARN)) { final AWSSecurityTokenService local = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build(); this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(local).build(); } else { this.credentialsProvider = new DefaultAWSCredentialsProviderChain(); } this.ec2 = AmazonEC2ClientBuilder.standard().withCredentials(this.credentialsProvider).build(); this.route53 = AmazonRoute53ClientBuilder.standard().withCredentials(this.credentialsProvider).build(); this.s3 = AmazonS3ClientBuilder.standard().withCredentials(this.credentialsProvider).build(); this.sts = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(this.credentialsProvider).build(); }
private AmazonEC2 createClient(Cloud cloud, Regions region) { return AmazonEC2ClientBuilder.standard() .withRegion(region) .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials( cloud.getIdentity(), cloud.getCredential() ) )) .build(); }
/** * Initializing the IP finder. */ private void initClients() { if (credsProvider == null || isNullOrEmpty(loadBalancerName) || isNullOrEmpty(region)) throw new IgniteSpiException("One or more configuration parameters are invalid [setCredentialsProvider=" + credsProvider + ", setRegion=" + region + ", setLoadBalancerName=" + loadBalancerName + "]"); if (amazonEC2Client == null) amazonEC2Client = AmazonEC2ClientBuilder.standard().withRegion(region).withCredentials(credsProvider) .build(); if (amazonELBClient == null) amazonELBClient = AmazonElasticLoadBalancingClientBuilder.standard().withRegion(region) .withCredentials(credsProvider).build(); }
public static void main(String[] args) { String region = "us-east-1"; AWSCredentials credentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey); AmazonEC2 api = AmazonEC2ClientBuilder.standard().withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(credentials)).build(); // no particular availability zone String availabilityZone = null; String instanceType = "t1.micro"; String imageId = "ami-3cf8b154"; List<String> securityGroups = Arrays.asList("webserver"); String keyPair = "instancekey"; String bootScript = Joiner.on("\n") .join(Arrays.asList("#!/bin/bash", "sudo apt-get update -qy", "sudo apt-get install -qy apache2")); int instanceCount = 50; String bidPrice = "0.001"; SpotPlacement placement = new SpotPlacement().withAvailabilityZone(availabilityZone); LaunchSpecification launchSpec = new LaunchSpecification().withInstanceType(instanceType).withImageId(imageId) .withPlacement(placement).withSecurityGroups(securityGroups).withKeyName(keyPair) .withUserData(AmazonApiUtils.base64Encode(bootScript)); RequestSpotInstancesRequest request = new RequestSpotInstancesRequest().withInstanceCount(instanceCount) .withType(SpotInstanceType.Persistent).withSpotPrice(bidPrice).withLaunchSpecification(launchSpec); RequestSpotInstancesResult result = api.requestSpotInstances(request); for (SpotInstanceRequest spotRequest : result.getSpotInstanceRequests()) { LOG.info("placed request: {}", spotRequest.getSpotInstanceRequestId()); } }
public static void deleteAWSInstance(Regions region, String instanceId) { List<String> idList = new ArrayList<>(); idList.add(instanceId); AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).build(); TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest(idList); ec2.terminateInstances(terminateInstancesRequest); LOGGER.info("Instance was deleted with id:" + instanceId); }
/** * Validates fields for credential submit */ public void validateSaveAWSCred() { if (awsCred.getAccessKey() == null || awsCred.getAccessKey().trim().equals("")) { addFieldError("awsCred.accessKey", "Required"); } if (awsCred.getSecretKey() == null || awsCred.getSecretKey().trim().equals("")) { addFieldError("awsCred.secretKey", "Required"); } if (!this.hasErrors()) { try { //check if credential are valid BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); AmazonEC2 service = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withClientConfiguration(AWSClientConfig.getClientConfig()).build(); service.describeKeyPairs(); } catch (Exception ex) { ex.printStackTrace(); addActionError("Invalid Credentials"); } } if(this.hasActionErrors() || this.hasErrors()){ sortedSet = AWSCredDB.getAWSCredSet(sortedSet); } }
/** * returns keypairs as a json string */ @Action(value = "/manage/getKeyPairJSON" ) public String getKeyPairJSON() { AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId()); //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); AmazonEC2 service = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withClientConfiguration(AWSClientConfig.getClientConfig()) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(ec2Key.getEc2Region(), ec2RegionMap.get(ec2Key.getEc2Region()))).build(); DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest); List<KeyPairInfo> keyPairInfoList = describeKeyPairsResult.getKeyPairs(); String json = new Gson().toJson(keyPairInfoList); try { servletResponse.getOutputStream().write(json.getBytes()); } catch (Exception ex) { log.error(ex.toString(), ex); } return null; }
private void createAmazonAPIClients() { cfnClient = AmazonCloudFormationClientBuilder.defaultClient(); ec2Client = AmazonEC2ClientBuilder.defaultClient(); snsClient = AmazonSNSClientBuilder.defaultClient(); sqsClient = AmazonSQSClientBuilder.defaultClient(); elbClient = AmazonElasticLoadBalancingClientBuilder.defaultClient(); s3Client = AmazonS3ClientBuilder.defaultClient(); rdsClient = AmazonRDSClientBuilder.defaultClient(); iamClient = AmazonIdentityManagementClientBuilder.defaultClient(); }
public static AmazonEC2Client createEC2Client() { BasicCredentialsProvider credentials = BasicCredentialsProvider.standard(); AmazonEC2Client client = !credentials.isValid() ? null : (AmazonEC2Client) AmazonEC2ClientBuilder.standard() .withCredentials(credentials) .withRegion("eu-west-1") .build(); return client; }
public EBHostMonitorLookup( Set<String> contactGroups ) throws CandlestackPropertiesException { this.contactGroups = contactGroups; environmentNamePrefix = GlobalAWSProperties.getEBEnvrionmentNamePrefix(); environmentNameRegex = GlobalAWSProperties.getEBEnvrionmentNameRegex(); newResourceMonitorDelayMillis = TimeUnit.MINUTES.toMillis( GlobalAWSProperties.getEBNewResourceMonitorDelay() ); ec2CloudWatchMetrics = GlobalAWSProperties.getEC2CloudwatchMetricsToMonitor(); ec2MetricbeatMetrics = GlobalAWSProperties.getEC2MetricbeatMetricsToMonitor(); ebCloudWatchMetrics = GlobalAWSProperties.getEBCloudwatchMetricsToMonitor(); String region = GlobalAWSProperties.getRegion(); beanstalkClient = AWSElasticBeanstalkClientBuilder.standard().withRegion( region ).build(); ec2Client = AmazonEC2ClientBuilder.standard().withRegion( region ).build(); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a group name, group description and vpc id\n" + "Ex: CreateSecurityGroup <group-name> <group-description> <vpc-id>\n"; if (args.length != 3) { System.out.println(USAGE); System.exit(1); } String group_name = args[0]; String group_desc = args[1]; String vpc_id = args[2]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); CreateSecurityGroupRequest create_request = new CreateSecurityGroupRequest() .withGroupName(group_name) .withDescription(group_desc) .withVpcId(vpc_id); CreateSecurityGroupResult create_response = ec2.createSecurityGroup(create_request); System.out.printf( "Successfully created security group named %s", group_name); IpRange ip_range = new IpRange() .withCidrIp("0.0.0.0/0"); IpPermission ip_perm = new IpPermission() .withIpProtocol("tcp") .withToPort(80) .withFromPort(80) .withIpv4Ranges(ip_range); IpPermission ip_perm2 = new IpPermission() .withIpProtocol("tcp") .withToPort(22) .withFromPort(22) .withIpv4Ranges(ip_range); AuthorizeSecurityGroupIngressRequest auth_request = new AuthorizeSecurityGroupIngressRequest() .withGroupName(group_name) .withIpPermissions(ip_perm, ip_perm2); AuthorizeSecurityGroupIngressResult auth_response = ec2.authorizeSecurityGroupIngress(auth_request); System.out.printf( "Successfully added ingress policy to security group %s", group_name); }
public EC2(AWSCredentialsProvider credentials, Regions region) { ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).withCredentials(credentials).build(); }
public EC2VPC(AWSCredentialsProvider credentials, Regions region) { ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).withCredentials(credentials).build(); }
@Parameters({"region", "hostGroupToCheck", "scalingAdjustment"}) @Test public void checkSpotInstance(Regions region, String hostGroupToCheck, @Optional Integer scalingAdjustment) { //GIVEN Integer spotInstanceCount = 0; IntegrationTestContext itContext = getItContext(); String stackId = itContext.getContextParam(CloudbreakITContextConstants.STACK_ID); StackV1Endpoint stackV1Endpoint = getCloudbreakClient().stackV1Endpoint(); StackResponse stackResponse = stackV1Endpoint.get(Long.valueOf(stackId), new HashSet<>()); List<InstanceGroupResponse> instanceGroups = stackResponse.getInstanceGroups(); List<String> instanceIdList = new ArrayList<>(); List<String> hostGroupList = Arrays.asList(hostGroupToCheck.split(",")); for (InstanceGroupResponse instanceGroup : instanceGroups) { if (hostGroupList.contains(instanceGroup.getGroup())) { Set<InstanceMetaDataJson> instanceMetaData = instanceGroup.getMetadata(); for (InstanceMetaDataJson metaData : instanceMetaData) { instanceIdList.add(metaData.getInstanceId()); } } } //WHEN AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).build(); DescribeSpotInstanceRequestsResult describeSpotInstanceRequestsResult = ec2.describeSpotInstanceRequests(); List<SpotInstanceRequest> spotInstanceRequests = describeSpotInstanceRequestsResult.getSpotInstanceRequests(); //THEN Assert.assertFalse(spotInstanceRequests.isEmpty()); List<String> spotInstanceIdList = new ArrayList<>(); for (SpotInstanceRequest request : spotInstanceRequests) { spotInstanceIdList.add(request.getInstanceId()); } for (String id : instanceIdList) { Assert.assertTrue(spotInstanceIdList.contains(id)); if (spotInstanceIdList.contains(id)) { spotInstanceCount += 1; } } if (scalingAdjustment != null) { Assert.assertNotNull(itContext.getContextParam(CloudbreakITContextConstants.INSTANCE_COUNT, List.class)); Integer instanceCountPrev = 0; for (String hostGroup : hostGroupList) { List<Map<String, Integer>> instanceList = itContext.getContextParam(CloudbreakITContextConstants.INSTANCE_COUNT, List.class); Assert.assertTrue(instanceList.size() >= 2); instanceCountPrev += instanceList.get(instanceList.size() - 2).get(hostGroup); } Assert.assertEquals(Integer.valueOf(instanceCountPrev + scalingAdjustment), spotInstanceCount); } }
@Action(value = "/manage/submitEC2Key", results = { @Result(name = "input", location = "/manage/view_ec2_keys.jsp"), @Result(name = "success", location = "/manage/viewEC2Keys.action", type = "redirect") } ) public String submitEC2Key() { String retVal = SUCCESS; try { //get AWS credentials from DB AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId()); //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); //create service AmazonEC2 service = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withClientConfiguration(AWSClientConfig.getClientConfig()) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(ec2Key.getEc2Region(), ec2RegionMap.get(ec2Key.getEc2Region()))).build(); //create key pair request CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.withKeyName(ec2Key.getKeyNm()); //call service CreateKeyPairResult createKeyPairResult = service.createKeyPair(createKeyPairRequest); //get key pair result KeyPair keyPair = createKeyPairResult.getKeyPair(); //set private key String privateKey = keyPair.getKeyMaterial(); ec2Key.setPrivateKey(privateKey); //add to db EC2KeyDB.saveEC2Key(ec2Key); } catch (AmazonServiceException ex) { addActionError(ex.getMessage()); retVal = INPUT; } return retVal; }
@Action(value = "/manage/importEC2Key", results = { @Result(name = "input", location = "/manage/view_ec2_keys.jsp"), @Result(name = "success", location = "/manage/viewEC2Keys.action", type = "redirect") } ) public String importEC2Key() { String retVal = SUCCESS; try { //get AWS credentials from DB AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId()); //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); //create service AmazonEC2 service = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withClientConfiguration(AWSClientConfig.getClientConfig()) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(ec2Key.getEc2Region(), ec2RegionMap.get(ec2Key.getEc2Region()))).build(); //describe key pair request DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); describeKeyPairsRequest.setKeyNames(Arrays.asList(ec2Key.getKeyNm())); //call service DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest); if (describeKeyPairsResult != null && describeKeyPairsResult.getKeyPairs().size() > 0) { //add to db EC2KeyDB.saveEC2Key(ec2Key); } else { addActionError("Imported key does not exist on AWS"); retVal = INPUT; } } catch (AmazonServiceException ex) { addActionError(ex.getMessage()); retVal = INPUT; } return retVal; }
public static AmazonEC2 createEC2Client() { return AmazonEC2ClientBuilder.defaultClient(); }
public EC2HostMonitorLookup( Set<String> contactGroups ) throws CandlestackPropertiesException { this.contactGroups = contactGroups; namePrefix = GlobalAWSProperties.getEC2NamePrefix(); nameRegex = GlobalAWSProperties.getEC2NameRegex(); newResourceMonitorDelayMillis = TimeUnit.MINUTES.toMillis( GlobalAWSProperties.getEC2NewResourceMonitorDelay() ); ec2CloudWatchMetrics = GlobalAWSProperties.getEC2CloudwatchMetricsToMonitor(); ec2MetricbeatMetrics = GlobalAWSProperties.getEC2MetricbeatMetricsToMonitor(); ec2Client = AmazonEC2ClientBuilder.standard().withRegion( GlobalAWSProperties.getRegion() ).build(); }
public EC2MetricsFetcher() throws CandlestackException { super( EC2Util.TYPE_NAME, GlobalAWSProperties.getEC2MetricsFetcherSleep() ); namePrefix = GlobalAWSProperties.getEC2NamePrefix(); nameRegex = GlobalAWSProperties.getEC2NameRegex(); ec2CloudWatchMetrics = GlobalAWSProperties.getEC2CloudwatchMetricsToFetch(); ec2Client = AmazonEC2ClientBuilder.standard().withRegion( GlobalAWSProperties.getRegion() ).build(); cloudWatchAccessor = CloudWatchAccessor.getInstance(); }
/** * Constructs a new {@link Ec2ApiClient} that operates against a given AWS * region. * * @param awsCredentials * The AWS credentials used to connect to the AWS account. * @param region * The AWS region that this client operates against. * @param clientConfiguration * Any HTTP client configuration to customize API invocations. */ public Ec2ApiClient(AWSCredentials awsCredentials, String region, ClientConfiguration clientConfiguration) { // limit the time-to-live of the JVM's DNS cache (in seconds) java.security.Security.setProperty("networkaddress.cache.ttl", "60"); this.region = region; this.api = AmazonEC2ClientBuilder.standard().withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build(); }
private static void init() throws Exception { ec2 = AmazonEC2ClientBuilder.standard().withRegion("us-east-1").withCredentials(new ProfileCredentialsProvider()).build(); }