Example usage for com.amazonaws.services.cloudformation AmazonCloudFormation describeStacks

List of usage examples for com.amazonaws.services.cloudformation AmazonCloudFormation describeStacks

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudformation AmazonCloudFormation describeStacks.

Prototype

DescribeStacksResult describeStacks(DescribeStacksRequest describeStacksRequest);

Source Link

Document

Returns the description for the specified stack; if no stack name was specified, then it returns the description for all the stacks created.

Usage

From source file:CloudFormation.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*  w  w  w  .  j  a v  a 2s  .  c  o  m*/
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     * Important: Be sure to fill in your AWS access credentials in the
     *            AwsCredentials.properties file before you try to run this
     *            sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonCloudFormation stackbuilder = new AmazonCloudFormationClient(
            new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    stackbuilder.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with AWS CloudFormation");
    System.out.println("===========================================\n");

    String stackName = "CloudFormationSampleStack";
    String logicalResourceName = "SampleNotificationTopic";

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(
                convertStreamToString(CloudFormation.class.getResourceAsStream("CloudFormation.template")));
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        stackbuilder.createStack(createRequest);

        // Wait for stack to be created
        // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

        // Show all the stacks for this account along with the resources for each stack
        for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
            System.out.println(
                    "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest)
                    .getStackResources()) {
                System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                        resource.getLogicalResourceId(), resource.getPhysicalResourceId());
            }
        }

        // Lookup a resource by its logical name
        DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
        logicalNameResourceRequest.setStackName(stackName);
        logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
        System.out.format("Looking up resource name %1$s from stack %2$s\n",
                logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
        for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest)
                .getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        // Delete the stack
        DeleteStackRequest deleteRequest = new DeleteStackRequest();
        deleteRequest.setStackName(stackName);
        System.out.println("Deleting the stack called " + deleteRequest.getStackName() + ".");
        stackbuilder.deleteStack(deleteRequest);

        // Wait for stack to be deleted
        // Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS CloudFormation, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS CloudFormation, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:CloudFormation.java

License:Open Source License

public static String waitForCompletion(AmazonCloudFormation stackbuilder, String stackName) throws Exception {

    DescribeStacksRequest wait = new DescribeStacksRequest();
    wait.setStackName(stackName);/*from  ww  w .ja  va2 s . c o m*/
    Boolean completed = false;
    String stackStatus = "Unknown";
    String stackReason = "";

    System.out.print("Waiting");

    while (!completed) {
        List<Stack> stacks = stackbuilder.describeStacks(wait).getStacks();
        if (stacks.isEmpty()) {
            completed = true;
            stackStatus = "NO_SUCH_STACK";
            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();
                }
            }
        }

        // Show we are waiting
        System.out.print(".");

        // Not done yet so sleep for 10 seconds.
        if (!completed)
            Thread.sleep(10000);
    }

    // Show we are done
    System.out.print("done\n");

    return stackStatus + " (" + stackReason + ")";
}

From source file:CloudFormationSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from   w w  w.j  a v a  2 s.c o m*/
    * Important: Be sure to fill in your AWS access credentials in the
    *            AwsCredentials.properties file before you try to run this
    *            sample.
    * http://aws.amazon.com/security-credentials
    */
    AmazonCloudFormation stackbuilder = new AmazonCloudFormationClient(new PropertiesCredentials(
            CloudFormationSample.class.getResourceAsStream("AwsCredentials.properties")));

    System.out.println("===========================================");
    System.out.println("Getting Started with AWS CloudFormation");
    System.out.println("===========================================\n");

    String stackName = "CloudFormationSampleStack";
    String logicalResourceName = "SampleNotificationTopic";

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(convertStreamToString(
                CloudFormationSample.class.getResourceAsStream("CloudFormationSample.template")));
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        stackbuilder.createStack(createRequest);

        // Wait for stack to be created
        // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

        // Show all the stacks for this account along with the resources for each stack
        for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
            System.out.println(
                    "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest)
                    .getStackResources()) {
                System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                        resource.getLogicalResourceId(), resource.getPhysicalResourceId());
            }
        }

        // Lookup a resource by its logical name
        DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
        logicalNameResourceRequest.setStackName(stackName);
        logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
        System.out.format("Looking up resource name %1$s from stack %2$s\n",
                logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
        for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest)
                .getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        // Delete the stack
        DeleteStackRequest deleteRequest = new DeleteStackRequest();
        deleteRequest.setStackName(stackName);
        System.out.println("Deleting the stack called " + deleteRequest.getStackName() + ".");
        stackbuilder.deleteStack(deleteRequest);

        // Wait for stack to be deleted
        // Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS CloudFormation, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS CloudFormation, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.CfStackDetail.java

License:Open Source License

@Override
public String retrieveDetails(ResourceDetailRequest detailRequest) {

    String response = null;//from w w  w.j a v  a  2  s.  c  o  m

    try {

        AmazonCloudFormation client = new AmazonCloudFormationClient(credentials);
        client.setRegion(Region.getRegion(Regions.fromName(detailRequest.getRegion())));

        DescribeStacksRequest request = new DescribeStacksRequest();
        request.setStackName(detailRequest.getResourceName());

        DescribeStacksResult result = client.describeStacks(request);
        buildUI(result);

    } catch (IllegalArgumentException | AmazonClientException e) {
        response = e.getMessage();
        LOGGER.log(Level.WARNING, "Problem retrieving CloudFormation details from AWS", e);
    }

    return response;
}

From source file:com.kinesisboard.amazonaws.utils.CloudFormationUtils.java

License:Open Source License

private static boolean stackExists(AmazonCloudFormation client, String stackName) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);
    try {/*from  ww w.j a  va 2s.  c o m*/
        client.describeStacks(describeStacksRequest);
        return true;
    } catch (AmazonServiceException e) {
        return false;
    }
}

From source file:com.kinesisboard.amazonaws.utils.CloudFormationUtils.java

License:Open Source License

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 {/* w w  w . ja  v a2s .c  om*/
        return StackStatus
                .fromValue(client.describeStacks(describeStacksRequest).getStacks().get(0).getStackStatus());
    } catch (AmazonServiceException ase) {
        return null;
    }
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.ops.DeployCloudFormationAtomicOperation.java

License:Apache License

private String updateStack(AmazonCloudFormation amazonCloudFormation, String template,
        List<Parameter> parameters) {
    Task task = TaskRepository.threadLocalTask.get();
    task.updateStatus(BASE_PHASE, "CloudFormation Stack exists. Updating it");
    UpdateStackRequest updateStackRequest = new UpdateStackRequest().withStackName(description.getStackName())
            .withParameters(parameters).withTemplateBody(template);
    task.updateStatus(BASE_PHASE, "Uploading CloudFormation Stack");
    try {//from   w  w w . jav  a  2 s. c  o m
        UpdateStackResult updateStackResult = amazonCloudFormation.updateStack(updateStackRequest);
        return updateStackResult.getStackId();
    } catch (AmazonCloudFormationException e) {
        // No changes on the stack, ignore failure
        return amazonCloudFormation
                .describeStacks(new DescribeStacksRequest().withStackName(description.getStackName()))
                .getStacks().stream().findFirst()
                .orElseThrow(() -> new IllegalArgumentException(
                        "No CloudFormation Stack found with stack name " + description.getStackName()))
                .getStackId();
    }

}

From source file:doug.iotdemo.common.AmazonUtils.java

License:Open Source License

public static String getStackOutput(String outputKey) {
    AmazonCloudFormation cf = new AmazonCloudFormationClient();
    DescribeStacksRequest request = new DescribeStacksRequest().withStackName(stackName);
    for (Stack stack : cf.describeStacks(request).getStacks()) {
        for (Output output : stack.getOutputs()) {
            if (outputKey.equals(output.getOutputKey())) {
                return output.getOutputValue();
            }/*from   w w  w  . j  a va2 s.  c  o  m*/
        }
    }
    return null;
}

From source file:io.konig.maven.CreateCloudFormationStackAction.java

License:Apache License

private List<Output> getOutputForRequest(String stackName, AmazonCloudFormation client)
        throws InterruptedException, StackCreationException {
    int tried = 0;
    String maxTime = System.getProperty("stackMaxTime");
    while (tried < (maxTime == null ? 1800 : Integer.parseInt(maxTime))) {
        DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
        describeStacksRequest.withStackName(stackName);
        Stack resultStack = client.describeStacks(describeStacksRequest).getStacks().get(0);
        StackStatus stackStatus = StackStatus.valueOf(resultStack.getStackStatus());
        if (("CREATE_COMPLETE").equals(stackStatus.toString())) {
            return resultStack.getOutputs();
        } else if (stackStatus.toString().endsWith("IN_PROGRESS")) {
            Thread.sleep(10000);/*  w  w w. ja  v a 2s  .c om*/
        } else {
            DescribeStackEventsRequest describeStackEventsRequest = new DescribeStackEventsRequest();
            describeStackEventsRequest.withStackName(stackName);
            List<StackEvent> stackEvents = client.describeStackEvents(describeStackEventsRequest)
                    .getStackEvents();
            List<StackEvent> errorEvents = new ArrayList<StackEvent>();
            for (StackEvent stackEvent : stackEvents) {
                if (stackEvent.getResourceStatus().equals("CREATE_FAILED")) {
                    errorEvents.add(stackEvent);
                }
            }
            throw new StackCreationException(errorEvents.toString());
        }
        tried++;
    }
    throw new RuntimeException("stack creation/deletion timed out");
}

From source file:jp.classmethod.aws.gradle.cloudformation.AmazonCloudFormationCreateChangeSetTask.java

License:Apache License

@TaskAction
public void createChangeSet() throws InterruptedException, IOException {
    // to enable conventionMappings feature
    String stackName = getStackName();
    List<String> stableStatuses = getStableStatuses();

    if (stackName == null) {
        throw new GradleException("stackName is not specified");
    }/*from   w  w  w.j  a  v a  2s  .  c o m*/

    AmazonCloudFormationPluginExtension ext = getProject().getExtensions()
            .getByType(AmazonCloudFormationPluginExtension.class);
    AmazonCloudFormation cfn = ext.getClient();

    DescribeStacksResult describeStackResult = cfn
            .describeStacks(new DescribeStacksRequest().withStackName(stackName));
    Stack stack = describeStackResult.getStacks().get(0);
    if (stableStatuses.contains(stack.getStackStatus())) {
        createChangeSet(cfn);
    } else {
        throw new GradleException("invalid status for create change set: " + stack.getStackStatus());
    }
}