com.amazonaws.services.cloudformation.model.CreateStackRequest Java Examples

The following examples show how to use com.amazonaws.services.cloudformation.model.CreateStackRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudFormationStack.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
public Map<String, String> create(String templateBody, String templateUrl, Collection<Parameter> params, Collection<Tag> tags, Collection<String> notificationARNs, PollConfiguration pollConfiguration, String roleArn, String onFailure, Boolean enableTerminationProtection) throws ExecutionException {
	if ((templateBody == null || templateBody.isEmpty()) && (templateUrl == null || templateUrl.isEmpty())) {
		throw new IllegalArgumentException("Either a file or url for the template must be specified");
	}

	CreateStackRequest req = new CreateStackRequest();
	req.withStackName(this.stack).withCapabilities(Capability.CAPABILITY_IAM, Capability.CAPABILITY_NAMED_IAM, Capability.CAPABILITY_AUTO_EXPAND).withEnableTerminationProtection(enableTerminationProtection);
	req.withTemplateBody(templateBody).withTemplateURL(templateUrl).withParameters(params).withTags(tags).withNotificationARNs(notificationARNs)
			.withTimeoutInMinutes(pollConfiguration.getTimeout() == null ? null : (int) pollConfiguration.getTimeout().toMinutes())
			.withRoleARN(roleArn)
			.withOnFailure(OnFailure.valueOf(onFailure));
	this.client.createStack(req);

	new EventPrinter(this.client, this.listener).waitAndPrintStackEvents(this.stack, this.client.waiters().stackCreateComplete(), pollConfiguration);

	Map<String, String> outputs = this.describeOutputs();
	outputs.put(UPDATE_STATUS_OUTPUT, "true");
	return outputs;
}
 
Example #2
Source File: AwsStackRequestHelperTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCreateStackRequestForCloudStack() {
    when(cloudContext.getLocation()).thenReturn(Location.location(Region.region("region"), new AvailabilityZone("az")));
    DescribeImagesResult imagesResult = new DescribeImagesResult();
    when(amazonEC2Client.describeImages(any(DescribeImagesRequest.class)))
            .thenReturn(imagesResult.withImages(new com.amazonaws.services.ec2.model.Image()));
    when(network.getStringParameter(anyString())).thenReturn("");

    Collection<Tag> tags = Lists.newArrayList(new Tag().withKey("mytag").withValue("myvalue"));
    when(awsTaggingService.prepareCloudformationTags(authenticatedContext, cloudStack.getTags())).thenReturn(tags);

    CreateStackRequest createStackRequest =
            underTest.createCreateStackRequest(authenticatedContext, cloudStack, "stackName", "subnet", "template");

    assertEquals("stackName", createStackRequest.getStackName());
    assertEquals("template", createStackRequest.getTemplateBody());

    verify(awsTaggingService).prepareCloudformationTags(authenticatedContext, cloudStack.getTags());
    assertEquals(tags, createStackRequest.getTags());
}
 
Example #3
Source File: CloudFormationManagerTest.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 6 votes vote down vote up
/**
 * Test of terminateCluster method, of class EMRManager.
 */
@Test
public void testTerminateStack() throws IOException {
    AmazonCloudFormationClient client = new AmazonCloudFormationClient();
    String name = "JUnitStack" + UUID.randomUUID().toString();
    CreateStackRequest createStackRequest = new CreateStackRequest();
    CloudFormationManager manager = new CloudFormationManager(Region.getRegion(Regions.US_WEST_2));
    
    client.setRegion(Region.getRegion(Regions.US_WEST_2));
    
    createStackRequest.setStackName(name);
    createStackRequest.setTemplateBody(IOUtils.toString(getClass().getResourceAsStream("cloudformation.template"), "UTF-8"));
    
    client.createStack(createStackRequest);
    
    manager.terminateStack(name);
    
    for(StackSummary stack : client.listStacks().getStackSummaries())
    {
        if(stack.getStackStatus().equalsIgnoreCase("DELETE_COMPLETE")) continue;
        if(stack.getStackStatus().equalsIgnoreCase("DELETE_FAILED")) continue;
        if(stack.getStackStatus().equalsIgnoreCase("DELETE_IN_PROGRESS")) continue;
        
        if(stack.getStackName().equals(name)) fail(name +  " should have been deleted but status is: " + stack.getStackStatus());
    }
}
 
Example #4
Source File: CreateStackTask.java    From aws-ant-tasks with Apache License 2.0 5 votes vote down vote up
public void execute() {
    checkParams();
    AmazonCloudFormationClient client = getOrCreateClient(AmazonCloudFormationClient.class);
    CreateStackRequest createStackRequest = new CreateStackRequest()
            .withDisableRollback(disableRollback).withOnFailure(onFailure)
            .withStackName(stackName).withStackPolicyBody(stackPolicyBody)
            .withStackPolicyURL(stackPolicyURL)
            .withTemplateBody(templateBody).withTemplateURL(templateURL)
            .withTimeoutInMinutes(timeoutInMinutes);

    if (capabilities.size() > 0) {
        createStackRequest.setCapabilities(capabilities);
    }
    if (parameters.size() > 0) {
        createStackRequest.setParameters(parameters);
    }
    if (tags.size() > 0) {
        createStackRequest.setTags(tags);
    }
    try {
        client.createStack(createStackRequest);
        System.out.println("Create stack " + stackName
                + " request submitted.");
        if(waitForCreation) {
            WaitForStackToReachStateTask.waitForCloudFormationStackToReachStatus(client, stackName, CREATE_COMPLETE);
        }
    } catch (Exception e) {
        throw new BuildException(
                "Could not create stack " + e.getMessage(), e);
    }
}
 
Example #5
Source File: AwsStackRequestHelperTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCreateStackRequestForDatabaseStack() {
    Collection<Tag> tags = Lists.newArrayList(new Tag().withKey("mytag").withValue("myvalue"));
    when(awsTaggingService.prepareCloudformationTags(authenticatedContext, databaseStack.getTags())).thenReturn(tags);

    CreateStackRequest createStackRequest =
            underTest.createCreateStackRequest(authenticatedContext, databaseStack, "stackName", "template");

    assertEquals("stackName", createStackRequest.getStackName());
    assertEquals("template", createStackRequest.getTemplateBody());

    verify(awsTaggingService).prepareCloudformationTags(authenticatedContext, cloudStack.getTags());
    assertEquals(tags, createStackRequest.getTags());
}
 
Example #6
Source File: AwsNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateNewNetworkWithSubnetsShouldCreateTheNetworkAndSubnets() {
    String networkCidr = "0.0.0.0/16";
    Set<NetworkSubnetRequest> subnets = Set.of(new NetworkSubnetRequest("1.1.1.1/8", PUBLIC), new NetworkSubnetRequest("1.1.1.2/8", PUBLIC));
    AmazonCloudFormationRetryClient cloudFormationRetryClient = mock(AmazonCloudFormationRetryClient.class);
    AmazonServiceException amazonServiceException = new AmazonServiceException("does not exist");
    amazonServiceException.setStatusCode(400);
    when(cloudFormationRetryClient.describeStacks(any(DescribeStacksRequest.class))).thenThrow(amazonServiceException);
    AmazonCloudFormationClient cfClient = mock(AmazonCloudFormationClient.class);
    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    Map<String, String> output = createOutput();
    NetworkCreationRequest networkCreationRequest = createNetworkRequest(networkCidr, subnets);
    List<SubnetRequest> subnetRequestList = createSubnetRequestList();
    Set<CreatedSubnet> createdSubnets = Set.of(new CreatedSubnet(), new CreatedSubnet(), new CreatedSubnet());

    when(awsClient.createAccess(any(), any())).thenReturn(ec2Client);
    when(awsSubnetRequestProvider.provide(ec2Client, new ArrayList<>(subnets), new ArrayList<>(subnets))).thenReturn(subnetRequestList);
    when(awsClient.createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cloudFormationRetryClient);
    when(awsClient.createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cfClient);
    when(cfClient.waiters()).thenReturn(cfWaiters);
    when(cfWaiters.stackCreateComplete()).thenReturn(creationWaiter);
    when(cfStackUtil.getOutputs(NETWORK_ID, cloudFormationRetryClient)).thenReturn(output);
    when(awsCreatedSubnetProvider.provide(output, subnetRequestList, true)).thenReturn(createdSubnets);

    CreatedCloudNetwork actual = underTest.createNetworkWithSubnets(networkCreationRequest);

    verify(awsClient).createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(awsNetworkCfTemplateProvider).provide(networkCreationRequest, subnetRequestList);
    verify(awsClient).createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(creationWaiter, times(1)).run(any());
    verify(awsTaggingService).prepareCloudformationTags(any(), any());
    verify(cloudFormationRetryClient).createStack(any(CreateStackRequest.class));
    verify(cfStackUtil).getOutputs(NETWORK_ID, cloudFormationRetryClient);
    assertEquals(VPC_ID, actual.getNetworkId());
    assertEquals(NUMBER_OF_SUBNETS, actual.getSubnets().size());
}
 
Example #7
Source File: AwsNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateNetworkWithSubnetsShouldReturnTheNetworkAndSubnets() {
    String networkCidr = "0.0.0.0/16";
    Set<NetworkSubnetRequest> subnets = Set.of(new NetworkSubnetRequest("1.1.1.1/8", PUBLIC), new NetworkSubnetRequest("1.1.1.2/8", PUBLIC));
    AmazonCloudFormationRetryClient cloudFormationRetryClient = mock(AmazonCloudFormationRetryClient.class);
    AmazonCloudFormationClient cfClient = mock(AmazonCloudFormationClient.class);
    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    Map<String, String> output = createOutput();
    NetworkCreationRequest networkCreationRequest = createNetworkRequest(networkCidr, subnets);
    List<SubnetRequest> subnetRequestList = createSubnetRequestList();
    Set<CreatedSubnet> createdSubnets = Set.of(new CreatedSubnet(), new CreatedSubnet(), new CreatedSubnet());

    when(awsClient.createAccess(any(), any())).thenReturn(ec2Client);
    when(awsSubnetRequestProvider.provide(ec2Client, new ArrayList<>(subnets), new ArrayList<>(subnets))).thenReturn(subnetRequestList);
    when(awsClient.createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cloudFormationRetryClient);
    when(awsClient.createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cfClient);

    when(cfClient.waiters()).thenReturn(cfWaiters);
    when(cfWaiters.stackCreateComplete()).thenReturn(creationWaiter);
    when(cfStackUtil.getOutputs(NETWORK_ID, cloudFormationRetryClient)).thenReturn(output);
    when(awsCreatedSubnetProvider.provide(output, subnetRequestList, true)).thenReturn(createdSubnets);

    CreatedCloudNetwork actual = underTest.createNetworkWithSubnets(networkCreationRequest);

    verify(awsClient).createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(awsClient).createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(creationWaiter, times(1)).run(any());
    verify(cfStackUtil).getOutputs(NETWORK_ID, cloudFormationRetryClient);
    verify(awsTaggingService, never()).prepareCloudformationTags(any(), any());
    verify(cloudFormationRetryClient, never()).createStack(any(CreateStackRequest.class));
    assertEquals(VPC_ID, actual.getNetworkId());
    assertEquals(NUMBER_OF_SUBNETS, actual.getSubnets().size());
}
 
Example #8
Source File: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private CreateStackRequest createStackRequest(String stackName, String cloudFormationTemplate, Map<String, String> tags, String creatorUser) {
    Collection<Tag> awsTags = awsTaggingService.prepareCloudformationTags(null, tags);
    return new CreateStackRequest()
            .withStackName(stackName)
            .withOnFailure(OnFailure.DO_NOTHING)
            .withTemplateBody(cloudFormationTemplate)
            .withTags(awsTags)
            .withCapabilities(CAPABILITY_IAM);
}
 
Example #9
Source File: AwsStackRequestHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public CreateStackRequest createCreateStackRequest(AuthenticatedContext ac, DatabaseStack stack, String cFStackName, String cfTemplate) {
    return new CreateStackRequest()
            .withStackName(cFStackName)
            .withOnFailure(OnFailure.DO_NOTHING)
            .withTemplateBody(cfTemplate)
            .withTags(awsTaggingService.prepareCloudformationTags(ac, stack.getTags()))
            .withCapabilities(CAPABILITY_IAM)
            .withParameters(getStackParameters(ac, stack));
}
 
Example #10
Source File: AwsStackRequestHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public CreateStackRequest createCreateStackRequest(AuthenticatedContext ac, CloudStack stack, String cFStackName, String subnet, String cfTemplate) {
    return new CreateStackRequest()
            .withStackName(cFStackName)
            .withOnFailure(OnFailure.DO_NOTHING)
            .withTemplateBody(cfTemplate)
            .withTags(awsTaggingService.prepareCloudformationTags(ac, stack.getTags()))
            .withCapabilities(CAPABILITY_IAM)
            .withParameters(getStackParameters(ac, stack, cFStackName, subnet));
}
 
Example #11
Source File: TestStackEnvironment.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private DescribeStackResourcesResult getStackResources(String stackName)
		throws InterruptedException, IOException {
	try {
		DescribeStacksResult describeStacksResult = this.amazonCloudFormationClient
				.describeStacks(new DescribeStacksRequest().withStackName(stackName));
		for (Stack stack : describeStacksResult.getStacks()) {
			if (isAvailable(stack)) {
				return this.amazonCloudFormationClient
						.describeStackResources(new DescribeStackResourcesRequest()
								.withStackName(stack.getStackName()));
			}
			if (isError(stack)) {
				if (this.stackCreatedByThisInstance) {
					throw new IllegalArgumentException("Could not create stack");
				}
				this.amazonCloudFormationClient.deleteStack(
						new DeleteStackRequest().withStackName(stack.getStackName()));
				return getStackResources(stackName);
			}
			if (isInProgress(stack)) {
				// noinspection BusyWait
				Thread.sleep(5000L);
				return getStackResources(stackName);
			}
		}
	}
	catch (AmazonClientException e) {
		String templateBody = FileCopyUtils.copyToString(new InputStreamReader(
				new ClassPathResource(TEMPLATE_PATH).getInputStream()));
		this.amazonCloudFormationClient.createStack(new CreateStackRequest()
				.withTemplateBody(templateBody).withOnFailure(OnFailure.DELETE)
				.withStackName(stackName)
				.withTags(new Tag().withKey("tag1").withValue("value1"))
				.withParameters(new Parameter().withParameterKey("RdsPassword")
						.withParameterValue(this.rdsPassword)));
		this.stackCreatedByThisInstance = true;
	}

	return getStackResources(stackName);
}
 
Example #12
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void createStackWithTemplateUrl() throws ExecutionException {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	Mockito.when(client.waiters()).thenReturn(new AmazonCloudFormationWaiters(client));
	Mockito.when(client.describeStacks(new DescribeStacksRequest().withStackName("foo")))
			.thenReturn(new DescribeStacksResult().withStacks(new Stack().withOutputs(new Output().withOutputKey("bar").withOutputValue("baz"))));

	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);

	PollConfiguration pollConfiguration = PollConfiguration.builder()
			.timeout(Duration.ofMinutes(3))
			.pollInterval(Duration.ofSeconds(17))
			.build();
	Map<String, String> outputs = stack.create(null, "bar", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), pollConfiguration, "myarn", OnFailure.DO_NOTHING.toString(), true);

	ArgumentCaptor<CreateStackRequest> captor = ArgumentCaptor.forClass(CreateStackRequest.class);
	Mockito.verify(client).createStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new CreateStackRequest()
															   .withStackName("foo")
															   .withEnableTerminationProtection(true)
															   .withTemplateURL("bar")
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withTimeoutInMinutes(3)
															   .withOnFailure(OnFailure.DO_NOTHING)
															   .withRoleARN("myarn")
	);
	Mockito.verify(this.eventPrinter).waitAndPrintStackEvents(Mockito.eq("foo"), Mockito.any(Waiter.class), Mockito.eq(pollConfiguration));
	Assertions.assertThat(outputs).containsEntry("bar", "baz").containsEntry("jenkinsStackUpdateStatus", "true");
}
 
Example #13
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void createStack() throws ExecutionException {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	Mockito.when(client.waiters()).thenReturn(new AmazonCloudFormationWaiters(client));
	Mockito.when(client.describeStacks(new DescribeStacksRequest().withStackName("foo")))
			.thenReturn(new DescribeStacksResult().withStacks(new Stack().withOutputs(new Output().withOutputKey("bar").withOutputValue("baz"))));

	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);

	Map<String, String> outputs = stack.create("templateBody", null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, "myarn", OnFailure.DO_NOTHING.toString(), null);

	ArgumentCaptor<CreateStackRequest> captor = ArgumentCaptor.forClass(CreateStackRequest.class);
	Mockito.verify(client).createStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new CreateStackRequest()
															   .withStackName("foo")
															   .withTemplateBody("templateBody")
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withTimeoutInMinutes((int) PollConfiguration.DEFAULT.getTimeout().toMinutes())
															   .withOnFailure(OnFailure.DO_NOTHING)
															   .withRoleARN("myarn")
	);
	Mockito.verify(this.eventPrinter).waitAndPrintStackEvents(Mockito.eq("foo"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
	Assertions.assertThat(outputs).containsEntry("bar", "baz").containsEntry("jenkinsStackUpdateStatus", "true");
}
 
Example #14
Source File: LoaderTest.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 5 votes vote down vote up
/**
 * Test of teardown method, of class Loader.
 */
@Test
public void testTeardown() throws IOException, SQLException, ClassNotFoundException 
{
    AmazonCloudFormationClient client = new AmazonCloudFormationClient();
    String name = "TestTeardownCluster" + UUID.randomUUID().toString();
    CreateStackRequest createStackRequest = new CreateStackRequest();
    
    client.setRegion(Region.getRegion(Regions.US_WEST_2)); 
    
    createStackRequest.setStackName(name);
    createStackRequest.setTemplateBody(IOUtils.toString(getClass().getResourceAsStream("cloudformation.template"), "UTF-8"));
    
    client.createStack(createStackRequest);
    
    loader.setConfiguration(configuration);
    loader.teardown(name, Region.getRegion(Regions.US_WEST_2));
    
    for(StackSummary stack : client.listStacks().getStackSummaries())
    {
        if(stack.getStackStatus().equalsIgnoreCase("DELETE_COMPLETE")) continue;
        if(stack.getStackStatus().equalsIgnoreCase("DELETE_FAILED")) continue;
        if(stack.getStackStatus().equalsIgnoreCase("DELETE_IN_PROGRESS")) continue;
        
        if(stack.getStackName().equals(name)) fail(name +  " should have been deleted but status is: " + stack.getStackStatus());
    }
}
 
Example #15
Source File: AmazonCloudFormationRetryClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public CreateStackResult createStack(CreateStackRequest request) {
    return retry.testWith2SecDelayMax15Times(() -> mapThrottlingError(() -> client.createStack(request)));
}
 
Example #16
Source File: CreateStackAction.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
/**
 * Creates AWS Cloud Formation Stack in sync mode using AWS Java SDK
 *
 * @param identity          Access key associated with your Amazon AWS or IAM account.
 *                          Example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
 * @param credential        Secret access key ID associated with your Amazon AWS or IAM account.
 * @param proxyHost         Optional - proxy server used to connect to Amazon API. If empty no proxy will be used.
 *                          Default: ""
 * @param proxyPort         Optional - proxy server port. You must either specify values for both proxyHost and
 *                          proxyPort inputs or leave them both empty.
 *                          Default: ""
 * @param proxyUsername     Optional - proxy server user name.
 *                          Default: ""
 * @param proxyPassword     Optional - proxy server password associated with the proxyUsername input value.
 *                          Default: ""
 * @param region            AWS region name
 *                          Example: "eu-central-1"
 * @param stackName         Stack name to create
 *                          Example: "MyStack"
 * @param templateBody      Template body in JSON or YAML format
 * @param parameters        Template parameters in key value format, one key=value per line
 * @return                  A map with strings as keys and strings as values that contains: outcome of the action, returnCode of the
 *                          operation, or failure message and the exception if there is one
 */
@Action(name = "Create AWS Cloud Formation Stack",
        outputs = {
                @Output(Outputs.RETURN_CODE),
                @Output(Outputs.RETURN_RESULT),
                @Output(Outputs.EXCEPTION)
        },
        responses = {
                @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
                        matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
                        matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
        }
)
public Map<String, String> execute(
        @Param(value = IDENTITY,   required = true)  String identity,
        @Param(value = CREDENTIAL, required = true, encrypted = true)  String credential,
        @Param(value = REGION,     required = true)  String region,
        @Param(value = PROXY_HOST)                   String proxyHost,
        @Param(value = PROXY_PORT)                   String proxyPort,
        @Param(value = PROXY_USERNAME)               String proxyUsername,
        @Param(value = PROXY_PASSWORD, encrypted = true) String proxyPassword,
        @Param(value = CONNECT_TIMEOUT)              String connectTimeoutMs,
        @Param(value = EXECUTION_TIMEOUT)            String execTimeoutMs,
        @Param(value = STACK_NAME, required = true)  String stackName,
        @Param(value = TEMPLATE_BODY, required = true) String templateBody,
        @Param(value = PARAMETERS)                   String parameters,
        @Param(value = CAPABILITIES)                 String capabilities) {

    proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT);
    connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
    execTimeoutMs = defaultIfEmpty(execTimeoutMs, DefaultValues.EXEC_TIMEOUT);

    try {
        final CreateStackRequest createRequest = new CreateStackRequest()
                .withStackName(stackName)
                .withTemplateBody(templateBody)
                .withParameters(toArrayOfParameters(parameters))
                .withCapabilities(toArrayOfString(capabilities));

        final AmazonCloudFormation stackBuilder = CloudFormationClientBuilder.getCloudFormationClient(identity, credential, proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs, region);

        final CreateStackResult result = stackBuilder.createStack(createRequest);

        return OutputUtilities.getSuccessResultsMap(result.toString());
    } catch (Exception e) {
        return OutputUtilities.getFailureResultsMap(e);
    }
}
 
Example #17
Source File: AwsIntegrationTestStackRule.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
@Override
protected void before() throws Throwable {
	try {
		String awsCredentialsDir = System.getProperty("aws.credentials.path");
		File awsCredentialsFile = new File(awsCredentialsDir, "aws.credentials.properties");
		Properties awsCredentials = new Properties();
		awsCredentials.load(new FileReader(awsCredentialsFile));
		String accessKey = awsCredentials.getProperty("cloud.aws.credentials.accessKey");
		String secretKey = awsCredentials.getProperty("cloud.aws.credentials.secretKey");
		this.cloudFormation = new AmazonCloudFormationClient(new BasicAWSCredentials(accessKey, secretKey));

		YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
		yamlPropertiesFactoryBean.setResources(new ClassPathResource("application.yml"));
		Properties applicationProperties = yamlPropertiesFactoryBean.getObject();

		this.stackName = applicationProperties.getProperty("cloud.aws.stack.name");

		after();

		ClassPathResource stackTemplate = new ClassPathResource("AwsIntegrationTestTemplate.json");
		String templateBody = FileCopyUtils.copyToString(new InputStreamReader(stackTemplate.getInputStream()));

		this.cloudFormation.createStack(
				new CreateStackRequest()
						.withTemplateBody(templateBody)
						.withOnFailure(OnFailure.DELETE)
						.withStackName(this.stackName));

		waitForCompletion();

		System.setProperty("cloud.aws.credentials.accessKey", accessKey);
		System.setProperty("cloud.aws.credentials.secretKey", secretKey);
	}
	catch (Exception e) {
		if (!(e instanceof AssumptionViolatedException)) {
			Assume.assumeTrue("Can't perform AWS integration test because of: " + e.getMessage(), false);
		}
		else {
			throw e;
		}
	}
}