Example usage for com.amazonaws.services.cloudformation.model StackResource getLogicalResourceId

List of usage examples for com.amazonaws.services.cloudformation.model StackResource getLogicalResourceId

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudformation.model StackResource getLogicalResourceId.

Prototype


public String getLogicalResourceId() 

Source Link

Document

The logical name of the resource specified in the template.

Usage

From source file:CloudFormation.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from www.  j  a v  a  2 s  . co 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:CloudFormationSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*//from   w  w  w  .  j a v a2 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.deploymentio.cfnstacker.Operation.java

License:Apache License

/**
 * Validates the stack's template for valid JSON, merge conflicts during JSON
 * fragment merges, for required template parameters, and then executes the
 * stack operation.//w  w  w  .j  av  a 2  s  .co  m
 * 
 * @param config the CLI and other options
 * @param action description of the action we are performing
 * @return <code>true</code> if everything went well
 */
public boolean validateAndExecuteStack(StackConfig config, String action, boolean validateOnly)
        throws Exception {

    JsonFormatter formatter = new JsonFormatter();
    String stackName = config.getName();
    JsonNode templateBody = null;
    boolean validated = false;

    try {

        if (!"create".equals(action)) {
            // print the existing values
            formatter.writeFormattedJSONString(client.getTemplateValue(stackName),
                    new File(".template-existing.json"));
            for (StackResource res : client.getStackResources(stackName)) {
                String subStackName = res.getLogicalResourceId();
                formatter.writeFormattedJSONString(client.getTemplateValue(res.getPhysicalResourceId()),
                        new File(".template-existing-" + subStackName + ".json"));
            }
        }

        // validate any sub-stacks
        Map<String, String> subStackTemplateUrls = new HashMap<>();
        boolean allSubStacksValid = true;
        for (SubStackConfig subStackConfig : config.getSubStacks()) {
            String subStackName = subStackConfig.getName();
            JsonNode subStackBody = jsonNodeHelper.getSubStackMergedJson(subStackConfig);
            String templateUrl = client.uploadCfnTemplateToS3(config.getName(), subStackName, subStackBody);
            if (client.validateSubStackTemplate(templateUrl)) {
                logger.info("SubStack template with name '" + subStackName + "' is valid");
                subStackTemplateUrls.put(subStackName, templateUrl);
                formatter.writeFormattedJSONString(subStackBody,
                        new File(".template-new-" + subStackName + ".json"));
            } else {
                logger.error("SubStack template with name '" + subStackName + "' is NOT valid");
                allSubStacksValid = false;
                break;
            }
        }

        // validate the main stack
        if (allSubStacksValid) {

            templateBody = jsonNodeHelper.getStackMergedJson(subStackTemplateUrls);
            validated = validateTemplateBody(templateBody);

            if (!validated) {
                logger.error("Stack template with name '" + config.getName() + "' is NOT valid");
            } else {
                logger.info("Stack template with name '" + config.getName() + "' is valid");
            }
        }

    } catch (Exception e) {
        logger.error("Failure to validate stack template with name '" + stackName + "'", e);
    }

    if (validated && !validateOnly) {

        // execute the code
        logger.info("Attempting to " + action + " stack with name '" + stackName + "'");
        String stackId = execute(templateBody);

        // track its progress
        tracker.track(client, stackName, stackId, 30).waitUntilCompletion();

        if (!"delete".equals(action)) {
            client.printStackOutputs(client.findStack(stackName));
        }
    }

    if (validated && validateOnly) {
        formatter.writeFormattedJSONString(templateBody, new File(".template-new.json"));
    }

    return validated;
}

From source file:org.terracotta.TerracottaCloudFormationSample.java

License:Open Source License

@org.junit.BeforeClass
public static void createStack() throws Exception {

    /*//from   w  w  w. j  a  v a  2  s.  c om
    * 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
    */
    amazonCloudFormationClient = new AmazonCloudFormationClient(new PropertiesCredentials(
            TerracottaCloudFormationSample.class.getResourceAsStream("/AwsCredentials.properties")));

    System.out.println("================================");
    System.out.println("Terracotta CloudFormation Sample");
    System.out.println("================================\n");

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(convertStreamToString(
                TerracottaCloudFormationSample.class.getResourceAsStream("/TerracottaServerArray.template")));

        Parameter parameter = new Parameter();
        parameter.setParameterKey("KeyName");
        parameter.setParameterValue(keyChainName);
        List parameters = new ArrayList();
        parameters.add(parameter);
        createRequest.setParameters(parameters);
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        amazonCloudFormationClient.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(amazonCloudFormationClient, stackName));

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

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : amazonCloudFormationClient
                    .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 : amazonCloudFormationClient
                .describeStackResources(logicalNameResourceRequest).getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        //deleteStack

    } 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:org.terracotta.TerracottaCloudFormationSample.java

License:Open Source License

@org.junit.Test
public void testStackCreated() {
    // 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 : amazonCloudFormationClient.describeStackResources(logicalNameResourceRequest)
            .getStackResources()) {//from w w w  .  j av  a 2s .com
        System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                resource.getLogicalResourceId(), resource.getPhysicalResourceId());
    }

}