com.amazonaws.services.cloudformation.AmazonCloudFormation Java Examples

The following examples show how to use com.amazonaws.services.cloudformation.AmazonCloudFormation. 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: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackDoesNotExist() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.CREATE), Mockito.anyString(), Mockito.any());
}
 
Example #2
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 #3
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void describeChangeSet() {
	TaskListener taskListener = Mockito.mock(TaskListener.class);
	Mockito.when(taskListener.getLogger()).thenReturn(System.out);
	AmazonCloudFormation client = Mockito.mock(AmazonCloudFormation.class);
	DescribeChangeSetResult expected = new DescribeChangeSetResult()
			.withChanges(
					new Change()
			);
	Mockito.when(client.describeChangeSet(Mockito.any(DescribeChangeSetRequest.class))).thenReturn(expected);

	CloudFormationStack stack = new CloudFormationStack(client, "foo", taskListener);
	DescribeChangeSetResult result = stack.describeChangeSet("bar");
	Assertions.assertThat(result).isSameAs(expected);

	ArgumentCaptor<DescribeChangeSetRequest> captor = ArgumentCaptor.forClass(DescribeChangeSetRequest.class);
	Mockito.verify(client).describeChangeSet(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new DescribeChangeSetRequest()
															   .withStackName("foo")
															   .withChangeSetName("bar")
	);
}
 
Example #4
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteStackByStackNameOnly() 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));

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

	stack.delete(PollConfiguration.DEFAULT, null, null, null);

	ArgumentCaptor<DeleteStackRequest> captor = ArgumentCaptor.forClass(DeleteStackRequest.class);
	Mockito.verify(client).deleteStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new DeleteStackRequest()
			.withStackName("foo")

	);
	Mockito.verify(this.eventPrinter).waitAndPrintStackEvents(Mockito.eq("foo"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
}
 
Example #5
Source File: CloudformationStackTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteStack() 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));

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

	stack.delete(PollConfiguration.DEFAULT, new String[]{"myresourcetoretain"}, "myarn", "myclientrequesttoken");

	ArgumentCaptor<DeleteStackRequest> captor = ArgumentCaptor.forClass(DeleteStackRequest.class);
	Mockito.verify(client).deleteStack(captor.capture());
	Assertions.assertThat(captor.getValue()).isEqualTo(new DeleteStackRequest()
															   .withStackName("foo")
															   .withClientRequestToken("myclientrequesttoken")
															   .withRoleARN("myarn")
															   .withRetainResources("myresourcetoretain")

	);
	Mockito.verify(this.eventPrinter).waitAndPrintStackEvents(Mockito.eq("foo"), Mockito.any(Waiter.class), Mockito.eq(PollConfiguration.DEFAULT));
}
 
Example #6
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 #7
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createNonExistantStack() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	Mockito.when(stackSet.exists()).thenReturn(false);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo')"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet).create(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class), Mockito.isNull(String.class), Mockito.isNull(String.class));
}
 
Example #8
Source File: CFNExecuteChangeSetStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> run() throws Exception {
	final String changeSet = this.step.getChangeSet();
	final String stack = this.step.getStack();
	final TaskListener listener = this.getContext().get(TaskListener.class);

	Preconditions.checkArgument(changeSet != null && !changeSet.isEmpty(), "Change Set must not be null or empty");

	Preconditions.checkArgument(stack != null && !stack.isEmpty(), "Stack must not be null or empty");

	listener.getLogger().format("Executing CloudFormation change set %s %n", changeSet);

	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	CloudFormationStack cfnStack = new CloudFormationStack(client, stack, listener);
	Map<String, String> outputs = cfnStack.executeChangeSet(changeSet, Execution.this.step.getPollConfiguration());
	listener.getLogger().println("Execute change set complete");
	return outputs;
}
 
Example #9
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 #10
Source File: Cloudformation.java    From lambadaframework with MIT License 6 votes vote down vote up
public CloudFormationOutput getStackOutputs(AmazonCloudFormation stackbuilder,
                                            String stackName) {
    DescribeStacksRequest wait = new DescribeStacksRequest();
    wait.setStackName(stackName);
    List<Stack> stacks = getCloudFormationClient().describeStacks(wait).getStacks();

    CloudFormationOutput cloudFormationOutput = new CloudFormationOutput();

    for (Stack stack : stacks) {
        if (stack.getStackName().equals(stackName)) {
            stack.getOutputs().forEach(output -> {
                if (output.getOutputKey().equals(LAMBDA_EXECUTION_IAM_RESOURCE_NAME)) {
                    cloudFormationOutput.setLambdaExecutionRole(output.getOutputValue());
                }

                if (output.getOutputKey().equals(LAMBDA_EXECUTION_NAME)) {
                    cloudFormationOutput.setLambdaFunctionArn(output.getOutputValue());
                }
            });
            return cloudFormationOutput;
        }
    }
    throw new RuntimeException("Unknown Cloudformation error. Try deploying.");

}
 
Example #11
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void updateExistingStackWithCustomAdminRole() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(stackSet.exists()).thenReturn(true);
	String operationId = UUID.randomUUID().toString();
	Mockito.when(stackSet.update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class)))
			.thenReturn(new UpdateStackSetResult()
					.withOperationId(operationId)
			);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo', administratorRoleArn: 'bar', executionRoleName: 'baz')"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet).update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class));
}
 
Example #12
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 #13
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void updateChangeSetWithRawTemplate() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', template: 'foobaz')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.eq("foobaz"), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.CREATE), Mockito.anyString(), Mockito.any());
}
 
Example #14
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackExists() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(), Mockito.any());
}
 
Example #15
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 #16
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackParametersFromMap() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', params: ['foo': 'bar', 'baz': 'true'])\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.eq(Arrays.asList(
			new Parameter().withParameterKey("foo").withParameterValue("bar"),
			new Parameter().withParameterKey("baz").withParameterValue("true")
	)), Mockito.anyCollectionOf(Tag.class), Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(),
											   Mockito.any());
}
 
Example #17
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testInjectCredentialsAndInvokeWithError() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final DescribeStackEventsRequest request = mock(DescribeStackEventsRequest.class);

    final AmazonCloudFormation client = mock(AmazonCloudFormation.class);
    when(client.describeStackEvents(any(DescribeStackEventsRequest.class))).thenThrow(new RuntimeException("Sorry"));

    final RuntimeException expectedException = assertThrows(RuntimeException.class,
        () -> proxy.injectCredentialsAndInvoke(request, client::describeStackEvents), "Expected Runtime Exception.");
    assertEquals(expectedException.getMessage(), "Sorry");

    // ensure credentials are injected and then removed
    verify(request).setRequestCredentialsProvider(any(AWSStaticCredentialsProvider.class));
    verify(request).setRequestCredentialsProvider(eq(null));
}
 
Example #18
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 #19
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 #20
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 #21
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AmazonCloudFormation amazonCloudFormation() {
    return decorateWithConfigsAndBuild(
        AmazonCloudFormationClientBuilder.standard(),
        LocalstackDocker::getEndpointCloudFormation
    );
}
 
Example #22
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 #23
Source File: ContextStackAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(StackResourceRegistry.class)
@ConditionalOnBean(StackNameProvider.class)
public StackResourceRegistryFactoryBean stackResourceRegistryFactoryBean(
		AmazonCloudFormation amazonCloudFormation,
		StackNameProvider stackNameProvider) {
	return new StackResourceRegistryFactoryBean(amazonCloudFormation,
			stackNameProvider);
}
 
Example #24
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 #25
Source File: CFNExecuteChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void executeChangeSet() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  cfnExecuteChangeSet(stack: 'foo', changeSet: 'bar')"
													+ "}\n", true)
	);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).executeChangeSet(Mockito.eq("bar"), Mockito.any(PollConfiguration.class));
}
 
Example #26
Source File: CloudFormationUtils.java    From amazon-kinesis-connectors with Apache License 2.0 5 votes vote down vote up
private static StackStatus stackStatus(AmazonCloudFormation client, String stackName) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);
    // describeStacks (with stack name specified) will return list of size 1 if found
    // and throw AmazonServiceException if no stack with that name exists
    try {
        return StackStatus.fromValue(client.describeStacks(describeStacksRequest)
                .getStacks()
                .get(0)
                .getStackStatus());
    } catch (AmazonServiceException ase) {
        return null;
    }
}
 
Example #27
Source File: ContextStackAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "cloud.aws.stack.auto", havingValue = "true",
		matchIfMissing = true)
public StackNameProvider autoDetectingStackNameProvider(
		AmazonCloudFormation amazonCloudFormation,
		ObjectProvider<AmazonEC2> amazonEC2) {
	return new AutoDetectingStackNameProvider(amazonCloudFormation,
			amazonEC2.getIfAvailable());
}
 
Example #28
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void updateExistantStack() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(stackSet.exists()).thenReturn(true);
	String operationId = UUID.randomUUID().toString();
	Mockito.when(stackSet.update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class)))
			.thenReturn(new UpdateStackSetResult()
					.withOperationId(operationId)
			);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo', pollInterval: 27, params: ['foo=bar'], paramsFile: 'params.json')"
			+ "}\n", true)
	);
	try (PrintWriter writer = new PrintWriter(jenkinsRule.jenkins.getWorkspaceFor(job).child("params.json").write())) {
		writer.println("[{\"ParameterKey\": \"foo1\", \"ParameterValue\": \"25\"}]");
	}
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	ArgumentCaptor<UpdateStackSetRequest> requestCapture = ArgumentCaptor.forClass(UpdateStackSetRequest.class);
	Mockito.verify(stackSet).update(Mockito.anyString(), Mockito.anyString(), requestCapture.capture());
	Assertions.assertThat(requestCapture.getValue().getParameters()).containsExactlyInAnyOrder(
			new Parameter()
					.withParameterKey("foo")
					.withParameterValue("bar"),
			new Parameter()
					.withParameterKey("foo1")
					.withParameterValue("25")
	);

	Mockito.verify(stackSet).waitForOperationToComplete(operationId, Duration.ofMillis(27));
}
 
Example #29
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void updateExistingStackStackSetWithOperationPreferences() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(stackSet.exists()).thenReturn(true);
	String operationId = UUID.randomUUID().toString();
	Mockito.when(stackSet.update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class)))
			.thenReturn(new UpdateStackSetResult()
					.withOperationId(operationId)
			);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo', operationPreferences: [failureToleranceCount: 5, regionOrder: ['us-west-2'], failureTolerancePercentage: 17, maxConcurrentCount: 18, maxConcurrentPercentage: 34])"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	ArgumentCaptor<UpdateStackSetRequest> requestCapture = ArgumentCaptor.forClass(UpdateStackSetRequest.class);
	Mockito.verify(stackSet).update(Mockito.anyString(), Mockito.anyString(), requestCapture.capture());

	Assertions.assertThat(requestCapture.getValue().getOperationPreferences()).isEqualTo(new StackSetOperationPreferences()
			.withFailureToleranceCount(5)
               .withRegionOrder("us-west-2")
			.withFailureTolerancePercentage(17)
			.withMaxConcurrentCount(18)
			.withMaxConcurrentPercentage(34)
	);

	Mockito.verify(stackSet).waitForOperationToComplete(operationId, Duration.ofSeconds(1));
}
 
Example #30
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setupSdk() throws Exception {
	stackSet = Mockito.mock(CloudFormationStackSet.class);
	PowerMockito.mockStatic(AWSClientFactory.class);
	PowerMockito.whenNew(CloudFormationStackSet.class)
			.withAnyArguments()
			.thenReturn(stackSet);
	AmazonCloudFormation cloudFormation = Mockito.mock(AmazonCloudFormation.class);
	PowerMockito.when(AWSClientFactory.create(Mockito.any(AwsSyncClientBuilder.class), Mockito.any(EnvVars.class)))
			.thenReturn(cloudFormation);
}