List of usage examples for com.amazonaws.services.cloudformation AmazonCloudFormationClient AmazonCloudFormationClient
AmazonCloudFormationClient(AwsSyncClientParams clientParams)
From source file:CloudFormation.java
License:Open Source License
public static void main(String[] args) throws Exception { /*//from w w w . j av a 2 s . com * 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 { /*// w w w . ja va 2s .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.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 www . j a v a 2 s. 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.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.CfStackDetail.java
License:Open Source License
@Override public String retrieveDetails(ResourceDetailRequest detailRequest) { String response = null;/*from ww w . j av a2s . com*/ 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.mweagle.tereus.commands.CreateCommand.java
License:Open Source License
protected void createStack(Optional<String> stackName, TereusInput tereusInput, JsonElement templateData, boolean logTemplate) throws UnsupportedEncodingException { if (tereusInput.dryRun) { tereusInput.logger.info("Dry run requested (-n/--noop). Stack creation bypassed."); if (logTemplate) { final String formattedTemplate = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping() .create().toJson(templateData); tereusInput.logger.info("Stack Template:\n {}", formattedTemplate); }/*from w w w . ja v a 2 s . c o m*/ } else { final String bucketName = tereusInput.params.get(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME).toString(); // Upload the template final String templateContent = new GsonBuilder().create().toJson(templateData); final byte[] templateBytes = templateContent.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(bucketName, keyName, is, Optional.of(Long.valueOf(templateBytes.length)))) { resource.upload(); final EstimateTemplateCostRequest costRequest = new EstimateTemplateCostRequest(); costRequest.setParameters(toParameterList(tereusInput.params)); costRequest.setTemplateURL(resource.getResourceURL().get()); final AmazonCloudFormationClient awsClient = new AmazonCloudFormationClient( tereusInput.awsCredentials); awsClient.setRegion(tereusInput.awsRegion); final EstimateTemplateCostResult costResult = awsClient.estimateTemplateCost(costRequest); tereusInput.logger.info("Cost Estimator: {}", costResult.getUrl()); // Go ahead and create the stack. final String defaultTemplateName = String.format("Tereus-%s", System.currentTimeMillis()); final CreateStackRequest request = new CreateStackRequest() .withStackName(stackName.orElse(defaultTemplateName)) .withTemplateURL(resource.getResourceURL().get()) .withParameters(toParameterList(tereusInput.params)).withTags(toTagList(tereusInput.tags)) .withCapabilities("CAPABILITY_IAM"); tereusInput.logger.debug("Creating stack: {}", stackName); tereusInput.logger.debug("Stack params: {}", request.getParameters()); tereusInput.logger.debug("Stack tags: {}", request.getTags()); final Optional<DescribeStacksResult> result = new CloudFormation().createStack(request, tereusInput.awsRegion, tereusInput.logger); if (result.isPresent()) { tereusInput.logger.info("Stack successfully created"); tereusInput.logger.info(result.get().toString()); resource.setReleased(true); } } } }
From source file:com.mweagle.tereus.commands.CreateCommand.java
License:Open Source License
protected void validateTemplate(TereusInput tereusInput, String parameterizedTemplate) throws UnsupportedEncodingException { if (tereusInput.dryRun) { tereusInput.logger.info("Dry run requested (-n/--noop). Stack validation bypassed."); } else {/*from w ww .j a v a2 s. c o m*/ tereusInput.logger.info("Validating template with AWS"); final String bucketName = tereusInput.params.get(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME).toString(); final byte[] templateBytes = parameterizedTemplate.getBytes("UTF-8"); final InputStream is = new ByteArrayInputStream(templateBytes); final String templateDigest = DigestUtils.sha256Hex(templateBytes); final String keyName = String.format("%s-tereus-pre.cf.template", templateDigest); try (S3Resource resource = new S3Resource(bucketName, keyName, is, Optional.of(Long.valueOf(templateBytes.length)))) { Optional<String> templateURL = resource.upload(); final ValidateTemplateRequest validationRequest = new ValidateTemplateRequest(); validationRequest.setTemplateURL(templateURL.get()); final AmazonCloudFormationClient awsClient = new AmazonCloudFormationClient( tereusInput.awsCredentials); awsClient.setRegion(tereusInput.awsRegion); final ValidateTemplateResult validationResult = awsClient.validateTemplate(validationRequest); tereusInput.logger.debug("Stack template validation results:"); tereusInput.logger.debug(validationResult.toString()); } } }
From source file:com.tvarit.plugin.AutoScalingMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug("Starting " + this.getClass().getSimpleName() + " execution "); final BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3Client amazonS3Client = new AmazonS3Client(awsCredentials); final MavenProject project = (MavenProject) this.getPluginContext().getOrDefault("project", null); String lambdaCodeS3Bucket = this.bucketName; if (lambdaCodeS3Key == null) { lambdaCodeS3Key = new LambdaS3BucketKeyMaker().makeKey(project); lambdaCodeS3Bucket = "tvarit"; }//www .ja v a2 s. co m AmazonCloudFormationClient amazonCloudFormationClient = new AmazonCloudFormationClient(awsCredentials); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(awsCredentials); List<com.amazonaws.services.cloudformation.model.Parameter> allParams = new AsgParameterMaker().make( amazonEC2Client, amazonCloudFormationClient, project, projectName, lambdaCodeS3Key, lambdaCodeS3Bucket); final String stackName = projectName + "-asg"; if (templateUrl == null) try { templateUrl = new TemplateUrlMaker().makeUrl(project, "autoscaling.template").toString(); } catch (MalformedURLException e) { throw new MojoExecutionException( "Could not create default url for templates. Please open an issue on github.", e); } final CreateStackRequest createStackRequest = new CreateStackRequest() .withCapabilities(Capability.CAPABILITY_IAM).withStackName(stackName).withParameters(allParams) .withTemplateURL(templateUrl); final Stack stack = new StackMaker().makeStack(createStackRequest, amazonCloudFormationClient, getLog()); new S3WarUploadEventToInvokeLambdaMaker().make(amazonS3Client, bucketName, stack); getLog().info("Finished completing stack"); }
From source file:com.tvarit.plugin.InfrastructureMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug("Starting " + this.getClass().getSimpleName() + " execution "); getLog().warn(/* ww w . j a va 2 s .c o m*/ "This goal has been deprecated and may be removed without notice. Please use the goal 'make-infrastructure' instead."); final BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonCloudFormationClient amazonCloudFormationClient = new AmazonCloudFormationClient(awsCredentials); final com.amazonaws.services.cloudformation.model.Parameter domainNameParameter = new com.amazonaws.services.cloudformation.model.Parameter() .withParameterKey("domainName").withParameterValue(this.domainName); final com.amazonaws.services.cloudformation.model.Parameter projectNameParameter = new com.amazonaws.services.cloudformation.model.Parameter() .withParameterKey("projectName").withParameterValue(this.projectName); final com.amazonaws.services.cloudformation.model.Parameter bucketNameParameter = new com.amazonaws.services.cloudformation.model.Parameter() .withParameterKey("bucketName").withParameterValue("tvarit-" + this.bucketName); final CreateStackRequest createStackRequest = new CreateStackRequest() .withCapabilities(Capability.CAPABILITY_IAM).withStackName(projectName + "-infra") .withParameters(domainNameParameter, projectNameParameter, bucketNameParameter); if (templateUrl == null) { final String template = new TemplateReader().readTemplate("/cfn-templates/vpc-infra.template"); createStackRequest.withTemplateBody(template); } else { createStackRequest.withTemplateURL(templateUrl); } new StackMaker().makeStack(createStackRequest, amazonCloudFormationClient, getLog()); getLog().info("Finished completing stack"); }
From source file:com.tvarit.plugin.NewInfrastructureMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug("Starting " + this.getClass().getSimpleName() + " execution "); final BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonCloudFormationClient amazonCloudFormationClient = new AmazonCloudFormationClient(awsCredentials); final com.amazonaws.services.cloudformation.model.Parameter domainNameParameter = new com.amazonaws.services.cloudformation.model.Parameter() .withParameterKey("domainName").withParameterValue(this.domainName); final com.amazonaws.services.cloudformation.model.Parameter projectNameParameter = new com.amazonaws.services.cloudformation.model.Parameter() .withParameterKey("projectName").withParameterValue(this.projectName); final com.amazonaws.services.cloudformation.model.Parameter bucketNameParameter = new com.amazonaws.services.cloudformation.model.Parameter() .withParameterKey("bucketName").withParameterValue(this.bucketName); final String template; final MavenProject project = (MavenProject) this.getPluginContext().getOrDefault("project", null); if (templateUrl == null) { try {/*from ww w.j a v a 2s . co m*/ templateUrl = new TemplateUrlMaker().makeUrl(project, "vpc-infra.template").toString(); } catch (MalformedURLException e) { throw new MojoExecutionException( "Could not create default url for templates. Please open an issue on github.", e); } } final CreateStackRequest createStackRequest = new CreateStackRequest() .withCapabilities(Capability.CAPABILITY_IAM).withStackName(projectName + "-infra") .withParameters(domainNameParameter, projectNameParameter, bucketNameParameter) .withTemplateURL(templateUrl); new StackMaker().makeStack(createStackRequest, amazonCloudFormationClient, getLog()); getLog().info("Finished completing stack"); }
From source file:edu.columbia.cc.elPonePeli.app.LiveStreamingHelper.java
public LiveStreamingHelper(AWSCredentials credentials) { stackbuilder = new AmazonCloudFormationClient(credentials); Region region = Region.getRegion(Regions.US_EAST_1); stackbuilder.setRegion(region);/* www.j a v a 2 s . c o m*/ System.out.println("==========================================="); System.out.println("Starting Live Streaming Formation"); System.out.println("===========================================\n"); String logicalResourceName = "SampleNotificationTopic"; createFormation(streamingStackName, logicalResourceName); }