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

The following examples show how to use com.amazonaws.services.cloudformation.model.StackStatus. 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: CloudFormationClient.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
/**
 * Get outputs for the wrapper stack and all nested stacks
 *
 * @return Outputs for stack {@link #stackName}
 */

public Map<String, String> getStackOutput() throws Exception {

    String rootStackId = getStackInfo().stackId();
    LOGGER.info("rootStackId   =   " + rootStackId);
    Map<String, String> outputs = new HashMap<>();
    outputs.put("rootStackId", rootStackId);

    DescribeStacksResult describeStacksResult = amazonCloudFormation.describeStacks();
    for (Stack currentStack : describeStacksResult.getStacks()) {
        // Get the output details for the running stacks that got created
        // go through both root and nested stacks
        if (currentStack.getStackStatus().equals(StackStatus.CREATE_COMPLETE.toString())
                && (rootStackId.equals(currentStack.getRootId())
                || rootStackId.equals(currentStack.getStackId()))) {
            for (Output output : currentStack.getOutputs()) {
                LOGGER.info(output.getOutputKey() + "   =   " + output.getOutputValue());
                outputs.put(output.getOutputKey(), output.getOutputValue());
            }
        }
    }
    return outputs;
}
 
Example #2
Source File: CloudFormationUtils.java    From amazon-kinesis-connectors with Apache License 2.0 5 votes vote down vote up
private static StackStatus stackStatus(AmazonCloudFormation client, String stackName) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);
    // describeStacks (with stack name specified) will return list of size 1 if found
    // and throw AmazonServiceException if no stack with that name exists
    try {
        return StackStatus.fromValue(client.describeStacks(describeStacksRequest)
                .getStacks()
                .get(0)
                .getStackStatus());
    } catch (AmazonServiceException ase) {
        return null;
    }
}
 
Example #3
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 #4
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 4 votes vote down vote up
public CFTStackStatus waitForCompletionAndGetStackStatus(AmazonCloudFormation awsCloudFormation,
        String stackId) throws InterruptedException {

    int stackStatusPollingInterval = 60 * 1000;
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackId);

    Boolean done = false;
    String stackStatus = "UNKNOWN";
    String stackReason = "";

    System.out.print("Waiting");

    while (!done) {
        List<Stack> stacks = awsCloudFormation.describeStacks(describeStacksRequest).getStacks();
        if (stacks.isEmpty()) {
            done = true;
            stackStatus = StackStatus.DELETE_COMPLETE.toString();
            stackReason = "Stack has been deleted";
        }
        else {
            for (Stack stack : stacks) {
                if (stack.getStackStatus().equals(StackStatus.CREATE_COMPLETE.toString())
                        || stack.getStackStatus().equals(StackStatus.CREATE_FAILED.toString())
                        || stack.getStackStatus().equals(StackStatus.ROLLBACK_FAILED.toString())
                        || stack.getStackStatus().equals(StackStatus.ROLLBACK_COMPLETE.toString())
                        || stack.getStackStatus().equals(StackStatus.DELETE_COMPLETE.toString())
                        || stack.getStackStatus().equals(StackStatus.DELETE_FAILED.toString())) {
                    done = true;
                    stackStatus = stack.getStackStatus();
                    stackReason = stack.getStackStatusReason();
                }
            }
        }
        System.out.print(".");
        if (!done) {
            Thread.sleep(stackStatusPollingInterval);
        }
    }
    LOGGER.info("done");

    CFTStackStatus cftStackStatus = new CFTStackStatus(stackStatus, stackReason);
    return cftStackStatus;
}
 
Example #5
Source File: StackCreationWaiter.java    From testgrid with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean call() throws Exception {
    //Stack details
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(stackName);
    DescribeStacksResult describeStacksResult = cloudFormation.describeStacks(describeStacksRequest);
    final List<Stack> stacks = describeStacksResult.getStacks();
    if (stacks.size() > 1 || stacks.isEmpty()) {
        String stackNames = stacks.stream().map(Stack::getStackName).collect(Collectors.joining(", "));
        final String msg = "More than one stack found or stack list is empty for the stack name: " +
                stackName + ": " + stackNames;
        logger.error(msg);
        throw new IllegalStateException(msg);
    }

    Stack stack = stacks.get(0);
    StackStatus stackStatus = StackStatus.fromValue(stack.getStackStatus());

    // Event details of the stack
    DescribeStackEventsRequest describeStackEventsRequest = new DescribeStackEventsRequest()
            .withStackName(stackName);
    DescribeStackEventsResult describeStackEventsResult = cloudFormation.
            describeStackEvents(describeStackEventsRequest);

    //Print a log of the current state of the resources
    StringBuilder stringBuilder = new StringBuilder();
    final List<StackEvent> originalStackEvents = describeStackEventsResult.getStackEvents();
    final List<StackEvent> newStackEvents = new ArrayList<>(originalStackEvents);
    newStackEvents.removeAll(prevStackEvents);
    ListIterator<StackEvent> li = newStackEvents.listIterator(newStackEvents.size());
    while (li.hasPrevious()) {
        StackEvent stackEvent = li.previous();
        stringBuilder.append(StringUtil.concatStrings(
                "Status: ", stackEvent.getResourceStatus(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Resource Type: ", stackEvent.getResourceType(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Logical ID: ", stackEvent.getLogicalResourceId(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Status Reason: ", Optional.ofNullable(stackEvent.getResourceStatusReason()).orElse("-")));
        stringBuilder.append("\n");
    }
    logger.info(StringUtil.concatStrings("\n", stringBuilder.toString()));
    prevStackEvents = originalStackEvents;

    //Determine the steps to execute based on the status of the stack
    switch (stackStatus) {
    case CREATE_COMPLETE:
        return true;
    case CREATE_IN_PROGRESS:
        break;
    default:
        throw new TestGridInfrastructureException(StringUtil.concatStrings(
                "Stack creation transitioned to ", stackStatus.toString(), " state."));
    }
    return false;
}
 
Example #6
Source File: AwsIntegrationTestStackRule.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
private void waitForCompletion() throws InterruptedException {
	DescribeStacksRequest wait = new DescribeStacksRequest();
	wait.setStackName(this.stackName);
	Boolean completed = false;
	String stackStatus = "Unknown";
	String stackReason = "";

	while (!completed) {
		List<Stack> stacks = null;
		try {
			stacks = this.cloudFormation.describeStacks(wait).getStacks();
		}
		catch (Exception e) {
			logger.error("cloudFormation.describeStacks() exception", e);
		}
		if (CollectionUtils.isEmpty(stacks)) {
			completed = true;
			stackStatus = StackStatus.DELETE_COMPLETE.toString();
			stackReason = "Stack has been deleted";
		}
		else {
			for (Stack stack : stacks) {
				if (stack.getStackStatus().equals(StackStatus.CREATE_COMPLETE.toString()) ||
						stack.getStackStatus().equals(StackStatus.CREATE_FAILED.toString()) ||
						stack.getStackStatus().equals(StackStatus.ROLLBACK_FAILED.toString()) ||
						stack.getStackStatus().equals(StackStatus.DELETE_FAILED.toString())) {
					completed = true;
					stackStatus = stack.getStackStatus();
					stackReason = stack.getStackStatusReason();
				}
			}
		}

		// Not done yet so sleep for 2 seconds.
		if (!completed) {
			Thread.sleep(2000);
		}
		else {
			if (stackStatus.equals(StackStatus.CREATE_FAILED.toString())) {
				Assume.assumeTrue("The test AWS stack [" + this.stackName + "] cannot be created. Reason: " +
								stackReason, true);
			}
		}
	}
}