Example usage for com.amazonaws.services.cloudformation.model UpdateStackRequest setCapabilities

List of usage examples for com.amazonaws.services.cloudformation.model UpdateStackRequest setCapabilities

Introduction

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

Prototype


public void setCapabilities(java.util.Collection<String> capabilities) 

Source Link

Document

In some cases, you must explicitly acknowledge that your stack template contains certain capabilities in order for AWS CloudFormation to update the stack.

Usage

From source file:com.cleanenergyexperts.aws.cf.CloudFormationMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    getLog().info("Bucket Name: " + bucketName);
    //getLog().info("Cloud Formation Stack Name: " + stackName);

    if (artifactFile == null || !artifactFile.isFile()) {
        throw new MojoExecutionException("Cannot find artifact file to upload");
    }/*from  w w w.  j av  a2s .  c  om*/
    String artifactKey = artifactFile.getName();
    getLog().info("Artifact Name: " + artifactKey);

    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonCloudFormationClient cfClient = new AmazonCloudFormationClient(awsCredentials);
    cfClient.setEndpoint(getCloudFormationEndPoint());
    AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);

    // Upload Artifact to S3
    try {
        getLog().info("Uploading artifact to S3...");
        s3Client.putObject(bucketName, artifactKey, artifactFile);
    } catch (AmazonServiceException e) {
        throw new MojoExecutionException("[SERVICE] Could Not Upload File to S3", e);
    } catch (AmazonClientException e) {
        throw new MojoExecutionException("[CLIENT] Could Not Upload File to S3", e);
    }

    // Update each stack with the new artifact file
    for (String stackName : stackNames) {
        getLog().info("Cloud Formation Stack Name: " + stackName);
        String templateBody = getTemplateBody(cfClient, stackName);
        Stack stack = getStack(cfClient, stackName);

        // If passed additional parameters, update them
        List<Parameter> parameters = stack.getParameters();
        if (stackParameters != null && !stackParameters.isEmpty()) {
            List<Parameter> tmpParams = new ArrayList<Parameter>();

            // Add Existing Parameters we haven't locally overwritten
            for (Parameter oldParam : parameters) {
                String oldKey = oldParam.getParameterKey();
                if (!stackParameters.containsKey(oldKey)) {
                    tmpParams.add(oldParam);
                }
            }

            // Add Overwrite parameters
            for (String key : stackParameters.keySet()) {
                Parameter newParam = new Parameter();
                newParam.setParameterKey(key);
                newParam.setParameterValue(stackParameters.get(key));
                tmpParams.add(newParam);
            }
            parameters = tmpParams;
        }

        // Update the Stack
        UpdateStackRequest updateStackRequest = new UpdateStackRequest();
        updateStackRequest.setStackName(stackName);
        updateStackRequest.setTemplateBody(templateBody);
        updateStackRequest.setParameters(parameters);
        updateStackRequest.setCapabilities(stack.getCapabilities());
        try {
            getLog().info("Updating Cloud Formation Stack...");
            cfClient.updateStack(updateStackRequest);
        } catch (AmazonServiceException e) {
            throw new MojoExecutionException("[SERVICE] Could Not Update Cloud Formation Stack", e);
        } catch (AmazonClientException e) {
            throw new MojoExecutionException("[CLIENT] Could Not Update Cloud Formation Stack", e);
        }
        getLog().info("Cloud Formation Stack " + stackName + "is now updating...");
    }

    getLog().info("All stacks have been updated. Complete.");
}

From source file:com.mweagle.tereus.commands.UpdateCommand.java

License:Open Source License

protected void updateStack(UpdateInput updateInput, String transformedTemplate, String stackTargetName)
        throws UnsupportedEncodingException {
    if (updateInput.dryRun) {
        updateInput.logger.info("Dry run requested (-n/--noop). Stack update bypassed.");
    } else {/* ww  w.j a v  a2s. c om*/
        // Fetch the stack parameters
        final DescribeStacksRequest stackRequest = new DescribeStacksRequest().withStackName(stackTargetName);
        final AmazonCloudFormationAsyncClient awsClient = new AmazonCloudFormationAsyncClient(
                updateInput.awsCredentials);
        awsClient.setRegion(updateInput.awsRegion);
        final DescribeStacksResult result = awsClient.describeStacks(stackRequest);
        final Stack existantStack = result.getStacks().get(0);

        final Optional<Parameter> s3Bucket = findNamedParameter(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME,
                existantStack.getParameters());

        Preconditions.checkArgument(s3Bucket.isPresent(),
                "Failed to determine S3 BucketName from existant template via parameter name: "
                        + CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME);

        // Super, now put the new content to S3, update the parameter list
        // to include the new URL, and submit the updated stack.
        final byte[] templateBytes = transformedTemplate.getBytes("UTF-8");
        final InputStream is = new ByteArrayInputStream(templateBytes);
        final String templateDigest = DigestUtils.sha256Hex(templateBytes);
        final String keyName = String.format("%s-tereus.cf.template", templateDigest);

        try (S3Resource resource = new S3Resource(s3Bucket.get().getParameterValue(), keyName, is,
                Optional.of(Long.valueOf(templateBytes.length)))) {
            // Upload the template
            resource.upload();

            // Go ahead and create the stack.
            final UpdateStackRequest request = new UpdateStackRequest().withStackName(stackTargetName);
            request.setTemplateURL(resource.getResourceURL().get());
            request.setParameters(existantStack.getParameters());
            request.setCapabilities(Arrays.asList("CAPABILITY_IAM"));

            updateInput.logger.debug("Updating stack: {}", stackTargetName);
            final Optional<DescribeStacksResult> updateResult = new CloudFormation().updateStack(request,
                    updateInput.awsRegion, updateInput.logger);

            // If everything worked out, then release the template
            // URL s.t. subsequent ASG instantiated instances have access
            // to the template content
            if (updateResult.isPresent()) {
                updateInput.logger.info("Stack successfully updated");
                updateInput.logger.info(updateResult.get().toString());
                resource.setReleased(true);
            }
        }
    }
}

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

License:Apache License

private void updateStack(AmazonCloudFormation cfn) throws IOException {
    // to enable conventionMappings feature
    String stackName = getStackName();
    String cfnTemplateUrl = getCfnTemplateUrl();
    File cfnTemplateFile = getCfnTemplateFile();
    List<Parameter> cfnStackParams = getCfnStackParams();
    List<Tag> cfnStackTags = getCfnStackTags();
    String cfnStackPolicyUrl = getCfnStackPolicyUrl();
    File cfnStackPolicyFile = getCfnStackPolicyFile();

    getLogger().info("Update stack: {}", stackName);
    UpdateStackRequest req = new UpdateStackRequest().withStackName(stackName).withParameters(cfnStackParams)
            .withTags(cfnStackTags);//from ww w.ja  v  a 2s  .c o  m

    // If template URL is specified, then use it
    if (Strings.isNullOrEmpty(cfnTemplateUrl) == false) {
        req.setTemplateURL(cfnTemplateUrl);
        getLogger().info("Using template url: {}", cfnTemplateUrl);
        // Else, use the template file body
    } else {
        req.setTemplateBody(FileUtils.readFileToString(cfnTemplateFile));
        getLogger().info("Using template file: {}", "$cfnTemplateFile.canonicalPath");
    }
    if (isCapabilityIam()) {
        Capability selectedCapability = (getUseCapabilityIam() == null) ? Capability.CAPABILITY_IAM
                : getUseCapabilityIam();
        getLogger().info("Using IAM capability: " + selectedCapability);
        req.setCapabilities(Arrays.asList(selectedCapability.toString()));
    }

    // If stack policy is specified, then use it
    if (Strings.isNullOrEmpty(cfnStackPolicyUrl) == false) {
        req.setStackPolicyURL(cfnStackPolicyUrl);
        // Else, use the stack policy file body if present
    } else if (cfnStackPolicyFile != null) {
        req.setStackPolicyBody(FileUtils.readFileToString(cfnStackPolicyFile));
    }

    UpdateStackResult updateStackResult = cfn.updateStack(req);
    getLogger().info("Update requested: {}", updateStackResult.getStackId());
}

From source file:org.xmlsh.aws.cfnUpdateStack.java

License:BSD License

private int updateStack(List<XValue> args, Options opts)
        throws IOException, XMLStreamException, SaxonApiException, CoreException {

    OutputPort stdout = getStdout();/*from w  w w.j  a v a 2 s.  c o  m*/
    mWriter = new SafeXMLStreamWriter(stdout.asXMLStreamWriter(getSerializeOpts()));

    startDocument();
    startElement(getName());

    UpdateStackRequest request = new UpdateStackRequest();

    // "capability:+,disable-rollback,notification-arn:+,name:,template:,timeout:,tag:+");

    if (opts.hasOpt("capability"))
        request.setCapabilities(Util.toStringList(opts.getOptValues("capability")));

    request.setStackName(opts.getOptStringRequired("name"));

    if (opts.hasOpt("template-file"))
        request.setTemplateBody(Util.readString(mShell.getFile(opts.getOptValue("template-file")),
                getSerializeOpts().getInput_text_encoding()));
    else
        request.setTemplateURL(opts.getOptStringRequired("template-url"));

    request.setParameters(getParameters(args));

    traceCall("updateStack");

    UpdateStackResult result = getAWSClient().updateStack(request);

    writeStackResult(result);

    endElement();
    endDocument();
    closeWriter();

    stdout.writeSequenceTerminator(getSerializeOpts());

    return 0;

}

From source file:org.xmlsh.aws.gradle.cloudformation.AmazonCloudFormationMigrateStackTask.java

License:BSD License

private void updateStack(AmazonCloudFormation cfn) {
    // to enable conventionMappings feature
    String stackName = getStackName();
    List<Parameter> cfnStackParams = getCfnStackParams();

    getLogger().info("update stack: {}", stackName);
    UpdateStackRequest req = new UpdateStackRequest().withStackName(stackName).withParameters(cfnStackParams)
            .withUsePreviousTemplate(isUsePreviousTemplate());
    if (getTemplateBody() != null)
        req.setTemplateBody(getTemplateBody());

    if (isCapabilityIam()) {
        req.setCapabilities(Arrays.asList(Capability.CAPABILITY_IAM.toString()));
    }/*from   w  w w  .j a  v a 2  s.c  o  m*/
    UpdateStackResult updateStackResult = cfn.updateStack(req);
    getLogger().info("update requested: {}", updateStackResult.getStackId());

}

From source file:org.xmlsh.aws.gradle.cloudformation.AmazonCloudFormationUpdateStackTask.java

License:BSD License

private void updateStack(AmazonCloudFormation cfn) {
    // to enable conventionMappings feature
    String stackName = getStackName();
    List<Parameter> cfnStackParams = getCfnStackParams();

    getLogger().info("update stack: {}", stackName);
    UpdateStackRequest req = new UpdateStackRequest().withStackName(stackName).withParameters(cfnStackParams)
            .withUsePreviousTemplate(isUsePreviousTemplate());
    if (getTemplateBody() != null)
        req.setTemplateBody(getTemplateBody());

    if (isCapabilityIam()) {
        req.setCapabilities(Arrays.asList(Capability.CAPABILITY_IAM.toString()));
    }/*from w w  w.j av a  2 s .  c o  m*/
    UpdateStackResult updateStackResult = cfn.updateStack(req);
    getLogger().info("update requested: {}", updateStackResult.getStackId());
}