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

The following examples show how to use com.amazonaws.services.cloudformation.model.DescribeStacksResult. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createNewStackChangeSet() 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());

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

	stack.createChangeSet("c1", "templateBody", null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), PollConfiguration.DEFAULT, ChangeSetType.CREATE, "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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #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
private boolean isInReview() {
	if (this.exists()) {
		DescribeStacksResult result = this.client.describeStacks(new DescribeStacksRequest().withStackName(this.stack));
		return result.getStacks().size() > 0 && result.getStacks().get(0).getStackStatus().equals("REVIEW_IN_PROGRESS");
	}
	return false;
}
 
Example #24
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 #25
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 #26
Source File: StackCreationWaiter.java    From testgrid with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean call() throws Exception {
    //Stack details
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(stackName);
    DescribeStacksResult describeStacksResult = cloudFormation.describeStacks(describeStacksRequest);
    final List<Stack> stacks = describeStacksResult.getStacks();
    if (stacks.size() > 1 || stacks.isEmpty()) {
        String stackNames = stacks.stream().map(Stack::getStackName).collect(Collectors.joining(", "));
        final String msg = "More than one stack found or stack list is empty for the stack name: " +
                stackName + ": " + stackNames;
        logger.error(msg);
        throw new IllegalStateException(msg);
    }

    Stack stack = stacks.get(0);
    StackStatus stackStatus = StackStatus.fromValue(stack.getStackStatus());

    // Event details of the stack
    DescribeStackEventsRequest describeStackEventsRequest = new DescribeStackEventsRequest()
            .withStackName(stackName);
    DescribeStackEventsResult describeStackEventsResult = cloudFormation.
            describeStackEvents(describeStackEventsRequest);

    //Print a log of the current state of the resources
    StringBuilder stringBuilder = new StringBuilder();
    final List<StackEvent> originalStackEvents = describeStackEventsResult.getStackEvents();
    final List<StackEvent> newStackEvents = new ArrayList<>(originalStackEvents);
    newStackEvents.removeAll(prevStackEvents);
    ListIterator<StackEvent> li = newStackEvents.listIterator(newStackEvents.size());
    while (li.hasPrevious()) {
        StackEvent stackEvent = li.previous();
        stringBuilder.append(StringUtil.concatStrings(
                "Status: ", stackEvent.getResourceStatus(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Resource Type: ", stackEvent.getResourceType(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Logical ID: ", stackEvent.getLogicalResourceId(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Status Reason: ", Optional.ofNullable(stackEvent.getResourceStatusReason()).orElse("-")));
        stringBuilder.append("\n");
    }
    logger.info(StringUtil.concatStrings("\n", stringBuilder.toString()));
    prevStackEvents = originalStackEvents;

    //Determine the steps to execute based on the status of the stack
    switch (stackStatus) {
    case CREATE_COMPLETE:
        return true;
    case CREATE_IN_PROGRESS:
        break;
    default:
        throw new TestGridInfrastructureException(StringUtil.concatStrings(
                "Stack creation transitioned to ", stackStatus.toString(), " state."));
    }
    return false;
}
 
Example #27
Source File: CloudFormationClient.java    From herd-mdl with Apache License 2.0 4 votes vote down vote up
/**
 * Delete the stack {@link #stackName}
 */
public void deleteStack() throws Exception {

    CFTStackInfo cftStackInfo = getStackInfo();
    String rootStackId = cftStackInfo.stackId(); // Use the stack id to track the delete operation
    LOGGER.info("rootStackId   =   " + rootStackId);

    // Go through the stack and pick up resources that we want
    // to finalize before deleting the stack.
    List<String> s3BucketIds = new ArrayList<>();

    DescribeStacksResult describeStacksResult = amazonCloudFormation.describeStacks();
    for (Stack currentStack : describeStacksResult.getStacks()) {
        if (rootStackId.equals(currentStack.getRootId()) || rootStackId
                .equals(currentStack.getStackId())) {
            LOGGER.info("stackId   =   " + currentStack.getStackId());
            DescribeStackResourcesRequest describeStackResourcesRequest = new DescribeStackResourcesRequest();
            describeStackResourcesRequest.setStackName(currentStack.getStackName());
            List<StackResource> stackResources = amazonCloudFormation
                    .describeStackResources(describeStackResourcesRequest).getStackResources();
            for (StackResource stackResource : stackResources) {
                if (!stackResource.getResourceStatus()
                        .equals(ResourceStatus.DELETE_COMPLETE.toString())) {
                    if (stackResource.getResourceType().equals("AWS::S3::Bucket")) {
                        s3BucketIds.add(stackResource.getPhysicalResourceId());
                    }
                }
            }
        }
    }

    // Now empty S3 buckets, clean up will be done when the stack is deleted
    AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withRegion(Regions.getCurrentRegion().getName())
            .withCredentials(new InstanceProfileCredentialsProvider(true)).build();
    for (String s3BucketPhysicalId : s3BucketIds) {
        String s3BucketName = s3BucketPhysicalId;
        if(!amazonS3.doesBucketExistV2(s3BucketName)){
            break;
        }
        LOGGER.info("Empyting S3 bucket, " + s3BucketName);
        ObjectListing objectListing = amazonS3.listObjects(s3BucketName);
        while (true) {
            for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator
                    .hasNext(); ) {
                S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
                amazonS3.deleteObject(s3BucketName, summary.getKey());
            }
            if (objectListing.isTruncated()) {
                objectListing = amazonS3.listNextBatchOfObjects(objectListing);
            }
            else {
                break;
            }
        }
    }

    //Proceed with the regular stack deletion operation
    DeleteStackRequest deleteRequest = new DeleteStackRequest();
    deleteRequest.setStackName(stackName);
    amazonCloudFormation.deleteStack(deleteRequest);
    LOGGER.info("Stack deletion initiated");

    CFTStackStatus cftStackStatus = waitForCompletionAndGetStackStatus(amazonCloudFormation,
            rootStackId);
    LOGGER.info(
            "Stack deletion completed, the stack " + stackName + " completed with " + cftStackStatus);

    // Throw exception if failed
    if (!cftStackStatus.getStackStatus().equals(StackStatus.DELETE_COMPLETE.toString())) {
        throw new Exception(
                "deleteStack operation failed for stack " + stackName + " - " + cftStackStatus);
    }
}
 
Example #28
Source File: AmazonCloudFormationRetryClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public DescribeStacksResult describeStacks(DescribeStacksRequest request) {
    return retry.testWith2SecDelayMax15Times(() -> mapThrottlingError(() -> client.describeStacks(request)));
}