List of usage examples for com.amazonaws.services.cloudformation.model CreateStackRequest CreateStackRequest
CreateStackRequest
From source file:CloudFormation.java
License:Open Source License
public static void main(String[] args) throws Exception { /*//from w ww. j a v a2s .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:CloudFormationSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/* w ww. j a va 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:br.com.ingenieux.mojo.cloudformation.PushStackMojo.java
License:Apache License
private CreateStackResult createStack() throws Exception { CreateStackRequest req = new CreateStackRequest().withStackName(stackName) .withCapabilities(Capability.CAPABILITY_IAM); if (null != this.destinationS3Uri) { req.withTemplateURL(generateExternalUrl(this.destinationS3Uri)); } else {/* w ww .ja va 2 s. c om*/ req.withTemplateBody(templateBody); } req.withNotificationARNs(notificationArns); req.withParameters(parameters); req.withResourceTypes(resourceTypes); req.withDisableRollback(disableRollback); req.withTags(tags); req.withTimeoutInMinutes(timeoutInMinutes); return getService().createStack(req); }
From source file:com.carrotgarden.maven.aws.cfn.CarrotCloudForm.java
License:BSD License
/** *//*from w w w .j a va 2s .c o m*/ public Stack stackCreate() throws Exception { final CreateStackRequest request = new CreateStackRequest(); request.withStackName(name); request.withParameters(paramList); request.withTemplateBody(template); amazonClient.createStack(request); final Stack stack = waitForStackCreate(); return stack; }
From source file:com.deploymentio.cfnstacker.CloudFormationClient.java
License:Apache License
/** * Initiates creation of a new CloudFormation stack with the given options * and template/*from ww w . j av a 2 s . c o m*/ * * @param templateBody ClouadFormation JSON template to create the stack * from * @return ID of the new stack */ public String createStack(JsonNode templateBody, boolean disableRollback) throws Exception { List<Tag> tags = new ArrayList<>(); for (String key : config.getTags().keySet()) { tags.add(new Tag().withKey(key).withValue(config.getTags().get(key))); } return client.createStack(new CreateStackRequest().withStackName(config.getName()) .withTemplateURL(uploadCfnTemplateToS3(config.getName(), "create", templateBody)) .withNotificationARNs(config.getSnsTopic()).withCapabilities("CAPABILITY_IAM").withTags(tags) .withDisableRollback(disableRollback) .withParameters(templateParameters.getApplicableParameters(templateBody))).getStackId(); }
From source file:com.kinesisboard.amazonaws.utils.CloudFormationUtils.java
License:Open Source License
public static void createStackIfNotExists(AmazonCloudFormation client, KinesisConnectorConfiguration config) { String stackName = config.ELASTICSEARCH_CLOUDFORMATION_STACK_NAME; if (stackExists(client, stackName)) { StackStatus status = stackStatus(client, stackName); switch (status) { case CREATE_COMPLETE: case UPDATE_COMPLETE: LOG.info("Stack " + stackName + " already exists."); return; case CREATE_IN_PROGRESS: case UPDATE_IN_PROGRESS: case UPDATE_COMPLETE_CLEANUP_IN_PROGRESS: LOG.info("Stack " + stackName + " exists with status: " + status + ". Waiting for completion."); break; default:/*from w w w . j a v a 2s . c om*/ throw new IllegalStateException( "Stack " + stackName + " exists but has an invalid status: " + status); } } else { CreateStackRequest createStackRequest = new CreateStackRequest(); createStackRequest.setStackName(stackName); String templateBody = null; try { templateBody = loadTemplate(config.ELASTICSEARCH_CLOUDFORMATION_TEMPLATE_URL); } catch (IOException ioe) { LOG.error("Error reading template", ioe); throw new RuntimeException( "Could not load template at location: " + config.ELASTICSEARCH_CLOUDFORMATION_TEMPLATE_URL); } createStackRequest.setTemplateBody(templateBody); List<Parameter> parameters = new ArrayList<Parameter>(); parameters.add(new Parameter().withParameterKey("KeyName") .withParameterValue(config.ELASTICSEARCH_CLOUDFORMATION_KEY_PAIR_NAME)); parameters.add(new Parameter().withParameterKey("InstanceType") .withParameterValue(config.ELASTICSEARCH_CLOUDFORMATION_CLUSTER_INSTANCE_TYPE)); parameters.add(new Parameter().withParameterKey("SSHLocation") .withParameterValue(config.ELASTICSEARCH_CLOUDFORMATION_SSH_LOCATION)); parameters.add(new Parameter().withParameterKey("ClusterSize") .withParameterValue(config.ELASTICSEARCH_CLOUDFORMATION_CLUSTER_SIZE)); parameters.add(new Parameter().withParameterKey("ElasticsearchVersion") .withParameterValue(config.ELASTICSEARCH_VERSION_NUMBER)); createStackRequest.setParameters(parameters); List<String> capabilities = new ArrayList<String>(); capabilities.add("CAPABILITY_IAM"); createStackRequest.setCapabilities(capabilities); client.createStack(createStackRequest); LOG.info("Stack " + stackName + " is creating"); } // now wait for good status while (true) { try { Thread.sleep(1000 * 10); } catch (Exception e) { } StackStatus status = stackStatus(client, stackName); switch (status) { case CREATE_COMPLETE: case UPDATE_COMPLETE: return; case CREATE_IN_PROGRESS: case UPDATE_IN_PROGRESS: case UPDATE_COMPLETE_CLEANUP_IN_PROGRESS: break; default: throw new IllegalStateException("Stack " + stackName + " failed to create with status: " + status); } } }
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); }//w ww .j av a 2 s . com } 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.netflix.spinnaker.clouddriver.aws.deploy.ops.DeployCloudFormationAtomicOperation.java
License:Apache License
private String createStack(AmazonCloudFormation amazonCloudFormation, String template, List<Parameter> parameters) { Task task = TaskRepository.threadLocalTask.get(); task.updateStatus(BASE_PHASE, "Preparing CloudFormation Stack"); CreateStackRequest createStackRequest = new CreateStackRequest().withStackName(description.getStackName()) .withParameters(parameters).withTemplateBody(template); task.updateStatus(BASE_PHASE, "Uploading CloudFormation Stack"); CreateStackResult createStackResult = amazonCloudFormation.createStack(createStackRequest); return createStackResult.getStackId(); }
From source file:com.nike.cerberus.service.CloudFormationService.java
License:Apache License
/** * Creates a new stack.//from www.j a v a 2 s.c o m * * @param name Stack name. * @param parameters Input parameters. * @param templatePath Classpath to the JSON template of the stack. * @return Stack ID */ public String createStack(final String name, final Map<String, String> parameters, final String templatePath, final boolean iamCapabilities) { logger.info(String.format("Executing the Cloud Formation: %s, Stack Name: %s", templatePath, name)); final CreateStackRequest request = new CreateStackRequest().withStackName(name) .withParameters(convertParameters(parameters)).withTemplateBody(getTemplateText(templatePath)); if (iamCapabilities) { request.getCapabilities().add("CAPABILITY_IAM"); } final CreateStackResult result = cloudFormationClient.createStack(request); return result.getStackId(); }
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"; }/* w w w .ja v a2 s .c om*/ 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"); }