com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder Java Examples

The following examples show how to use com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder. 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 cloud formation stack test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchCloudFormationStackTest() throws Exception {
    
    mockStatic(AmazonCloudFormationClientBuilder.class);
    AmazonCloudFormation cloudFormClient = PowerMockito.mock(AmazonCloudFormation.class);
    AmazonCloudFormationClientBuilder amazonCloudFormationClientBuilder = PowerMockito.mock(AmazonCloudFormationClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonCloudFormationClientBuilder.standard()).thenReturn(amazonCloudFormationClientBuilder);
    when(amazonCloudFormationClientBuilder.withCredentials(anyObject())).thenReturn(amazonCloudFormationClientBuilder);
    when(amazonCloudFormationClientBuilder.withRegion(anyString())).thenReturn(amazonCloudFormationClientBuilder);
    when(amazonCloudFormationClientBuilder.build()).thenReturn(cloudFormClient);
    
    DescribeStacksResult describeStacksResult = new DescribeStacksResult();
    List<Stack> stacks = new ArrayList<>();
    stacks.add(new Stack());
    describeStacksResult.setStacks(stacks);
    when(cloudFormClient.describeStacks(anyObject())).thenReturn(describeStacksResult);
    assertThat(inventoryUtil.fetchCloudFormationStack(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #2
Source File: CFNExecuteChangeSetStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> run() throws Exception {
	final String changeSet = this.step.getChangeSet();
	final String stack = this.step.getStack();
	final TaskListener listener = this.getContext().get(TaskListener.class);

	Preconditions.checkArgument(changeSet != null && !changeSet.isEmpty(), "Change Set must not be null or empty");

	Preconditions.checkArgument(stack != null && !stack.isEmpty(), "Stack must not be null or empty");

	listener.getLogger().format("Executing CloudFormation change set %s %n", changeSet);

	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	CloudFormationStack cfnStack = new CloudFormationStack(client, stack, listener);
	Map<String, String> outputs = cfnStack.executeChangeSet(changeSet, Execution.this.step.getPollConfiguration());
	listener.getLogger().println("Execute change set complete");
	return outputs;
}
 
Example #3
Source File: CloudFormationClientBuilder.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
public static AmazonCloudFormation getCloudFormationClient(
        String accessKeyId,
        String secretAccessKey,
        String proxyHost,
        String proxyPort,
        String proxyUsername,
        String proxyPassword,
        String connectTimeoutMs,
        String executionTimeoutMs,
        String region) {

    connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
    executionTimeoutMs = defaultIfEmpty(executionTimeoutMs, DefaultValues.EXEC_TIMEOUT);

    ClientConfiguration clientConf = AmazonWebServiceClientUtil.getClientConfiguration(proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, executionTimeoutMs);

    return AmazonCloudFormationClientBuilder.standard()
            .withRegion(region)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKeyId, secretAccessKey)))
            .withClientConfiguration(clientConf)
            .build();
}
 
Example #4
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AmazonCloudFormation amazonCloudFormation() {
    return decorateWithConfigsAndBuild(
        AmazonCloudFormationClientBuilder.standard(),
        LocalstackDocker::getEndpointCloudFormation
    );
}
 
Example #5
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch cloud formation stack.
 *
 * @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<Stack>> fetchCloudFormationStack(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	AmazonCloudFormation cloudFormClient ;
	Map<String,List<Stack>> stacks = new LinkedHashMap<>();
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Stack\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				List<Stack> stacksTemp = new ArrayList<>();
				String nextToken = null;
				cloudFormClient = AmazonCloudFormationClientBuilder.standard().
						 withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeStacksResult describeResult ;
				do{
					describeResult =  cloudFormClient.describeStacks(new DescribeStacksRequest().withNextToken(nextToken));
					stacksTemp.addAll(describeResult.getStacks());
					nextToken = describeResult.getNextToken();
				}while(nextToken!=null);

				if(! stacksTemp.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Cloud Formation Stack "+region.getName() + " >> " + stacksTemp.size());
					stacks.put(accountId+delimiter+accountName+delimiter+region.getName(), stacksTemp);
				}
			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"stack",e.getMessage());
		}
	}
	return stacks;
}
 
Example #6
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor
 *
 * @param stackSetName - stack name
 */
public CloudFormationClient(String stackSetName) throws Exception {

    this.stackName = stackSetName;
    propertyValues = TestProperties.getProperties();
    // Create AWS client
    amazonCloudFormation = AmazonCloudFormationClientBuilder.standard()
            .withRegion(Regions.getCurrentRegion().getName())
            .withCredentials(new InstanceProfileCredentialsProvider(true)).build();
}
 
Example #7
Source File: AWSProvider.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 * This method releases the provisioned AWS infrastructure.
 *
 * @param script            the script config
 * @param inputs
 * @return true or false to indicate the result of destroy operation.
 * @throws TestGridInfrastructureException when AWS error occurs in deletion process.
 * @throws InterruptedException            when there is an interruption while waiting for the result.
 */
private boolean doRelease(Script script, Properties inputs, TestPlan testPlan)
        throws TestGridInfrastructureException, InterruptedException, TestGridDAOException {
    Path configFilePath;
    String stackName = script.getName();
    String region = inputs.getProperty(AWS_REGION_PARAMETER);
    configFilePath = TestGridUtil.getConfigFilePath();
    AmazonCloudFormation stackdestroy = AmazonCloudFormationClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest();
    deleteStackRequest.setStackName(stackName);
    stackdestroy.deleteStack(deleteStackRequest);
    logger.info(StringUtil.concatStrings("Stack : ", stackName, " is handed over for deletion!"));

    //Notify AWSResourceManager about stack destruction to release acquired resources
    AWSResourceManager awsResourceManager = new AWSResourceManager();
    awsResourceManager.notifyStackDeletion(testPlan, script, region);

    boolean waitForStackDeletion = Boolean
            .parseBoolean(getProperty(ConfigurationProperties.WAIT_FOR_STACK_DELETION));
    if (waitForStackDeletion) {
        logger.info(StringUtil.concatStrings("Waiting for stack : ", stackName, " to delete.."));
        Waiter<DescribeStacksRequest> describeStacksRequestWaiter = new
                AmazonCloudFormationWaiters(stackdestroy).stackDeleteComplete();
        try {
            describeStacksRequestWaiter.run(new WaiterParameters<>(new DescribeStacksRequest()
                    .withStackName(stackName)));
        } catch (WaiterUnrecoverableException e) {

            throw new TestGridInfrastructureException("Error occurred while waiting for Stack :"
                                                      + stackName + " deletion !");
        }
    }
    return true;
}
 
Example #8
Source File: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void deleteAllStackFunctionVersions(AWSLambda client, String stackName) throws Exception  {
	TaskListener listener = Execution.this.getContext().get(TaskListener.class);
	listener.getLogger().format("Deleting old versions from stackName=%s%n", stackName);
	AmazonCloudFormation cloudformation = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), this.getContext());
	DescribeStackResourcesResult result = cloudformation.describeStackResources(new DescribeStackResourcesRequest()
			.withStackName(stackName)
	);
	for (StackResource stackResource : result.getStackResources()) {
		if ("AWS::Lambda::Function".equals(stackResource.getResourceType())) {
			deleteAllVersions(client, stackResource.getPhysicalResourceId());
		}
	}
}
 
Example #9
Source File: CFNValidateStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean start() throws Exception {
	final String file = this.step.getFile();
	final String url = this.step.getUrl();

	if ((file == null || file.isEmpty()) && (url == null || url.isEmpty())) {
		throw new IllegalArgumentException("Either a file or url for the template must be specified");
	}

	this.getContext().get(TaskListener.class).getLogger().format("Validating CloudFormation template %s %n", file);

	final String template = this.readTemplate(file);

	new Thread("cfnValidate-" + file) {
		@Override
		public void run() {
			AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
			try {
				ValidateTemplateRequest request = new ValidateTemplateRequest();
				if (template != null) {
					request.withTemplateBody(template);
				} else {
					request.withTemplateURL(url);
				}
				ValidateTemplateResult result = client.validateTemplate(request);
				Execution.this.getContext().onSuccess(AwsSdkResponseToJson.convertToMap(result));
			} catch (AmazonCloudFormationException | IOException e) {
				Execution.this.getContext().onFailure(e);
			}
		}
	}.start();
	return false;
}
 
Example #10
Source File: CFNDeleteStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public Void run() throws Exception {
	final String stack = this.step.getStack();
	final TaskListener listener = this.getContext().get(TaskListener.class);

	Preconditions.checkArgument(stack != null && !stack.isEmpty(), "Stack must not be null or empty");

	listener.getLogger().format("Removing CloudFormation stack %s %n", stack);

	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	CloudFormationStack cfnStack = new CloudFormationStack(client, stack, listener);
	cfnStack.delete(Execution.this.step.getPollConfiguration(), this.step.getRetainResources(), this.step.getRoleArn(), this.step.getClientRequestToken());
	listener.getLogger().println("Stack deletion complete");
	return null;
}
 
Example #11
Source File: CFNDeleteStackSetStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public Void run() throws Exception {
	final String stackSet = this.step.getStackSet();
	final TaskListener listener = this.getContext().get(TaskListener.class);

	Preconditions.checkArgument(stackSet != null && !stackSet.isEmpty(), "StackSet must not be null or empty");

	listener.getLogger().format("Removing CloudFormation stack set %s %n", stackSet);

	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	CloudFormationStackSet cfnStackSet = new CloudFormationStackSet(client, stackSet, listener, SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY);
	cfnStackSet.delete();
	listener.getLogger().println("Stack Set deletion complete");
	return null;
}
 
Example #12
Source File: CFNDescribeStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	final String stack = this.step.getStack();
	final TaskListener listener = this.getContext().get(TaskListener.class);

	Preconditions.checkArgument(stack != null && !stack.isEmpty(), "Stack must not be null or empty");

	listener.getLogger().format("Getting outputs of CloudFormation stack %s %n", stack);
	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	CloudFormationStack cfnStack = new CloudFormationStack(client, stack, listener);
	return cfnStack.describeOutputs();
}
 
Example #13
Source File: CloudFormationFacade.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 4 votes vote down vote up
public CloudFormationFacade(Regions region, AWSCredentialsProvider credentials) {
    this.cloudformation = AmazonCloudFormationClientBuilder.standard()
            .withCredentials(credentials)
            .withRegion(region)
            .build();
}
 
Example #14
Source File: CFNExportsStep.java    From pipeline-aws-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	this.getContext().get(TaskListener.class).getLogger().format("Getting global exports of CloudFormation %n");
	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	return Execution.this.getExports(client, null);
}
 
Example #15
Source File: AbstractCFNCreateStep.java    From pipeline-aws-plugin with Apache License 2.0 4 votes vote down vote up
protected CloudFormationStack getCfnStack() {
	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), this.getEnvVars());
	return new CloudFormationStack(client, this.getStack(), this.getListener());
}
 
Example #16
Source File: AbstractCFNCreateStackSetStep.java    From pipeline-aws-plugin with Apache License 2.0 4 votes vote down vote up
protected CloudFormationStackSet getCfnStackSet() {
	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), this.getEnvVars());
	return new CloudFormationStackSet(client, this.getStackSet(), this.getListener(), SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY);
}