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

The following examples show how to use com.amazonaws.services.cloudformation.model.StackResource. 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: LambdaVersionCleanupStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void deleteAllStackFunctionVersions(AWSLambda client, String stackName) throws Exception  {
	TaskListener listener = Execution.this.getContext().get(TaskListener.class);
	listener.getLogger().format("Deleting old versions from stackName=%s%n", stackName);
	AmazonCloudFormation cloudformation = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), this.getContext());
	DescribeStackResourcesResult result = cloudformation.describeStackResources(new DescribeStackResourcesRequest()
			.withStackName(stackName)
	);
	for (StackResource stackResource : result.getStackResources()) {
		if ("AWS::Lambda::Function".equals(stackResource.getResourceType())) {
			deleteAllVersions(client, stackResource.getPhysicalResourceId());
		}
	}
}
 
Example #2
Source File: LambdaVersionCleanupStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteCloudFormationStack() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.awsLambda.listAliases(Mockito.eq(new ListAliasesRequest().withFunctionName("foo")))).thenReturn(new ListAliasesResult());
	Mockito.when(this.awsLambda.listVersionsByFunction(Mockito.eq(new ListVersionsByFunctionRequest().withFunctionName("foo")))).thenReturn(new ListVersionsByFunctionResult()
			.withVersions(Arrays.asList(
					new FunctionConfiguration().withVersion("v1").withLastModified(ZonedDateTime.now().format(DateTimeFormatter.ISO_ZONED_DATE_TIME)),
					new FunctionConfiguration().withVersion("v2").withLastModified("2018-02-05T11:15:12Z")
					))
			);
	Mockito.when(this.cloudformation.describeStackResources(new DescribeStackResourcesRequest().withStackName("baz"))).thenReturn(new DescribeStackResourcesResult().withStackResources(
				new StackResource()
				.withResourceType("AWS::Lambda::Function")
				.withPhysicalResourceId("foo"),
				new StackResource()
				.withResourceType("AWS::Baz::Function")
				.withPhysicalResourceId("bar")
				)
			);
	job.setDefinition(new CpsFlowDefinition(""
				+ "node {\n"
				+ "  lambdaVersionCleanup(stackName: 'baz', daysAgo: 5)\n"
				+ "}\n", true)
			);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.awsLambda).deleteFunction(new DeleteFunctionRequest()
			.withQualifier("v2")
			.withFunctionName("foo")
			);
	Mockito.verify(this.awsLambda).listVersionsByFunction(Mockito.any());
	Mockito.verify(this.awsLambda).listAliases(Mockito.any());
	Mockito.verifyNoMoreInteractions(this.awsLambda);
}
 
Example #3
Source File: TestStackEnvironment.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
protected String getByLogicalId(String id) {
	for (StackResource stackResource : this.stackResources.getStackResources()) {
		if (stackResource.getLogicalResourceId().equals(id)) {
			return stackResource.getPhysicalResourceId();
		}
	}
	return null;
}
 
Example #4
Source File: AutoScalingGroupHandler.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public Map<AutoScalingGroup, String> getAutoScalingGroups(AmazonCloudFormationClient cloudFormationClient, AmazonAutoScalingClient autoScalingClient,
        CloudResource cfResource) {
    DescribeStackResourcesRequest resourcesRequest = new DescribeStackResourcesRequest();
    resourcesRequest.setStackName(cfResource.getName());
    DescribeStackResourcesResult resourcesResult = cloudFormationClient.describeStackResources(resourcesRequest);
    Map<String, String> autoScalingGroups = resourcesResult.getStackResources().stream()
            .filter(stackResource -> "AWS::AutoScaling::AutoScalingGroup".equalsIgnoreCase(stackResource.getResourceType()))
            .collect(Collectors.toMap(StackResource::getPhysicalResourceId, StackResource::getLogicalResourceId));
    DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest();
    request.setAutoScalingGroupNames(autoScalingGroups.keySet());
    List<AutoScalingGroup> scalingGroups = autoScalingClient.describeAutoScalingGroups(request).getAutoScalingGroups();
    return scalingGroups.stream()
            .collect(Collectors.toMap(scalingGroup -> scalingGroup, scalingGroup -> autoScalingGroups.get(scalingGroup.getAutoScalingGroupName())));
}
 
Example #5
Source File: AutoScalingGroupHandlerTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAutoScalingGroups() {
    CloudResource cfResource = CloudResource.builder()
            .type(ResourceType.CLOUDFORMATION_STACK)
            .name("cf")
            .build();
    DescribeStackResourcesResult resourcesResult = new DescribeStackResourcesResult();
    StackResource stackResource = new StackResource()
            .withLogicalResourceId("logicalResourceId")
            .withPhysicalResourceId("physicalResourceId")
            .withResourceType("AWS::AutoScaling::AutoScalingGroup");
    resourcesResult.getStackResources().add(stackResource);
    resourcesResult.getStackResources().add(new StackResource().withResourceType("other"));
    when(cloudFormationClient.describeStackResources(any(DescribeStackResourcesRequest.class))).thenReturn(resourcesResult);

    DescribeAutoScalingGroupsResult scalingGroupsResult = new DescribeAutoScalingGroupsResult();
    AutoScalingGroup autoScalingGroup = new AutoScalingGroup().withAutoScalingGroupName(stackResource.getPhysicalResourceId());
    scalingGroupsResult.getAutoScalingGroups().add(autoScalingGroup);
    when(autoScalingClient.describeAutoScalingGroups(any(DescribeAutoScalingGroupsRequest.class))).thenReturn(scalingGroupsResult);

    Map<AutoScalingGroup, String> autoScalingGroups = underTest.getAutoScalingGroups(cloudFormationClient, autoScalingClient, cfResource);
    assertEquals(1, autoScalingGroups.size());
    assertEquals(autoScalingGroup, autoScalingGroups.entrySet().stream().findFirst().get().getKey());
    assertEquals(stackResource.getLogicalResourceId(), autoScalingGroups.entrySet().stream().findFirst().get().getValue());

    ArgumentCaptor<DescribeStackResourcesRequest> stackResourcesRequestArgumentCaptor = ArgumentCaptor.forClass(DescribeStackResourcesRequest.class);
    verify(cloudFormationClient).describeStackResources(stackResourcesRequestArgumentCaptor.capture());
    assertEquals(cfResource.getName(), stackResourcesRequestArgumentCaptor.getValue().getStackName());

    ArgumentCaptor<DescribeAutoScalingGroupsRequest> scalingGroupsRequestArgumentCaptor = ArgumentCaptor.forClass(DescribeAutoScalingGroupsRequest.class);
    verify(autoScalingClient).describeAutoScalingGroups(scalingGroupsRequestArgumentCaptor.capture());
    assertEquals(1, scalingGroupsRequestArgumentCaptor.getValue().getAutoScalingGroupNames().size());
    assertEquals(stackResource.getPhysicalResourceId(), scalingGroupsRequestArgumentCaptor.getValue().getAutoScalingGroupNames().get(0));
}
 
Example #6
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);
    }
}