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

The following examples show how to use com.amazonaws.services.cloudformation.model.Stack. 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: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void updateStackWithStackChangeSet() 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().withStackStatus("CREATE_COMPLETE")));

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

	stack.createChangeSet("c1", "templateBody", null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, ChangeSetType.UPDATE, "myarn", null);

	ArgumentCaptor<CreateChangeSetRequest> captor = ArgumentCaptor.forClass(CreateChangeSetRequest.class);
	Mockito.verify(client).createChangeSet(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new CreateChangeSetRequest()
															   .withChangeSetType(ChangeSetType.UPDATE)
															   .withStackName("foo")
															   .withTemplateBody("templateBody")
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withChangeSetName("c1")
															   .withRoleARN("myarn")
	);
	Mockito.verify(this.eventPrinter).waitAndPrintChangeSetEvents(Mockito.eq("foo"), Mockito.eq("c1"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
}
 
Example #2
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createStackWithStackChangeSetReviewInProgress() 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().withStackStatus("REVIEW_IN_PROGRESS")));

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

	stack.createChangeSet("c1", "templateBody", null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, ChangeSetType.UPDATE, "myarn", null);

	ArgumentCaptor<CreateChangeSetRequest> captor = ArgumentCaptor.forClass(CreateChangeSetRequest.class);
	Mockito.verify(client).createChangeSet(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new CreateChangeSetRequest()
															   .withChangeSetType(ChangeSetType.CREATE)
															   .withStackName("foo")
															   .withTemplateBody("templateBody")
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withChangeSetName("c1")
															   .withRoleARN("myarn")
	);
	Mockito.verify(this.eventPrinter).waitAndPrintChangeSetEvents(Mockito.eq("foo"), Mockito.eq("c1"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
}
 
Example #3
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void noExecuteChangeSetIfNoChanges() throws ExecutionException {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);
	Mockito.when(client.describeChangeSet(new DescribeChangeSetRequest()
												  .withStackName("foo")
												  .withChangeSetName("bar")
	)).thenReturn(new DescribeChangeSetResult());
	Mockito.when(client.describeStacks(new DescribeStacksRequest().withStackName("foo")))
			.thenReturn(new DescribeStacksResult().withStacks(new Stack().withOutputs(new Output().withOutputKey("bar").withOutputValue("baz"))));

	Map<String, String> outputs = stack.executeChangeSet("bar", PollConfiguration.DEFAULT);
	Mockito.verify(client, Mockito.never()).executeChangeSet(Mockito.any(ExecuteChangeSetRequest.class));
	Assertions.assertThat(outputs).containsEntry("bar", "baz").containsEntry("jenkinsStackUpdateStatus", "false");
}
 
Example #4
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch cloud formation stack test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchCloudFormationStackTest() throws Exception {
    
    mockStatic(AmazonCloudFormationClientBuilder.class);
    AmazonCloudFormation cloudFormClient = PowerMockito.mock(AmazonCloudFormation.class);
    AmazonCloudFormationClientBuilder amazonCloudFormationClientBuilder = PowerMockito.mock(AmazonCloudFormationClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonCloudFormationClientBuilder.standard()).thenReturn(amazonCloudFormationClientBuilder);
    when(amazonCloudFormationClientBuilder.withCredentials(anyObject())).thenReturn(amazonCloudFormationClientBuilder);
    when(amazonCloudFormationClientBuilder.withRegion(anyString())).thenReturn(amazonCloudFormationClientBuilder);
    when(amazonCloudFormationClientBuilder.build()).thenReturn(cloudFormClient);
    
    DescribeStacksResult describeStacksResult = new DescribeStacksResult();
    List<Stack> stacks = new ArrayList<>();
    stacks.add(new Stack());
    describeStacksResult.setStacks(stacks);
    when(cloudFormClient.describeStacks(anyObject())).thenReturn(describeStacksResult);
    assertThat(inventoryUtil.fetchCloudFormationStack(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #5
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void executeChangeSetWithChanges() throws ExecutionException {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	Mockito.when(client.waiters()).thenReturn(new AmazonCloudFormationWaiters(client));

	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);
	Mockito.when(client.describeChangeSet(new DescribeChangeSetRequest()
												  .withStackName("foo")
												  .withChangeSetName("bar")
	)).thenReturn(new DescribeChangeSetResult()
						  .withChanges(new Change())
	);

	Mockito.when(client.describeStacks(new DescribeStacksRequest().withStackName("foo")))
			.thenReturn(new DescribeStacksResult().withStacks(new Stack().withStackStatus("CREATE_COMPLETE").withOutputs(new Output().withOutputKey("bar").withOutputValue("baz"))));

	Map<String, String> outputs = stack.executeChangeSet("bar", PollConfiguration.DEFAULT);

	Mockito.verify(client).executeChangeSet(Mockito.any(ExecuteChangeSetRequest.class));
	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 #6
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
/**
 * Get outputs for the wrapper stack and all nested stacks
 *
 * @return Outputs for stack {@link #stackName}
 */

public Map<String, String> getStackOutput() throws Exception {

    String rootStackId = getStackInfo().stackId();
    LOGGER.info("rootStackId   =   " + rootStackId);
    Map<String, String> outputs = new HashMap<>();
    outputs.put("rootStackId", rootStackId);

    DescribeStacksResult describeStacksResult = amazonCloudFormation.describeStacks();
    for (Stack currentStack : describeStacksResult.getStacks()) {
        // Get the output details for the running stacks that got created
        // go through both root and nested stacks
        if (currentStack.getStackStatus().equals(StackStatus.CREATE_COMPLETE.toString())
                && (rootStackId.equals(currentStack.getRootId())
                || rootStackId.equals(currentStack.getStackId()))) {
            for (Output output : currentStack.getOutputs()) {
                LOGGER.info(output.getOutputKey() + "   =   " + output.getOutputValue());
                outputs.put(output.getOutputKey(), output.getOutputValue());
            }
        }
    }
    return outputs;
}
 
Example #7
Source File: StackResourceUserTagsFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void getObject_stackWithTagsDefined_createTagsMap() throws Exception {
	// Arrange
	AmazonCloudFormation cloudFormation = mock(AmazonCloudFormation.class);
	StackNameProvider stackNameProvider = mock(StackNameProvider.class);

	when(stackNameProvider.getStackName()).thenReturn("testStack");
	when(cloudFormation
			.describeStacks(new DescribeStacksRequest().withStackName("testStack")))
					.thenReturn(new DescribeStacksResult().withStacks(new Stack()
							.withTags(new Tag().withKey("key1").withValue("value1"),
									new Tag().withKey("key2").withValue("value2"))));

	StackResourceUserTagsFactoryBean factoryBean = new StackResourceUserTagsFactoryBean(
			cloudFormation, stackNameProvider);

	// Act
	factoryBean.afterPropertiesSet();
	Map<String, String> factoryBeanObject = factoryBean.getObject();

	// Assert
	assertThat(factoryBeanObject.get("key1")).isEqualTo("value1");
	assertThat(factoryBeanObject.get("key2")).isEqualTo("value2");
}
 
Example #8
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
public CFTStackInfo getStackInfo() throws Exception {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);

    List<Stack> stacks = amazonCloudFormation.describeStacks(describeStacksRequest).getStacks();
    CFTStackInfo cftStackInfo = null;
    if (!stacks.isEmpty()) {
        for (Stack stack : stacks) {
            cftStackInfo = new CFTStackInfo(stack);
        }
    }
    else {
        throw new Exception("Stack not found " + stackName);
    }
    return cftStackInfo;
}
 
Example #9
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
private static Properties getCloudformationOutputs(AmazonCloudFormation cloudFormation, CreateStackResult stack) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stack.getStackId());
    final DescribeStacksResult describeStacksResult = cloudFormation
            .describeStacks(describeStacksRequest);

    Properties outputProps = new Properties();
    for (Stack st : describeStacksResult.getStacks()) {
        StringBuilder outputsStr = new StringBuilder("Infrastructure/Deployment outputs {\n");
        for (Output output : st.getOutputs()) {
            outputProps.setProperty(output.getOutputKey(), output.getOutputValue());
            outputsStr.append(output.getOutputKey()).append("=").append(output.getOutputValue()).append("\n");
        }
        //Log cfn outputs
        logger.info(outputsStr.toString() + "\n}");
    }
    return outputProps;
}
 
Example #10
Source File: OutputsUtil.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static String getStackOutputsToJson(Stack stack) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, stack.getOutputs());
    final byte[] stackOutputs = out.toByteArray();

    return new String(stackOutputs);
}
 
Example #11
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void updateStack() 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);

	RollbackConfiguration rollbackConfig = new RollbackConfiguration().withMonitoringTimeInMinutes(10);
	Map<String, String> outputs = stack.update("templateBody", null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, "myarn", rollbackConfig);

	ArgumentCaptor<UpdateStackRequest> captor = ArgumentCaptor.forClass(UpdateStackRequest.class);
	Mockito.verify(client).updateStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new UpdateStackRequest()
															   .withStackName("foo")
															   .withTemplateBody("templateBody")
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withRoleARN("myarn")
															   .withRollbackConfiguration(rollbackConfig)
	);
	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 #12
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void updateStackWithTemplateUrl() 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);

	RollbackConfiguration rollbackConfig = new RollbackConfiguration().withMonitoringTimeInMinutes(10);
	Map<String, String> outputs = stack.update(null, "bar", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, "myarn", rollbackConfig);

	ArgumentCaptor<UpdateStackRequest> captor = ArgumentCaptor.forClass(UpdateStackRequest.class);
	Mockito.verify(client).updateStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new UpdateStackRequest()
															   .withStackName("foo")
															   .withTemplateURL("bar")
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withRoleARN("myarn")
															   .withRollbackConfiguration(rollbackConfig)
	);
	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 #13
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void updateStackWithPreviousTemplate() 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);

	RollbackConfiguration rollbackConfig = new RollbackConfiguration().withMonitoringTimeInMinutes(10);
	Map<String, String> outputs = stack.update(null, null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, "myarn", rollbackConfig);

	ArgumentCaptor<UpdateStackRequest> captor = ArgumentCaptor.forClass(UpdateStackRequest.class);
	Mockito.verify(client).updateStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new UpdateStackRequest()
															   .withStackName("foo")
															   .withUsePreviousTemplate(true)
															   .withCapabilities(Capability.values())
															   .withParameters(Collections.emptyList())
															   .withRoleARN("myarn")
															   .withRollbackConfiguration(rollbackConfig)
	);
	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: 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 #15
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 #16
Source File: AwsLaunchTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private DescribeStacksResult getDescribeStacksResult() {
    return new DescribeStacksResult().withStacks(
            new Stack().withOutputs(
                    new Output().withOutputKey("CreatedVpc").withOutputValue("vpc-id"),
                    new Output().withOutputKey("CreatedSubnet").withOutputValue("subnet-id"),
                    new Output().withOutputKey("EIPAllocationIDmaster1").withOutputValue("eipalloc-id")
            ));
}
 
Example #17
Source File: StackResourceUserTagsFactoryBean.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> createInstance() throws Exception {
	LinkedHashMap<String, String> userTags = new LinkedHashMap<>();
	DescribeStacksResult stacksResult = this.amazonCloudFormation
			.describeStacks(new DescribeStacksRequest()
					.withStackName(this.stackNameProvider.getStackName()));
	for (Stack stack : stacksResult.getStacks()) {
		for (Tag tag : stack.getTags()) {
			userTags.put(tag.getKey(), tag.getValue());
		}
	}
	return userTags;
}
 
Example #18
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 #19
Source File: TestStackInstanceIdService.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static Stack getStack(DescribeStacksResult describeStacksResult,
		String stackName) {
	for (Stack stack : describeStacksResult.getStacks()) {
		if (stack.getStackName().equals(stackName)) {
			return stack;
		}
	}

	throw new IllegalStateException(
			"No stack found with name '" + stackName + "' (available stacks: "
					+ allStackNames(describeStacksResult) + ")");
}
 
Example #20
Source File: TestStackInstanceIdService.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static String getOutputValue(Stack stack, String outputKey) {
	for (Output output : stack.getOutputs()) {
		if (output.getOutputKey().equals(outputKey)) {
			return output.getOutputValue();
		}
	}

	throw new IllegalStateException("No output '" + outputKey
			+ "' defined in stack '" + stack.getStackName() + "'");
}
 
Example #21
Source File: TestStackInstanceIdService.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public String getInstanceId() {
	DescribeStacksResult describeStacksResult = this.amazonCloudFormationClient
			.describeStacks(new DescribeStacksRequest());
	Stack stack = getStack(describeStacksResult, this.stackName);

	return getOutputValue(stack, this.outputKey);
}
 
Example #22
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void stackExists() {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);
	Mockito.when(client.describeStacks(new DescribeStacksRequest()
											   .withStackName("foo")
	)).thenReturn(new DescribeStacksResult()
						  .withStacks(new Stack()
						  )
	);
	Assertions.assertThat(stack.exists()).isTrue();
}
 
Example #23
Source File: CloudFormationStack.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
public Map<String, String> describeOutputs() {
	DescribeStacksResult result = this.client.describeStacks(new DescribeStacksRequest().withStackName(this.stack));
	Stack cfnStack = result.getStacks().get(0);
	Map<String, String> map = new HashMap<>();
	for (Output output : cfnStack.getOutputs()) {
		map.put(output.getOutputKey(), output.getOutputValue());
	}
	return map;
}
 
Example #24
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void describeStack() {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);
	Mockito.when(client.describeStacks(new DescribeStacksRequest().withStackName("foo")))
			.thenReturn(new DescribeStacksResult().withStacks(new Stack().withOutputs(new Output().withOutputKey("bar").withOutputValue("baz"))));
	Assertions.assertThat(stack.describeOutputs()).isEqualTo(Collections.singletonMap(
			"bar", "baz"
	));
}
 
Example #25
Source File: CloudFormationFacade.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 5 votes vote down vote up
private Stack describeStack(String stackId) {
    DescribeStacksRequest request = new DescribeStacksRequest().withStackName(stackId);
    DescribeStacksResult result = cloudformation.describeStacks(request);

    List<Stack> stacks = result.getStacks();
    if (stacks.isEmpty()) {
        String message = String.format("Invalid stackId. No stack found for %s.", stackId);
        throw new RuntimeException(message);
    }
    return stacks.get(0);
}
 
Example #26
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
public Stack getStackByName(String stackName) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);
    List<Stack> stacksList = amazonCloudFormation.describeStacks(describeStacksRequest).getStacks();
    assertNotNull("stack list cannot be null", stacksList);
    assertEquals("only 1 stack is expected, but getting " + stacksList.size(), 1,
            stacksList.size());
    return stacksList.get(0);
}
 
Example #27
Source File: FileManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate cloud formation stack files.
 *
 * @param fileInofMap the file inof map
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void generateCloudFormationStackFiles(Map<String,List<Stack>> fileInofMap) throws IOException {
	String fieldNames;
	String keys;
	fieldNames ="StackId`StackName`ChangeSetId`CreationTime`Description`DisableRollback`LastUpdatedTime`RoleARN`StackStatus`StackStatusReason`TimeoutInMinutes";
	keys ="discoverydate`accountid`accountname`region`stackid`stackname`changesetid`creationtime`description`disablerollback`lastupdatedtime`rolearn`status`statusreason`timeoutinminutes";
	FileGenerator.generateJson(fileInofMap, fieldNames, "aws-stack.data",keys);
	fieldNames ="StackId`tags.key`tags.value";
	keys ="discoverydate`accountid`accountname`region`stackid`key`value";
	FileGenerator.generateJson(fileInofMap, fieldNames, "aws-stack-tags.data",keys);

}
 
Example #28
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch cloud formation stack.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<Stack>> fetchCloudFormationStack(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	AmazonCloudFormation cloudFormClient ;
	Map<String,List<Stack>> stacks = new LinkedHashMap<>();
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Stack\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				List<Stack> stacksTemp = new ArrayList<>();
				String nextToken = null;
				cloudFormClient = AmazonCloudFormationClientBuilder.standard().
						 withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeStacksResult describeResult ;
				do{
					describeResult =  cloudFormClient.describeStacks(new DescribeStacksRequest().withNextToken(nextToken));
					stacksTemp.addAll(describeResult.getStacks());
					nextToken = describeResult.getNextToken();
				}while(nextToken!=null);

				if(! stacksTemp.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Cloud Formation Stack "+region.getName() + " >> " + stacksTemp.size());
					stacks.put(accountId+delimiter+accountName+delimiter+region.getName(), stacksTemp);
				}
			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"stack",e.getMessage());
		}
	}
	return stacks;
}
 
Example #29
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
public Stack getStackByNamePrefix(String stackNamePrefix) {
    List<Stack> stacksList = amazonCloudFormation.describeStacks().getStacks()
            .stream().filter(stack -> stack.getStackName().startsWith(stackNamePrefix))
            .collect(Collectors.toList());
    assertNotNull(stacksList);
    assertTrue(stacksList.size() > 0);
    return stacksList.get(0);
}
 
Example #30
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
public boolean stackExists(String stackName){
    LOGGER.info("Check if stack exists or not :" + stackName);
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);
    try {
        List<Stack> stacks = amazonCloudFormation.describeStacks(describeStacksRequest).getStacks();
    } catch (AmazonCloudFormationException e) {
        if (e.getErrorCode().equals("ValidationError")){
            return false;
        }
    }
    return true;
}