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

The following examples show how to use com.amazonaws.services.cloudformation.model.DescribeStacksRequest. 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: 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 #2
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 #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: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public CreatedCloudNetwork createNetworkWithSubnets(NetworkCreationRequest networkRequest) {
    AwsCredentialView credentialView = new AwsCredentialView(networkRequest.getCloudCredential());
    AmazonCloudFormationRetryClient cloudFormationRetryClient = getCloudFormationRetryClient(credentialView, networkRequest.getRegion().value());
    List<SubnetRequest> subnetRequests = getCloudSubNets(networkRequest);
    String cfStackName = networkRequest.getStackName();
    try {
        cloudFormationRetryClient.describeStacks(new DescribeStacksRequest().withStackName(cfStackName));
        LOGGER.warn("AWS CloudFormation stack for Network with stack name: '{}' already exists. Attaching this one to the network.", cfStackName);
        return getCreatedNetworkWithPolling(networkRequest, credentialView, cloudFormationRetryClient, subnetRequests);
    } catch (AmazonServiceException e) {
        if (networkDoesNotExist(e)) {
            LOGGER.warn("{} occurred during describe AWS CloudFormation stack for Network with stack name: '{}'. "
                    + "Assuming the CF Stack does not exist, so creating a new one. Exception message: {}", e.getClass(), cfStackName, e.getMessage());
            String cloudFormationTemplate = createTemplate(networkRequest, subnetRequests);
            return createNewCfNetworkStack(networkRequest, credentialView, cloudFormationRetryClient, cloudFormationTemplate, subnetRequests);
        } else {
            throw new CloudConnectorException("Failed to create network.", e);
        }
    }
}
 
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: EventPrinter.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
void waitAndPrintStackEvents(String stack, Waiter<DescribeStacksRequest> waiter, PollConfiguration pollConfiguration) throws ExecutionException {

		final BasicFuture<AmazonWebServiceRequest> waitResult = new BasicFuture<>(null);

		waiter.runAsync(new WaiterParameters<>(new DescribeStacksRequest().withStackName(stack)).withPollingStrategy(this.pollingStrategy(pollConfiguration)), new WaiterHandler() {
			@Override
			public void onWaitSuccess(AmazonWebServiceRequest request) {
				waitResult.completed(request);
			}

			@Override
			public void onWaitFailure(Exception e) {
				waitResult.failed(e);
			}
		});
		this.waitAndPrintEvents(stack, pollConfiguration, waitResult);
	}
 
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: 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 #11
Source File: AwsTerminateService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void waitAndDeleteCloudformationStack(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources,
        AmazonCloudFormationClient amazonCloudFormationClient) {
    CloudResource stackResource = cfStackUtil.getCloudFormationStackResource(resources);
    if (stackResource == null) {
        LOGGER.debug("No cloudformation stack in resources");
        return;
    }
    String cFStackName = stackResource.getName();
    AmazonCloudFormationRetryClient cfRetryClient = awsClient.createCloudFormationRetryClient(amazonCloudFormationClient);
    LOGGER.debug("Search and wait stack with name: {}", cFStackName);
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(cFStackName);
    try {
        retryService.testWith2SecDelayMax15Times(() -> isStackExist(cfRetryClient, cFStackName, describeStacksRequest));
    } catch (ActionFailedException ignored) {
        LOGGER.debug("Stack not found with name: {}", cFStackName);
        return;
    }

    resumeAutoScalingPolicies(ac, stack);
    LOGGER.debug("Delete cloudformation stack from resources");
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName(cFStackName);
    cfRetryClient.deleteStack(deleteStackRequest);
    Waiter<DescribeStacksRequest> stackDeleteCompleteWaiter = amazonCloudFormationClient.waiters().stackDeleteComplete();
    try {
        WaiterParameters<DescribeStacksRequest> describeStacksRequestWaiterParameters = new WaiterParameters<>(describeStacksRequest)
                .withPollingStrategy(getBackoffCancellablePollingStrategy(null));
        stackDeleteCompleteWaiter.run(describeStacksRequestWaiterParameters);
    } catch (Exception e) {
        LOGGER.debug("Cloudformation stack delete failed ", e);
        throw new CloudConnectorException(e.getMessage(), e);
    }
    LOGGER.debug("Cloudformation stack from resources has been deleted");
}
 
Example #12
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 #13
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 #14
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 #15
Source File: WaitForStackToReachStateTask.java    From aws-ant-tasks with Apache License 2.0 5 votes vote down vote up
public static boolean waitForCloudFormationStackToReachStatus(
        AmazonCloudFormationClient client, String stackName, String status) {
    int count = 0;
    while (true) {
        if (count++ == 100) {
            System.out
                    .println(stackName + " never reached state " + status);
            return false;
        }
        try {
            Thread.sleep(1000 * 30);
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
            return false;
        }
        String stackStatus = client
                .describeStacks(
                        new DescribeStacksRequest()
                                .withStackName(stackName)).getStacks()
                .get(0).getStackStatus();
        if (stackStatus.equals(status)) {
            return true;
        } else if (stackStatus.contains(FAILED)) {
            System.out.println("The process failed with status " + stackStatus);
            return false;
        }
        System.out.println(stackName + " is in status " + stackStatus);
    }
}
 
Example #16
Source File: CloudFormationStackUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getOutputs(String cFStackName, AmazonCloudFormationRetryClient client) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(cFStackName);
    String outputNotFound = String.format("Couldn't get Cloudformation stack's('%s') output", cFStackName);
    List<Output> cfStackOutputs = client.describeStacks(describeStacksRequest).getStacks()
            .stream().findFirst().orElseThrow(getCloudConnectorExceptionSupplier(outputNotFound)).getOutputs();
    return cfStackOutputs.stream().collect(Collectors.toMap(Output::getOutputKey, Output::getOutputValue));
}
 
Example #17
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 #18
Source File: AwsTerminateService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Boolean isStackExist(AmazonCloudFormationRetryClient cfRetryClient, String cFStackName, DescribeStacksRequest describeStacksRequest) {
    try {
        cfRetryClient.describeStacks(describeStacksRequest);
    } catch (AmazonServiceException e) {
        if (!e.getErrorMessage().contains(cFStackName + " does not exist")) {
            throw e;
        }
        throw new ActionFailedException("Stack not exists");
    }
    return Boolean.TRUE;
}
 
Example #19
Source File: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private CreatedCloudNetwork getCreatedNetworkWithPolling(NetworkCreationRequest networkRequest, AwsCredentialView credentialView,
        AmazonCloudFormationRetryClient cloudFormationRetryClient, List<SubnetRequest> subnetRequests) {

    AmazonCloudFormationClient cfClient = awsClient.createCloudFormationClient(credentialView, networkRequest.getRegion().value());
    Waiter<DescribeStacksRequest> creationWaiter = cfClient.waiters().stackCreateComplete();
    DescribeStacksRequest stackRequestWithStackId = new DescribeStacksRequest().withStackName(networkRequest.getStackName());
    EnvironmentCancellationCheck environmentCancellationCheck = new EnvironmentCancellationCheck(networkRequest.getEnvId(), networkRequest.getEnvName());

    run(creationWaiter, stackRequestWithStackId,
            environmentCancellationCheck);

    return getCreatedCloudNetwork(cloudFormationRetryClient, networkRequest, subnetRequests);
}
 
Example #20
Source File: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteNetworkWithSubnets(NetworkDeletionRequest networkDeletionRequest) {
    if (!networkDeletionRequest.isExisting()) {
        AwsCredentialView credentialView = new AwsCredentialView(networkDeletionRequest.getCloudCredential());
        AmazonCloudFormationRetryClient cloudFormationRetryClient = getCloudFormationRetryClient(credentialView, networkDeletionRequest.getRegion());
        DeleteStackRequest deleteStackRequest = new DeleteStackRequest();
        deleteStackRequest.setStackName(networkDeletionRequest.getStackName());
        cloudFormationRetryClient.deleteStack(deleteStackRequest);
        AmazonCloudFormationClient cfClient = awsClient.createCloudFormationClient(credentialView, networkDeletionRequest.getRegion());
        Waiter<DescribeStacksRequest> deletionWaiter = cfClient.waiters().stackDeleteComplete();
        LOGGER.debug("CloudFormation stack deletion request sent with stack name: '{}' ", networkDeletionRequest.getStackName());
        DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(networkDeletionRequest.getStackName());
        run(deletionWaiter, describeStacksRequest, null);
    }
}
 
Example #21
Source File: AwsStackValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(AuthenticatedContext ac, CloudStack cloudStack) {
    AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential());
    String regionName = ac.getCloudContext().getLocation().getRegion().value();
    AmazonCloudFormationRetryClient cfClient = awsClient.createCloudFormationRetryClient(credentialView, regionName);
    String cFStackName = cfStackUtil.getCfStackName(ac);
    try {
        cfClient.describeStacks(new DescribeStacksRequest().withStackName(cFStackName));
        throw new CloudConnectorException(String.format("Stack is already exists with the given name: %s", cFStackName));
    } catch (AmazonServiceException ignored) {

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

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

    CreatedCloudNetwork actual = underTest.createNetworkWithSubnets(networkCreationRequest);

    verify(awsClient).createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(awsNetworkCfTemplateProvider).provide(networkCreationRequest, subnetRequestList);
    verify(awsClient).createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(creationWaiter, times(1)).run(any());
    verify(awsTaggingService).prepareCloudformationTags(any(), any());
    verify(cloudFormationRetryClient).createStack(any(CreateStackRequest.class));
    verify(cfStackUtil).getOutputs(NETWORK_ID, cloudFormationRetryClient);
    assertEquals(VPC_ID, actual.getNetworkId());
    assertEquals(NUMBER_OF_SUBNETS, actual.getSubnets().size());
}
 
Example #23
Source File: CloudFormationUtils.java    From amazon-kinesis-connectors with Apache License 2.0 5 votes vote down vote up
private static boolean stackExists(AmazonCloudFormation client, String stackName) {
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
    describeStacksRequest.setStackName(stackName);
    try {
        client.describeStacks(describeStacksRequest);
        return true;
    } catch (AmazonServiceException e) {
        return false;
    }
}
 
Example #24
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 #25
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 #26
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 #27
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;
}
 
Example #28
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 #29
Source File: AWSProvider.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 * This method releases the provisioned AWS infrastructure.
 *
 * @param script            the script config
 * @param inputs
 * @return true or false to indicate the result of destroy operation.
 * @throws TestGridInfrastructureException when AWS error occurs in deletion process.
 * @throws InterruptedException            when there is an interruption while waiting for the result.
 */
private boolean doRelease(Script script, Properties inputs, TestPlan testPlan)
        throws TestGridInfrastructureException, InterruptedException, TestGridDAOException {
    Path configFilePath;
    String stackName = script.getName();
    String region = inputs.getProperty(AWS_REGION_PARAMETER);
    configFilePath = TestGridUtil.getConfigFilePath();
    AmazonCloudFormation stackdestroy = AmazonCloudFormationClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest();
    deleteStackRequest.setStackName(stackName);
    stackdestroy.deleteStack(deleteStackRequest);
    logger.info(StringUtil.concatStrings("Stack : ", stackName, " is handed over for deletion!"));

    //Notify AWSResourceManager about stack destruction to release acquired resources
    AWSResourceManager awsResourceManager = new AWSResourceManager();
    awsResourceManager.notifyStackDeletion(testPlan, script, region);

    boolean waitForStackDeletion = Boolean
            .parseBoolean(getProperty(ConfigurationProperties.WAIT_FOR_STACK_DELETION));
    if (waitForStackDeletion) {
        logger.info(StringUtil.concatStrings("Waiting for stack : ", stackName, " to delete.."));
        Waiter<DescribeStacksRequest> describeStacksRequestWaiter = new
                AmazonCloudFormationWaiters(stackdestroy).stackDeleteComplete();
        try {
            describeStacksRequestWaiter.run(new WaiterParameters<>(new DescribeStacksRequest()
                    .withStackName(stackName)));
        } catch (WaiterUnrecoverableException e) {

            throw new TestGridInfrastructureException("Error occurred while waiting for Stack :"
                                                      + stackName + " deletion !");
        }
    }
    return true;
}
 
Example #30
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;
}