com.amazonaws.services.autoscaling.AmazonAutoScaling Java Examples

The following examples show how to use com.amazonaws.services.autoscaling.AmazonAutoScaling. 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: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch launch configurations test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchLaunchConfigurationsTest() throws Exception {
    
    mockStatic(AmazonAutoScalingClientBuilder.class);
    AmazonAutoScaling asgClient = PowerMockito.mock(AmazonAutoScaling.class);
    AmazonAutoScalingClientBuilder amazonAutoScalingClientBuilder = PowerMockito.mock(AmazonAutoScalingClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonAutoScalingClientBuilder.standard()).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withCredentials(anyObject())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withRegion(anyString())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.build()).thenReturn(asgClient);
    
    DescribeAutoScalingGroupsResult autoScalingGroupsResult = new DescribeAutoScalingGroupsResult();
    List<AutoScalingGroup> asgList = new ArrayList<>();
    asgList.add(new AutoScalingGroup());
    autoScalingGroupsResult.setAutoScalingGroups(asgList);
    when(asgClient.describeAutoScalingGroups(anyObject())).thenReturn(autoScalingGroupsResult);
    assertThat(inventoryUtil.fetchAsg(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #2
Source File: AwsModule.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    bind(AWSSecurityTokenServiceAsync.class).toProvider(AmazonStsAsyncProvider.class);
    bind(AmazonEC2Async.class).toProvider(AmazonEC2AsyncProvider.class);
    bind(AmazonElasticLoadBalancingAsync.class).toProvider(AmazonElasticLoadBalancingAsyncProvider.class);
    bind(AmazonAutoScaling.class).toProvider(AmazonAutoScalingProvider.class);
    bind(AmazonIdentityManagementAsync.class).toProvider(AmazonIamAsyncProvider.class);

    bind(AmazonAutoScalingAsync.class).annotatedWith(Names.named(DataPlaneAmazonAutoScalingAsyncProvider.NAME))
            .toProvider(DataPlaneAmazonAutoScalingAsyncProvider.class);
    bind(AmazonAutoScalingAsync.class).annotatedWith(Names.named(ControlPlaneAmazonAutoScalingAsyncProvider.NAME))
            .toProvider(ControlPlaneAmazonAutoScalingAsyncProvider.class);

    bind(AWSCredentialsProvider.class)
            .annotatedWith(Names.named(DataPlaneControllerCredentialsProvider.NAME))
            .toProvider(DataPlaneControllerCredentialsProvider.class);
    bind(AWSCredentialsProvider.class)
            .annotatedWith(Names.named(DataPlaneAgentCredentialsProvider.NAME))
            .toProvider(DataPlaneAgentCredentialsProvider.class);

    bind(InstanceReaper.class).asEagerSingleton();
}
 
Example #3
Source File: AWSMembership.java    From Raigad with Apache License 2.0 6 votes vote down vote up
@Override
public void expandRacMembership(int count) {
    AmazonAutoScaling client = null;

    try {
        client = getAutoScalingClient();
        DescribeAutoScalingGroupsRequest asgReq = new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(config.getASGName());
        DescribeAutoScalingGroupsResult res = client.describeAutoScalingGroups(asgReq);
        AutoScalingGroup asg = res.getAutoScalingGroups().get(0);
        UpdateAutoScalingGroupRequest ureq = new UpdateAutoScalingGroupRequest();
        ureq.setAutoScalingGroupName(asg.getAutoScalingGroupName());
        ureq.setMinSize(asg.getMinSize() + 1);
        ureq.setMaxSize(asg.getMinSize() + 1);
        ureq.setDesiredCapacity(asg.getMinSize() + 1);
        client.updateAutoScalingGroup(ureq);
    } finally {
        if (client != null) {
            client.shutdown();
        }
    }
}
 
Example #4
Source File: AWSMembership.java    From Raigad with Apache License 2.0 6 votes vote down vote up
/**
 * Actual membership AWS source of truth...
 */
@Override
public int getRacMembershipSize() {
    AmazonAutoScaling client = null;

    try {
        client = getAutoScalingClient();
        DescribeAutoScalingGroupsRequest asgReq = new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(config.getASGName());
        DescribeAutoScalingGroupsResult res = client.describeAutoScalingGroups(asgReq);

        int size = 0;
        for (AutoScalingGroup asg : res.getAutoScalingGroups()) {
            size += asg.getMaxSize();
        }

        logger.info(String.format("Query on ASG returning %d instances", size));

        return size;
    } finally {
        if (client != null) {
            client.shutdown();
        }
    }
}
 
Example #5
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/***
 * Get list of {@link AutoScalingGroup}s for a given tag
 *
 * @param tag Tag to filter the auto scaling groups
 * @return List of {@link AutoScalingGroup}s qualifying the filter tag
 */
public List<AutoScalingGroup> getAutoScalingGroupsWithTag(Tag tag) {

  final AmazonAutoScaling autoScaling = getAmazonAutoScalingClient();

  final DescribeAutoScalingGroupsRequest describeAutoScalingGroupsRequest = new DescribeAutoScalingGroupsRequest();

  final List<AutoScalingGroup> allAutoScalingGroups = autoScaling
      .describeAutoScalingGroups(describeAutoScalingGroupsRequest)
      .getAutoScalingGroups();

  final List<AutoScalingGroup> filteredAutoScalingGroups = Lists.newArrayList();
  for (AutoScalingGroup autoScalingGroup : allAutoScalingGroups) {
    for (TagDescription tagDescription : autoScalingGroup.getTags()) {
      if (tagDescription.getKey().equalsIgnoreCase(tag.getKey()) &&
          tagDescription.getValue().equalsIgnoreCase(tag.getValue())) {
        filteredAutoScalingGroups.add(autoScalingGroup);
      }
    }
  }

  return filteredAutoScalingGroups;
}
 
Example #6
Source File: ASGInventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch scaling policies.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<ScalingPolicy>> fetchScalingPolicies(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
		
		AmazonAutoScaling asgClient;
		Map<String,List<ScalingPolicy>> scalingPolicyList = new LinkedHashMap<>();
		
		String expPrefix = "{\"errcode\": \"NO_RES_REG\" ,\"accountId\": \""+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"ASG\" , \"region\":\"" ;
		for(Region region : RegionUtils.getRegions()){ 
			try{
				if(!skipRegions.contains(region.getName())){ //!skipRegions
					List<ScalingPolicy> _scalingPolicyList = new ArrayList<>();
					asgClient = AmazonAutoScalingClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
					String nextToken = null;
					DescribeAutoScalingGroupsResult  describeResult ;
					do{
						describeResult =  asgClient.describeAutoScalingGroups(new DescribeAutoScalingGroupsRequest().withNextToken(nextToken).withMaxRecords(asgMaxRecord));
						for(AutoScalingGroup _asg : describeResult.getAutoScalingGroups()) {
							_scalingPolicyList.addAll(asgClient.describePolicies(new DescribePoliciesRequest().withAutoScalingGroupName(_asg.getAutoScalingGroupName())).getScalingPolicies());
						}
						nextToken = describeResult.getNextToken();
					}while(nextToken!=null);
					
					if(!_scalingPolicyList.isEmpty() ){
						log.debug("Account : " + accountId + " Type : ASG Scaling Policy "+region.getName()+" >> " + _scalingPolicyList.size());
						scalingPolicyList.put(accountId+delimiter+accountName+delimiter+region.getName(), _scalingPolicyList);
					}
			   	}
			}catch(Exception e){
				log.warn(expPrefix+ region.getName()+"\", \"cause\":\"" +e.getMessage()+"\"}");
				ErrorManageUtil.uploadError(accountId,region.getName(),"asgpolicy",e.getMessage());
			}
		}
		return scalingPolicyList;
	}
 
Example #7
Source File: ASGInventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch launch configurations test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchLaunchConfigurationsTest() throws Exception {
    
    mockStatic(AmazonAutoScalingClientBuilder.class);
    AmazonAutoScaling asgClient = PowerMockito.mock(AmazonAutoScaling.class);
    AmazonAutoScalingClientBuilder amazonAutoScalingClientBuilder = PowerMockito.mock(AmazonAutoScalingClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonAutoScalingClientBuilder.standard()).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withCredentials(anyObject())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withRegion(anyString())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.build()).thenReturn(asgClient);
    
    DescribeAutoScalingGroupsResult autoScalingGroupsResult = new DescribeAutoScalingGroupsResult();
    List<AutoScalingGroup> asgList = new ArrayList<>();
    AutoScalingGroup autoScalingGroup = new AutoScalingGroup();
    autoScalingGroup.setLaunchConfigurationName("launchConfigurationName");
    asgList.add(autoScalingGroup);
    autoScalingGroupsResult.setAutoScalingGroups(asgList);
    when(asgClient.describeAutoScalingGroups(anyObject())).thenReturn(autoScalingGroupsResult);
    
    DescribeLaunchConfigurationsResult launchConfigurationsResult = new DescribeLaunchConfigurationsResult();
    List<LaunchConfiguration> launchConfigurations = new ArrayList<>();
    launchConfigurations.add(new LaunchConfiguration());
    
    launchConfigurationsResult.setLaunchConfigurations(launchConfigurations);
    when(asgClient.describeLaunchConfigurations(anyObject())).thenReturn(launchConfigurationsResult);
    assertThat(asgInventoryUtil.fetchLaunchConfigurations(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #8
Source File: ASGInventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch scaling policies test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchScalingPoliciesTest() throws Exception {
    
    mockStatic(AmazonAutoScalingClientBuilder.class);
    AmazonAutoScaling asgClient = PowerMockito.mock(AmazonAutoScaling.class);
    AmazonAutoScalingClientBuilder amazonAutoScalingClientBuilder = PowerMockito.mock(AmazonAutoScalingClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonAutoScalingClientBuilder.standard()).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withCredentials(anyObject())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withRegion(anyString())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.build()).thenReturn(asgClient);
    
    DescribeAutoScalingGroupsResult autoScalingGroupsResult = new DescribeAutoScalingGroupsResult();
    List<AutoScalingGroup> asgList = new ArrayList<>();
    AutoScalingGroup autoScalingGroup = new AutoScalingGroup();
    autoScalingGroup.setAutoScalingGroupName("autoScalingGrpName");
    asgList.add(autoScalingGroup);
    autoScalingGroupsResult.setAutoScalingGroups(asgList);
    
    when(asgClient.describeAutoScalingGroups(anyObject())).thenReturn(autoScalingGroupsResult);
    
    DescribePoliciesResult policiesResult = new DescribePoliciesResult();
    List<ScalingPolicy> scalingPolicies = new ArrayList<>();
    scalingPolicies.add(new ScalingPolicy());
    policiesResult.setScalingPolicies(scalingPolicies);
    when(asgClient.describePolicies(anyObject())).thenReturn(policiesResult);
    assertThat(asgInventoryUtil.fetchScalingPolicies(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #9
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/***
 * Initialize the AWS SDK Client
 *
 * @param awsClusterSecurityManager The {@link AWSClusterSecurityManager} to fetch AWS credentials
 * @param region The Amazon AWS {@link Region}
 */
public AWSSdkClient(final AWSClusterSecurityManager awsClusterSecurityManager, final Region region) {
  this.amazonEC2Supplier = Suppliers.memoize(new Supplier<AmazonEC2>() {
    @Override
    public AmazonEC2 get() {
      AmazonEC2Client amazonEC2 = new AmazonEC2Client(awsClusterSecurityManager.getCredentialsProvider());
      amazonEC2.setRegion(region);
      return amazonEC2;
    }
  });
  this.amazonS3Supplier = Suppliers.memoize(new Supplier<AmazonS3>() {
    @Override
    public AmazonS3 get() {
      AmazonS3Client amazonS3 = new AmazonS3Client(awsClusterSecurityManager.getCredentialsProvider());
      amazonS3.setRegion(region);
      return amazonS3;
    }
  });
  this.amazonAutoScalingSupplier = Suppliers.memoize(new Supplier<AmazonAutoScaling>() {
    @Override
    public AmazonAutoScaling get() {
      AmazonAutoScalingClient amazonAutoScaling =
              new AmazonAutoScalingClient(awsClusterSecurityManager.getCredentialsProvider());
      amazonAutoScaling.setRegion(region);
      return amazonAutoScaling;
    }
  });
}
 
Example #10
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch asg.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<AutoScalingGroup>> fetchAsg(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){

	AmazonAutoScaling asgClient;
	Map<String,List<AutoScalingGroup>> asgList = new LinkedHashMap<>();

	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"ASG\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				List<AutoScalingGroup> asgListTemp = new ArrayList<>();
				asgClient = AmazonAutoScalingClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				String nextToken = null;
				DescribeAutoScalingGroupsResult  describeResult ;
				do{
					describeResult =  asgClient.describeAutoScalingGroups(new DescribeAutoScalingGroupsRequest().withNextToken(nextToken).withMaxRecords(asgMaxRecord));
					asgListTemp.addAll(describeResult.getAutoScalingGroups());
					nextToken = describeResult.getNextToken();
				}while(nextToken!=null);

				if(!asgListTemp.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : ASG "+region.getName()+" >> " + asgListTemp.size());
					asgList.put(accountId+delimiter+accountName+delimiter+region.getName(), asgListTemp);
				}
		   	}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"asg",e.getMessage());
		}
	}
	return asgList;
}
 
Example #11
Source File: AWSMembership.java    From Raigad with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<String>> getRacMembership(Collection<String> autoScalingGroupNames) {
    if (CollectionUtils.isEmpty(autoScalingGroupNames)) {
        return Collections.emptyMap();
    }

    AmazonAutoScaling client = null;

    try {
        client = getAutoScalingClient();
        DescribeAutoScalingGroupsRequest describeAutoScalingGroupsRequest =
                new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(autoScalingGroupNames);
        DescribeAutoScalingGroupsResult describeAutoScalingGroupsResult = client.describeAutoScalingGroups(describeAutoScalingGroupsRequest);

        Map<String, List<String>> asgs = new HashMap<>();
        for (AutoScalingGroup autoScalingGroup : describeAutoScalingGroupsResult.getAutoScalingGroups()) {
            List<String> asgInstanceIds = Lists.newArrayList();
            for (Instance asgInstance : autoScalingGroup.getInstances()) {
                if (!(asgInstance.getLifecycleState().equalsIgnoreCase("terminating") ||
                        asgInstance.getLifecycleState().equalsIgnoreCase("shutting-down") ||
                        asgInstance.getLifecycleState().equalsIgnoreCase("terminated"))) {
                    asgInstanceIds.add(asgInstance.getInstanceId());
                }
            }
            asgs.put(autoScalingGroup.getAutoScalingGroupName(), asgInstanceIds);
            logger.info("AWS returned the following instance ID's for {} ASG: {}",
                    autoScalingGroup.getAutoScalingGroupName(),
                    StringUtils.join(asgInstanceIds, ","));
        }

        return asgs;
    } finally {
        if (client != null) {
            client.shutdown();
        }
    }
}
 
Example #12
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/***
 * Delete an auto scaling group by its name
 *
 * @param autoScalingGroupName Name of auto scaling group to delete
 * @param shouldForceDelete If the AutoScalingGroup should be deleted without waiting for instances to terminate
 */
public void deleteAutoScalingGroup(String autoScalingGroupName,
    boolean shouldForceDelete) {

  final AmazonAutoScaling autoScaling = getAmazonAutoScalingClient();

  final DeleteAutoScalingGroupRequest deleteLaunchConfigurationRequest = new DeleteAutoScalingGroupRequest()
      .withAutoScalingGroupName(autoScalingGroupName)
      .withForceDelete(shouldForceDelete);

  autoScaling.deleteAutoScalingGroup(deleteLaunchConfigurationRequest);

  LOGGER.info("Deleted AutoScalingGroup: " + autoScalingGroupName);
}
 
Example #13
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/***
 * Create a launch configuration that can be later used to create {@link AmazonAutoScaling} groups
 *
 * @param launchConfigName Desired launch config name
 * @param imageId AMI image id to use
 * @param instanceType EC2 instance type to use
 * @param keyName Key name
 * @param securityGroups Security groups to apply
 * @param kernelId Optional kernel id
 * @param ramdiskId Optional ram disk id
 * @param blockDeviceMapping Optional EBS device mapping
 * @param iamInstanceProfile Optional IAM instance profile
 * @param instanceMonitoring Optional instance monitoring
 * @param userData User data (eg. shell script to execute at instance boot under this launch config)
 */
public void createLaunchConfig(String launchConfigName,
    String imageId,
    String instanceType,
    String keyName,
    String securityGroups,
    Optional<String> kernelId,
    Optional<String> ramdiskId,
    Optional<BlockDeviceMapping> blockDeviceMapping,
    Optional<String> iamInstanceProfile,
    Optional<InstanceMonitoring> instanceMonitoring,
    String userData) {

  final AmazonAutoScaling autoScaling = getAmazonAutoScalingClient();

  CreateLaunchConfigurationRequest createLaunchConfigurationRequest = new CreateLaunchConfigurationRequest()
      .withLaunchConfigurationName(launchConfigName)
      .withImageId(imageId)
      .withInstanceType(instanceType)
      .withSecurityGroups(SPLITTER.splitToList(securityGroups))
      .withKeyName(keyName)
      .withUserData(userData);
  if (kernelId.isPresent()) {
    createLaunchConfigurationRequest = createLaunchConfigurationRequest
        .withKernelId(kernelId.get());
  }
  if (ramdiskId.isPresent()) {
    createLaunchConfigurationRequest = createLaunchConfigurationRequest
        .withRamdiskId(ramdiskId.get());
  }
  if (blockDeviceMapping.isPresent()) {
    createLaunchConfigurationRequest = createLaunchConfigurationRequest
        .withBlockDeviceMappings(blockDeviceMapping.get());
  }
  if (iamInstanceProfile.isPresent()) {
    createLaunchConfigurationRequest = createLaunchConfigurationRequest
        .withIamInstanceProfile(iamInstanceProfile.get());
  }
  if (instanceMonitoring.isPresent()) {
    createLaunchConfigurationRequest = createLaunchConfigurationRequest
        .withInstanceMonitoring(instanceMonitoring.get());
  }

  autoScaling.createLaunchConfiguration(createLaunchConfigurationRequest);

  LOGGER.info("Created Launch Configuration: " + launchConfigName);
}
 
Example #14
Source File: AWSMembership.java    From Raigad with Apache License 2.0 4 votes vote down vote up
protected AmazonAutoScaling getAutoScalingClient() {
    AmazonAutoScaling client = new AmazonAutoScalingClient(provider.getAwsCredentialProvider());
    client.setEndpoint("autoscaling." + config.getDC() + ".amazonaws.com");
    return client;
}
 
Example #15
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/***
 * Create and launch an {@link AmazonAutoScaling} group
 *
 * @param groupName Auto scaling group name
 * @param launchConfig Launch configuration string
 * @param minSize Minimum number of instances to maintain in auto scaling group
 * @param maxSize Maximum number of instances to scale up-to for load
 * @param desiredCapacity Desired number of instances to maintain in auto scaling group
 * @param availabilityZones Optional availability zones to make use of
 * @param cooldown Optional cooldown period before any scaling event (default is 300 secs)
 * @param healthCheckGracePeriod Optional grace period till which no health check is performed after bootup (default is 300 secs)
 * @param healthCheckType Optional health check type (default is EC2 instance check)
 * @param loadBalancer Optional load balancer to use
 * @param terminationPolicy Optional termination policies
 * @param tags Optional tags to set on auto scaling group (they are set to propagate to EC2 instances implicitly)
 */
public void createAutoScalingGroup(String groupName,
    String launchConfig,
    Integer minSize, Integer maxSize, Integer desiredCapacity,
    Optional<String> availabilityZones,
    Optional<Integer> cooldown,
    Optional<Integer> healthCheckGracePeriod,
    Optional<String> healthCheckType,
    Optional<String> loadBalancer,
    Optional<String> terminationPolicy,
    List<Tag> tags) {

  AmazonAutoScaling autoScaling = getAmazonAutoScalingClient();

  // Propagate ASG tags to EC2 instances launched under the ASG by default
  // (we want to ensure this, hence not configurable)
  final List<Tag> tagsWithPropagationSet = Lists.newArrayList();
  for (Tag tag : tags) {
    tagsWithPropagationSet.add(tag.withPropagateAtLaunch(true));
  }

  CreateAutoScalingGroupRequest createAutoScalingGroupRequest = new CreateAutoScalingGroupRequest()
      .withAutoScalingGroupName(groupName)
      .withLaunchConfigurationName(launchConfig)
      .withMinSize(minSize)
      .withMaxSize(maxSize)
      .withDesiredCapacity(desiredCapacity)
      .withTags(tagsWithPropagationSet);
  if (availabilityZones.isPresent()) {
    createAutoScalingGroupRequest = createAutoScalingGroupRequest
        .withAvailabilityZones(SPLITTER.splitToList(availabilityZones.get()));
  }
  if (cooldown.isPresent()) {
    createAutoScalingGroupRequest = createAutoScalingGroupRequest
        .withDefaultCooldown(cooldown.get());
  }
  if (healthCheckGracePeriod.isPresent()) {
    createAutoScalingGroupRequest = createAutoScalingGroupRequest
        .withHealthCheckGracePeriod(healthCheckGracePeriod.get());
  }
  if (healthCheckType.isPresent()) {
    createAutoScalingGroupRequest = createAutoScalingGroupRequest
        .withHealthCheckType(healthCheckType.get());
  }
  if (loadBalancer.isPresent()) {
    createAutoScalingGroupRequest = createAutoScalingGroupRequest
        .withLoadBalancerNames(SPLITTER.splitToList(loadBalancer.get()));
  }
  if (terminationPolicy.isPresent()) {
    createAutoScalingGroupRequest = createAutoScalingGroupRequest
        .withTerminationPolicies(SPLITTER.splitToList(terminationPolicy.get()));
  }

  autoScaling.createAutoScalingGroup(createAutoScalingGroupRequest);

  LOGGER.info("Created AutoScalingGroup: " + groupName);
}
 
Example #16
Source File: MvcConfiguration.java    From aws-codedeploy-sample-tomcat with Apache License 2.0 4 votes vote down vote up
@Bean
public AmazonAutoScaling autoScaling() {
    AmazonAutoScaling client = new AmazonAutoScalingClient();
    client.setRegion(region);
    return client;
}
 
Example #17
Source File: AmazonAutoScalingProvider.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
public AmazonAutoScaling get() {
    return amazonAutoScaling;
}
 
Example #18
Source File: ASGInventoryUtil.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Fetch launch configurations.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<LaunchConfiguration>> fetchLaunchConfigurations(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	AmazonAutoScaling asgClient;
	Map<String,List<LaunchConfiguration>> launchConfigurationList = new LinkedHashMap<>();
	List<String> launchConfigurationNames = new ArrayList<>();
	
	String expPrefix = "{\"errcode\": \"NO_RES_REG\" ,\"accountId\": \""+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"ASG\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){ 
		try{
			if(!skipRegions.contains(region.getName())){ //!skipRegions
				List<LaunchConfiguration> launchConfigurationListTemp = new ArrayList<>();
				asgClient = AmazonAutoScalingClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				String nextToken = null;
				DescribeAutoScalingGroupsResult  describeResult ;
				do{
					describeResult =  asgClient.describeAutoScalingGroups(new DescribeAutoScalingGroupsRequest().withNextToken(nextToken).withMaxRecords(asgMaxRecord));
					for(AutoScalingGroup _asg : describeResult.getAutoScalingGroups()) {
						launchConfigurationNames.add(_asg.getLaunchConfigurationName());
					}
					nextToken = describeResult.getNextToken();
				}while(nextToken!=null);
				List<String> launchConfigurationNamesTemp = new ArrayList<>();
				
				for(int i =0 ; i<launchConfigurationNames.size();i++){
					launchConfigurationNamesTemp.add(launchConfigurationNames.get(i));
					if((i+1)%50==0 || i == launchConfigurationNames.size()-1){
						launchConfigurationListTemp.addAll(asgClient.describeLaunchConfigurations(new DescribeLaunchConfigurationsRequest().withLaunchConfigurationNames(launchConfigurationNamesTemp)).getLaunchConfigurations());
						launchConfigurationNamesTemp = new ArrayList<>();
					}
					
				}
				
				if(!launchConfigurationListTemp.isEmpty() ){
					log.debug("Account : " + accountId + " Type : ASG Launch Configurations "+region.getName()+" >> " + launchConfigurationListTemp.size());
					launchConfigurationList.put(accountId+delimiter+accountName+delimiter+region.getName(), launchConfigurationListTemp);
				}
		   	}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+"\", \"cause\":\"" +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"launchconfig",e.getMessage());
		}
	}
	return launchConfigurationList;
}
 
Example #19
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 3 votes vote down vote up
/***
 * Delete a launch configuration by its name
 *
 * @param launchConfigName Name of launch config to delete
 */
public void deleteLaunchConfiguration(String launchConfigName) {

  final AmazonAutoScaling autoScaling = getAmazonAutoScalingClient();

  final DeleteLaunchConfigurationRequest deleteLaunchConfigurationRequest = new DeleteLaunchConfigurationRequest()
      .withLaunchConfigurationName(launchConfigName);

  autoScaling.deleteLaunchConfiguration(deleteLaunchConfigurationRequest);

  LOGGER.info("Deleted Launch Configuration: " + launchConfigName);
}
 
Example #20
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 2 votes vote down vote up
/***
 * Creates a new Amazon AutoScaling client to invoke service methods on Amazon AutoScaling
 *
 * @return Amazon AutoScaling client to invoke service methods on Amazon AutoScaling
 */
public AmazonAutoScaling getAmazonAutoScalingClient() {
  return amazonAutoScalingSupplier.get();
}