com.amazonaws.services.cloudformation.model.DeleteStackRequest Java Examples

The following examples show how to use com.amazonaws.services.cloudformation.model.DeleteStackRequest. 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: AwsNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test(expected = CloudConnectorException.class)
public void testDeleteNetworkWithSubNetsShouldThrowAnExceptionWhenTheStackDeletionFailed()
        throws InterruptedException, ExecutionException, TimeoutException {
    NetworkDeletionRequest networkDeletionRequest = createNetworkDeletionRequest();
    AmazonCloudFormationRetryClient cloudFormationRetryClient = mock(AmazonCloudFormationRetryClient.class);
    AmazonCloudFormationClient cfClient = mock(AmazonCloudFormationClient.class);
    when(awsClient.createCloudFormationRetryClient(any(AwsCredentialView.class), eq(networkDeletionRequest.getRegion())))
            .thenReturn(cloudFormationRetryClient);
    when(awsClient.createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cfClient);
    when(cfClient.waiters()).thenReturn(cfWaiters);
    when(cfWaiters.stackDeleteComplete()).thenReturn(deletionWaiter);
    doThrow(new WaiterTimedOutException("fail")).when(deletionWaiter).run(any());

    underTest.deleteNetworkWithSubnets(networkDeletionRequest);

    verify(cloudFormationRetryClient).deleteStack(any(DeleteStackRequest.class));
    verify(awsClient).createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(awsClient).createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()));
}
 
Example #2
Source File: AwsNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteNetworkWithSubNetsShouldDeleteTheStackAndTheResourceGroup() {
    NetworkDeletionRequest networkDeletionRequest = createNetworkDeletionRequest();
    AmazonCloudFormationRetryClient cloudFormationRetryClient = mock(AmazonCloudFormationRetryClient.class);
    AmazonCloudFormationClient cfClient = mock(AmazonCloudFormationClient.class);
    when(awsClient.createCloudFormationRetryClient(any(AwsCredentialView.class), eq(networkDeletionRequest.getRegion())))
            .thenReturn(cloudFormationRetryClient);
    when(awsClient.createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cfClient);
    when(cfClient.waiters()).thenReturn(cfWaiters);
    when(cfWaiters.stackDeleteComplete()).thenReturn(deletionWaiter);

    underTest.deleteNetworkWithSubnets(networkDeletionRequest);

    verify(cloudFormationRetryClient).deleteStack(any(DeleteStackRequest.class));
    verify(awsClient).createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(awsClient).createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(deletionWaiter, times(1)).run(any());
}
 
Example #3
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteStack() throws ExecutionException {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	Mockito.when(client.waiters()).thenReturn(new AmazonCloudFormationWaiters(client));

	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);

	stack.delete(PollConfiguration.DEFAULT, new String[]{"myresourcetoretain"}, "myarn", "myclientrequesttoken");

	ArgumentCaptor<DeleteStackRequest> captor = ArgumentCaptor.forClass(DeleteStackRequest.class);
	Mockito.verify(client).deleteStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new DeleteStackRequest()
															   .withStackName("foo")
															   .withClientRequestToken("myclientrequesttoken")
															   .withRoleARN("myarn")
															   .withRetainResources("myresourcetoretain")

	);
	Mockito.verify(this.eventPrinter).waitAndPrintStackEvents(Mockito.eq("foo"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
}
 
Example #4
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteStackByStackNameOnly() throws ExecutionException {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	Mockito.when(client.waiters()).thenReturn(new AmazonCloudFormationWaiters(client));

	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);

	stack.delete(PollConfiguration.DEFAULT, null, null, null);

	ArgumentCaptor<DeleteStackRequest> captor = ArgumentCaptor.forClass(DeleteStackRequest.class);
	Mockito.verify(client).deleteStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new DeleteStackRequest()
			.withStackName("foo")

	);
	Mockito.verify(this.eventPrinter).waitAndPrintStackEvents(Mockito.eq("foo"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
}
 
Example #5
Source File: TestStackEnvironment.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private DescribeStackResourcesResult getStackResources(String stackName)
		throws InterruptedException, IOException {
	try {
		DescribeStacksResult describeStacksResult = this.amazonCloudFormationClient
				.describeStacks(new DescribeStacksRequest().withStackName(stackName));
		for (Stack stack : describeStacksResult.getStacks()) {
			if (isAvailable(stack)) {
				return this.amazonCloudFormationClient
						.describeStackResources(new DescribeStackResourcesRequest()
								.withStackName(stack.getStackName()));
			}
			if (isError(stack)) {
				if (this.stackCreatedByThisInstance) {
					throw new IllegalArgumentException("Could not create stack");
				}
				this.amazonCloudFormationClient.deleteStack(
						new DeleteStackRequest().withStackName(stack.getStackName()));
				return getStackResources(stackName);
			}
			if (isInProgress(stack)) {
				// noinspection BusyWait
				Thread.sleep(5000L);
				return getStackResources(stackName);
			}
		}
	}
	catch (AmazonClientException e) {
		String templateBody = FileCopyUtils.copyToString(new InputStreamReader(
				new ClassPathResource(TEMPLATE_PATH).getInputStream()));
		this.amazonCloudFormationClient.createStack(new CreateStackRequest()
				.withTemplateBody(templateBody).withOnFailure(OnFailure.DELETE)
				.withStackName(stackName)
				.withTags(new Tag().withKey("tag1").withValue("value1"))
				.withParameters(new Parameter().withParameterKey("RdsPassword")
						.withParameterValue(this.rdsPassword)));
		this.stackCreatedByThisInstance = true;
	}

	return getStackResources(stackName);
}
 
Example #6
Source File: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteNetworkWithSubnets(NetworkDeletionRequest networkDeletionRequest) {
    if (!networkDeletionRequest.isExisting()) {
        AwsCredentialView credentialView = new AwsCredentialView(networkDeletionRequest.getCloudCredential());
        AmazonCloudFormationRetryClient cloudFormationRetryClient = getCloudFormationRetryClient(credentialView, networkDeletionRequest.getRegion());
        DeleteStackRequest deleteStackRequest = new DeleteStackRequest();
        deleteStackRequest.setStackName(networkDeletionRequest.getStackName());
        cloudFormationRetryClient.deleteStack(deleteStackRequest);
        AmazonCloudFormationClient cfClient = awsClient.createCloudFormationClient(credentialView, networkDeletionRequest.getRegion());
        Waiter<DescribeStacksRequest> deletionWaiter = cfClient.waiters().stackDeleteComplete();
        LOGGER.debug("CloudFormation stack deletion request sent with stack name: '{}' ", networkDeletionRequest.getStackName());
        DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(networkDeletionRequest.getStackName());
        run(deletionWaiter, describeStacksRequest, null);
    }
}
 
Example #7
Source File: AwsTerminateService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void waitAndDeleteCloudformationStack(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources,
        AmazonCloudFormationClient amazonCloudFormationClient) {
    CloudResource stackResource = cfStackUtil.getCloudFormationStackResource(resources);
    if (stackResource == null) {
        LOGGER.debug("No cloudformation stack in resources");
        return;
    }
    String cFStackName = stackResource.getName();
    AmazonCloudFormationRetryClient cfRetryClient = awsClient.createCloudFormationRetryClient(amazonCloudFormationClient);
    LOGGER.debug("Search and wait stack with name: {}", cFStackName);
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(cFStackName);
    try {
        retryService.testWith2SecDelayMax15Times(() -> isStackExist(cfRetryClient, cFStackName, describeStacksRequest));
    } catch (ActionFailedException ignored) {
        LOGGER.debug("Stack not found with name: {}", cFStackName);
        return;
    }

    resumeAutoScalingPolicies(ac, stack);
    LOGGER.debug("Delete cloudformation stack from resources");
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName(cFStackName);
    cfRetryClient.deleteStack(deleteStackRequest);
    Waiter<DescribeStacksRequest> stackDeleteCompleteWaiter = amazonCloudFormationClient.waiters().stackDeleteComplete();
    try {
        WaiterParameters<DescribeStacksRequest> describeStacksRequestWaiterParameters = new WaiterParameters<>(describeStacksRequest)
                .withPollingStrategy(getBackoffCancellablePollingStrategy(null));
        stackDeleteCompleteWaiter.run(describeStacksRequestWaiterParameters);
    } catch (Exception e) {
        LOGGER.debug("Cloudformation stack delete failed ", e);
        throw new CloudConnectorException(e.getMessage(), e);
    }
    LOGGER.debug("Cloudformation stack from resources has been deleted");
}
 
Example #8
Source File: TearDownCloudFormationTestsTask.java    From aws-ant-tasks with Apache License 2.0 5 votes vote down vote up
public void execute() {
    checkParams();
    AmazonEC2Client ec2Client = getOrCreateClient(AmazonEC2Client.class);
    ec2Client
            .deleteKeyPair(new DeleteKeyPairRequest().withKeyName(keyName));
    AmazonCloudFormationClient cloudFormationClient = getOrCreateClient(AmazonCloudFormationClient.class);
    cloudFormationClient.deleteStack(new DeleteStackRequest()
            .withStackName(stackName));
}
 
Example #9
Source File: TestStackEnvironment.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
	if (this.stackCreatedByThisInstance) {
		this.amazonCloudFormationClient.deleteStack(
				new DeleteStackRequest().withStackName(DEFAULT_STACK_NAME));
	}
}
 
Example #10
Source File: AwsIntegrationTestStackRule.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Override
protected void after() {
	this.cloudFormation.deleteStack(new DeleteStackRequest()
			.withStackName(this.stackName));
	try {
		waitForCompletion();
	}
	catch (InterruptedException e) {
		// Ignore the InterruptedException
	}
	finally {
		System.clearProperty("cloud.aws.credentials.accessKey");
		System.clearProperty("cloud.aws.credentials.secretKey");
	}
}
 
Example #11
Source File: CloudFormationStack.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
public void delete(PollConfiguration pollConfiguration, String[] retainResources, String roleArn, String clientRequestToken) throws ExecutionException {
	DeleteStackRequest req = new DeleteStackRequest().withStackName(this.stack).withRoleARN(roleArn).withClientRequestToken(clientRequestToken);
	if (retainResources != null){
		req.withRetainResources(retainResources);
	}
	this.client.deleteStack(req);
	new EventPrinter(this.client, this.listener).waitAndPrintStackEvents(this.stack, this.client.waiters().stackDeleteComplete(), pollConfiguration);
}
 
Example #12
Source File: CloudFormationManager.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 5 votes vote down vote up
public void terminateStack(String name) 
{
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest();
    
    deleteStackRequest.setStackName(name);
    
    cf.deleteStack(deleteStackRequest);
}
 
Example #13
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 #14
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 4 votes vote down vote up
/**
 * Delete the stack {@link #stackName}
 */
public void deleteStack() throws Exception {

    CFTStackInfo cftStackInfo = getStackInfo();
    String rootStackId = cftStackInfo.stackId(); // Use the stack id to track the delete operation
    LOGGER.info("rootStackId   =   " + rootStackId);

    // Go through the stack and pick up resources that we want
    // to finalize before deleting the stack.
    List<String> s3BucketIds = new ArrayList<>();

    DescribeStacksResult describeStacksResult = amazonCloudFormation.describeStacks();
    for (Stack currentStack : describeStacksResult.getStacks()) {
        if (rootStackId.equals(currentStack.getRootId()) || rootStackId
                .equals(currentStack.getStackId())) {
            LOGGER.info("stackId   =   " + currentStack.getStackId());
            DescribeStackResourcesRequest describeStackResourcesRequest = new DescribeStackResourcesRequest();
            describeStackResourcesRequest.setStackName(currentStack.getStackName());
            List<StackResource> stackResources = amazonCloudFormation
                    .describeStackResources(describeStackResourcesRequest).getStackResources();
            for (StackResource stackResource : stackResources) {
                if (!stackResource.getResourceStatus()
                        .equals(ResourceStatus.DELETE_COMPLETE.toString())) {
                    if (stackResource.getResourceType().equals("AWS::S3::Bucket")) {
                        s3BucketIds.add(stackResource.getPhysicalResourceId());
                    }
                }
            }
        }
    }

    // Now empty S3 buckets, clean up will be done when the stack is deleted
    AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withRegion(Regions.getCurrentRegion().getName())
            .withCredentials(new InstanceProfileCredentialsProvider(true)).build();
    for (String s3BucketPhysicalId : s3BucketIds) {
        String s3BucketName = s3BucketPhysicalId;
        if(!amazonS3.doesBucketExistV2(s3BucketName)){
            break;
        }
        LOGGER.info("Empyting S3 bucket, " + s3BucketName);
        ObjectListing objectListing = amazonS3.listObjects(s3BucketName);
        while (true) {
            for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator
                    .hasNext(); ) {
                S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
                amazonS3.deleteObject(s3BucketName, summary.getKey());
            }
            if (objectListing.isTruncated()) {
                objectListing = amazonS3.listNextBatchOfObjects(objectListing);
            }
            else {
                break;
            }
        }
    }

    //Proceed with the regular stack deletion operation
    DeleteStackRequest deleteRequest = new DeleteStackRequest();
    deleteRequest.setStackName(stackName);
    amazonCloudFormation.deleteStack(deleteRequest);
    LOGGER.info("Stack deletion initiated");

    CFTStackStatus cftStackStatus = waitForCompletionAndGetStackStatus(amazonCloudFormation,
            rootStackId);
    LOGGER.info(
            "Stack deletion completed, the stack " + stackName + " completed with " + cftStackStatus);

    // Throw exception if failed
    if (!cftStackStatus.getStackStatus().equals(StackStatus.DELETE_COMPLETE.toString())) {
        throw new Exception(
                "deleteStack operation failed for stack " + stackName + " - " + cftStackStatus);
    }
}
 
Example #15
Source File: DeleteStackAction.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
/**
 * Creates AWS Cloud Formation Stack in sync mode using AWS Java SDK
 *
 * @param identity          Access key associated with your Amazon AWS or IAM account.
 *                          Example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
 * @param credential        Secret access key ID associated with your Amazon AWS or IAM account.
 * @param proxyHost         Optional - proxy server used to connect to Amazon API. If empty no proxy will be used.
 *                          Default: ""
 * @param proxyPort         Optional - proxy server port. You must either specify values for both proxyHost and
 *                          proxyPort inputs or leave them both empty.
 *                          Default: ""
 * @param proxyUsername     Optional - proxy server user name.
 *                          Default: ""
 * @param proxyPassword     Optional - proxy server password associated with the proxyUsername input value.
 *                          Default: ""
 * @param region            AWS region name
 *                          Example: "eu-central-1"
 * @param stackName         Stack name to delete
 *                          Example: "MyStack"
 * @return                  A map with strings as keys and strings as values that contains: outcome of the action, returnCode of the
 *                          operation, or failure message and the exception if there is one
 */
@Action(name = "Delete AWS Cloud Formation Stack",
        outputs = {
                @Output(Outputs.RETURN_CODE),
                @Output(Outputs.RETURN_RESULT),
                @Output(Outputs.EXCEPTION)
        },
        responses = {
                @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
                        matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
                        matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
        }
)
public Map<String, String> execute(
        @Param(value = IDENTITY,   required = true)  String identity,
        @Param(value = CREDENTIAL, required = true, encrypted = true)  String credential,
        @Param(value = REGION,     required = true)  String region,
        @Param(value = PROXY_HOST)                   String proxyHost,
        @Param(value = PROXY_PORT)                   String proxyPort,
        @Param(value = PROXY_USERNAME)               String proxyUsername,
        @Param(value = PROXY_PASSWORD)               String proxyPassword,
        @Param(value = CONNECT_TIMEOUT)              String connectTimeoutMs,
        @Param(value = EXECUTION_TIMEOUT)            String execTimeoutMs,
        @Param(value = STACK_NAME, required = true)  String stackName) {

    proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT);
    connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
    execTimeoutMs = defaultIfEmpty(execTimeoutMs, DefaultValues.EXEC_TIMEOUT);

    try {
        AmazonCloudFormation stackBuilder = CloudFormationClientBuilder.getCloudFormationClient(identity, credential, proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs, region);

        // Delete the stack
        DeleteStackRequest deleteRequest = new DeleteStackRequest()
                .withStackName(stackName);

        DeleteStackResult result = stackBuilder.deleteStack(deleteRequest);
        return OutputUtilities.getSuccessResultsMap(result.toString());
    } catch (Exception e) {
        return OutputUtilities.getFailureResultsMap(e);
    }
}
 
Example #16
Source File: AwsStackRequestHelper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public DeleteStackRequest createDeleteStackRequest(String cFStackName) {
    return new DeleteStackRequest()
            .withStackName(cFStackName);
}
 
Example #17
Source File: AmazonCloudFormationRetryClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public DeleteStackResult deleteStack(DeleteStackRequest request) {
    return retry.testWith2SecDelayMax15Times(() -> mapThrottlingError(() -> client.deleteStack(request)));
}