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

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

Introduction

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

Prototype

UpdateStackRequest

Source Link

Usage

From source file:br.com.ingenieux.mojo.cloudformation.PushStackMojo.java

License:Apache License

private UpdateStackResult updateStack() throws Exception {
    UpdateStackRequest req = new UpdateStackRequest().withStackName(stackName)
            .withCapabilities(Capability.CAPABILITY_IAM);

    if (null != this.destinationS3Uri) {
        req.withTemplateURL(generateExternalUrl(this.destinationS3Uri));
    } else {//w w w .j a  v a2 s  . c  o m
        req.withTemplateBody(templateBody);
    }

    req.withNotificationARNs(notificationArns);

    req.withParameters(parameters);
    req.withResourceTypes(resourceTypes);
    req.withTags(tags);

    try {
        return getService().updateStack(req);
    } catch (AmazonServiceException exc) {
        if ("No updates are to be performed.".equals(exc.getErrorMessage())) {
            return null;
        }

        throw exc;
    }
}

From source file:com.carrotgarden.maven.aws.cfn.CarrotCloudForm.java

License:BSD License

public Stack stackUpdate() throws Exception {

    final UpdateStackRequest request = new UpdateStackRequest();

    request.withStackName(name);/*from ww  w . j av a  2s  .c o m*/
    request.withParameters(paramList);
    request.withTemplateBody(template);

    amazonClient.updateStack(request);

    final Stack stack = waitForStackUpdate();

    return stack;

}

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 ww.  ja  v  a2s. co m*/
    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.deploymentio.cfnstacker.CloudFormationClient.java

License:Apache License

/**
 * Initiate updates to an existing stack with the given options and template
 * /*from w ww. ja  v  a2  s  .c  o  m*/
 * @param templateBody updated ClouadFormation JSON template
 * @return ID of the updated stack
 */
public String updateStack(JsonNode templateBody) throws Exception {
    return client.updateStack(new UpdateStackRequest().withStackName(config.getName())
            .withTemplateURL(uploadCfnTemplateToS3(config.getName(), "update", templateBody))
            .withCapabilities("CAPABILITY_IAM")
            .withParameters(templateParameters.getApplicableParameters(templateBody))).getStackId();
}

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 {/*from ww  w  .j a  v a2 s  .co m*/
        // 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: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 {/*  w  w w.ja v  a2 s.co 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:com.nike.cerberus.service.CloudFormationService.java

License:Apache License

/**
 * Updates an existing stack by name./*  ww w .  ja  v  a  2  s .c om*/
 *
 * @param stackId Stack ID.
 * @param parameters Input parameters.
 * @param templatePath Path to the JSON template of the stack.
 */
public void updateStack(final String stackId, final Map<String, String> parameters, final String templatePath,
        final boolean iamCapabilities) {
    final UpdateStackRequest request = new UpdateStackRequest().withStackName(stackId)
            .withParameters(convertParameters(parameters));

    if (StringUtils.isNotBlank(templatePath)) {
        request.withTemplateBody(getTemplateText(templatePath));
    } else {
        request.withUsePreviousTemplate(true);
    }

    if (iamCapabilities) {
        request.getCapabilities().add("CAPABILITY_IAM");
    }

    cloudFormationClient.updateStack(request);
}

From source file:de.taimos.pipeline.aws.cloudformation.CloudFormationStack.java

License:Apache License

public void update(String templateBody, String templateUrl, Collection<Parameter> params, Collection<Tag> tags,
        long pollIntervallMillis, String roleArn) throws ExecutionException {
    try {// w  ww .  j  av  a  2 s  . co  m
        UpdateStackRequest req = new UpdateStackRequest();
        req.withStackName(this.stack).withCapabilities(Capability.CAPABILITY_IAM,
                Capability.CAPABILITY_NAMED_IAM);

        if (templateBody != null && !templateBody.isEmpty()) {
            req.setTemplateBody(templateBody);
        } else if (templateUrl != null && !templateUrl.isEmpty()) {
            req.setTemplateURL(templateUrl);
        } else {
            req.setUsePreviousTemplate(true);
        }

        req.withParameters(params).withTags(tags).withRoleARN(roleArn);

        this.client.updateStack(req);

        new EventPrinter(this.client, this.listener).waitAndPrintStackEvents(this.stack,
                this.client.waiters().stackUpdateComplete(), pollIntervallMillis);

        this.listener.getLogger().format("Updated CloudFormation stack %s %n", this.stack);

    } catch (AmazonCloudFormationException e) {
        if (e.getMessage().contains("No updates are to be performed")) {
            this.listener.getLogger().format("No updates were needed for CloudFormation stack %s %n",
                    this.stack);
            return;
        }
        this.listener.getLogger().format("Failed to update CloudFormation stack %s %n", this.stack);
        throw e;
    }
}

From source file:jetbrains.buildServer.runner.cloudformation.AWSClient.java

License:Apache License

/**
 * Uploads application revision archive to S3 bucket named s3BucketName with
 * the provided key and bundle type.//from w  ww  .  jav  a2s  .  co  m
 * <p>
 * For performing this operation target AWSClient must have corresponding S3
 * permissions.
 *
 * @param s3BucketName
 *            valid S3 bucket name
 * @param s3ObjectKey
 *            valid S3 object key
 */
public void initiateCFN(@NotNull String stackName, @NotNull String region, @NotNull String s3BucketName,
        @NotNull String s3ObjectKey, @NotNull String cfnAction, @NotNull String onFailure) {
    try {
        String templateURL;
        Region reg = Region.getRegion(Regions.fromName(region));
        myCloudFormationClient.setRegion(reg);
        templateURL = getTemplateUrl(reg, s3BucketName, s3ObjectKey);
        System.out.println("The template url is " + templateURL);

        if (cfnAction.equalsIgnoreCase("Create")) {
            System.out.println("The CFN action is " + cfnAction);
            myListener.createStackStarted(stackName, region, s3BucketName, s3ObjectKey, cfnAction);
            CreateStackRequest createRequest = new CreateStackRequest();
            createRequest.setStackName(stackName);
            if (!onFailure.equalsIgnoreCase("null"))
                createRequest.setOnFailure(onFailure);
            createRequest.setTemplateURL(templateURL);
            myCloudFormationClient.createStack(createRequest);
            waitForCompletion(myCloudFormationClient, stackName);

        } else if (cfnAction.equalsIgnoreCase("Delete")) {
            myListener.deleteStarted(stackName, region);
            DeleteStackRequest deleteStackRequest = new DeleteStackRequest();
            deleteStackRequest.setStackName(stackName);
            myCloudFormationClient.deleteStack(deleteStackRequest);
            waitForDelete(myCloudFormationClient, stackName);

        } else if (cfnAction.equalsIgnoreCase("Validate")) {
            myListener.validateStarted(stackName);
            ValidateTemplateRequest validatetempRequest = new ValidateTemplateRequest();
            validatetempRequest.setTemplateURL(templateURL);
            myListener.validateFinished(
                    myCloudFormationClient.validateTemplate(validatetempRequest).getParameters().toString());

        } else if (cfnAction.equalsIgnoreCase("Update")) {
            myListener.updateInProgress(stackName);
            UpdateStackRequest updateStackRequest = new UpdateStackRequest();
            updateStackRequest.setStackName(stackName);
            updateStackRequest.setTemplateURL(templateURL);
            myCloudFormationClient.updateStack(updateStackRequest);
            waitForCompletion(myCloudFormationClient, stackName);
        }
    } catch (Throwable t) {
        processFailure(t);
    }
}

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 w  ww  .j ava2 s .  co  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());
}