Java Code Examples for com.amazonaws.services.cloudformation.model.DescribeStacksResult#getStacks()

The following examples show how to use com.amazonaws.services.cloudformation.model.DescribeStacksResult#getStacks() . 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: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
private static Properties getCloudformationOutputs(AmazonCloudFormation cloudFormation, CreateStackResult stack) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stack.getStackId());
    final DescribeStacksResult describeStacksResult = cloudFormation
            .describeStacks(describeStacksRequest);

    Properties outputProps = new Properties();
    for (Stack st : describeStacksResult.getStacks()) {
        StringBuilder outputsStr = new StringBuilder("Infrastructure/Deployment outputs {\n");
        for (Output output : st.getOutputs()) {
            outputProps.setProperty(output.getOutputKey(), output.getOutputValue());
            outputsStr.append(output.getOutputKey()).append("=").append(output.getOutputValue()).append("\n");
        }
        //Log cfn outputs
        logger.info(outputsStr.toString() + "\n}");
    }
    return outputProps;
}
 
Example 3
Source File: CloudFormationFacade.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 5 votes vote down vote up
private Stack describeStack(String stackId) {
    DescribeStacksRequest request = new DescribeStacksRequest().withStackName(stackId);
    DescribeStacksResult result = cloudformation.describeStacks(request);

    List<Stack> stacks = result.getStacks();
    if (stacks.isEmpty()) {
        String message = String.format("Invalid stackId. No stack found for %s.", stackId);
        throw new RuntimeException(message);
    }
    return stacks.get(0);
}
 
Example 4
Source File: StackResourceUserTagsFactoryBean.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> createInstance() throws Exception {
	LinkedHashMap<String, String> userTags = new LinkedHashMap<>();
	DescribeStacksResult stacksResult = this.amazonCloudFormation
			.describeStacks(new DescribeStacksRequest()
					.withStackName(this.stackNameProvider.getStackName()));
	for (Stack stack : stacksResult.getStacks()) {
		for (Tag tag : stack.getTags()) {
			userTags.put(tag.getKey(), tag.getValue());
		}
	}
	return userTags;
}
 
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: TestStackInstanceIdService.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static Stack getStack(DescribeStacksResult describeStacksResult,
		String stackName) {
	for (Stack stack : describeStacksResult.getStacks()) {
		if (stack.getStackName().equals(stackName)) {
			return stack;
		}
	}

	throw new IllegalStateException(
			"No stack found with name '" + stackName + "' (available stacks: "
					+ allStackNames(describeStacksResult) + ")");
}
 
Example 7
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 8
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;
}