

# Delete a CA for AWS IAM for agents and workloads

This Java example deletes a multi-Region certificate authority (CA) for AWS IAM for agents and workloads in the required order. It lists the CA's replicas, disables each `ACTIVE` replica, and deletes each replica in its own Region. It skips a replica that is already `DELETED`. It then waits until every remaining replica is `FAILED` or no replicas remain, and deletes the primary CA with a 7-day restoration period. You can't restore a replica. Before you run the example, detach the CA from the workload identity provider in IAM, and confirm that the CA has no associations. For instructions, see [Tear down a CA for AWS IAM for agents and workloads](PcaWorkloadIdentity-teardown.md).

Run the example as `DeleteWorkloadIdentityCA {{primary-ca-arn}}`, where {{primary-ca-arn}} is the Amazon Resource Name (ARN) of the primary CA. The example prints a line for each replica that it deletes. It then prints the ARN of the deleted primary CA and the number of days during which you can restore it.

**Important**  
This example deletes a private CA and all of its replicas. You are not charged for a private CA after you delete it. However, if you restore the primary CA, you are charged for the time between deletion and restoration.  
For the latest AWS Private CA pricing information, see [AWS Private Certificate Authority Pricing](https://aws.amazon.com/private-ca/pricing/). You can also use the [AWS pricing calculator](https://calculator.aws/#/createCalculator/certificateManager) to estimate costs. 

```java
package com.amazonaws.samples.workloadidentity;

import java.time.Duration;
import java.time.Instant;
import java.util.List;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.acmpca.AcmPcaClient;
import software.amazon.awssdk.services.acmpca.model.AcmPcaException;
import software.amazon.awssdk.services.acmpca.model.CertificateAuthorityStatus;
import software.amazon.awssdk.services.acmpca.model.DeleteCertificateAuthorityRequest;
import software.amazon.awssdk.services.acmpca.model.DescribeCertificateAuthorityRequest;
import software.amazon.awssdk.services.acmpca.model.ListCertificateAuthorityReplicasRequest;
import software.amazon.awssdk.services.acmpca.model.Replica;
import software.amazon.awssdk.services.acmpca.model.UpdateCertificateAuthorityRequest;

/**
 * Deletes a multi-Region service-affiliated CA for AWS IAM for agents and workloads: first every
 * replica in its own Region, and then the primary CA with a 7-day restoration period.
 */
public class DeleteWorkloadIdentityCA {

    private static final Duration POLL_INTERVAL = Duration.ofSeconds(5);
    private static final Duration TIMEOUT = Duration.ofMinutes(10);

    // The primary CA can be restored for this many days after you delete it. Replicas can't be
    // restored. You create them again instead.
    private static final int PERMANENT_DELETION_TIME_IN_DAYS = 7;

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage: DeleteWorkloadIdentityCA <primary-ca-arn>");
            System.exit(1);
        }
        String primaryCaArn = args[0];
        Region primaryRegion = Region.of(primaryCaArn.split(":")[3]);

        // Before you delete the CA, remove it from your workload identity provider's outbound
        // signers in IAM, so that workloads stop requesting certificates from it.
        try (AcmPcaClient primary = AcmPcaClient.builder().region(primaryRegion).build()) {
            ListCertificateAuthorityReplicasRequest listRequest = ListCertificateAuthorityReplicasRequest.builder()
                    .certificateAuthorityArn(primaryCaArn)
                    .build();

            // Delete each replica in its own Region. A replica delete takes no restoration
            // period: issuance stops in that Region at once. A replica that can't be deleted
            // doesn't stop the others; the wait below reports any replica that remains.
            for (Replica replica : primary.listCertificateAuthorityReplicasPaginator(listRequest).replicas()) {
                if (replica.status() == CertificateAuthorityStatus.DELETED) {
                    continue;
                }
                try (AcmPcaClient regional = AcmPcaClient.builder().region(Region.of(replica.region())).build()) {
                    deleteCertificateAuthority(regional, replica.arn(), null);
                    System.out.println("Deleted replica in " + replica.region());
                } catch (AcmPcaException e) {
                    System.err.println("Couldn't delete the replica in " + replica.region() + ": "
                            + e.awsErrorDetails().errorMessage());
                }
            }

            // The primary can't be deleted until every replica is DELETED or FAILED, so wait until
            // no other replica is listed. Deleted replicas are omitted from the list.
            Instant deadline = Instant.now().plus(TIMEOUT);
            List<Replica> remaining;
            while (!(remaining = primary.listCertificateAuthorityReplicasPaginator(listRequest).replicas().stream().toList())
                    .stream().allMatch(replica -> replica.status() == CertificateAuthorityStatus.FAILED
                            || replica.status() == CertificateAuthorityStatus.DELETED)) {
                if (Instant.now().isAfter(deadline)) {
                    System.err.println("Replicas still exist: " + remaining);
                    System.exit(1);
                }
                Thread.sleep(POLL_INTERVAL.toMillis());
            }

            deleteCertificateAuthority(primary, primaryCaArn, PERMANENT_DELETION_TIME_IN_DAYS);
            System.out.println("Deleted primary CA " + primaryCaArn
                    + ". You can restore it for " + PERMANENT_DELETION_TIME_IN_DAYS + " days.");
        } catch (AcmPcaException e) {
            // Print the error message from AWS Private CA, such as why it rejected the request.
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Deletes a replica or the primary. A CA that is still CREATING can't be deleted yet, so wait
    // for it to finish. Only an ACTIVE CA must be disabled first; a DISABLED, FAILED, or
    // PENDING_CERTIFICATE CA can be deleted directly. Only the primary takes a restoration period.
    private static void deleteCertificateAuthority(AcmPcaClient client, String caArn, Integer permanentDeletionTimeInDays)
            throws InterruptedException {
        DescribeCertificateAuthorityRequest describeRequest = DescribeCertificateAuthorityRequest.builder()
                .certificateAuthorityArn(caArn)
                .build();
        CertificateAuthorityStatus status = client.describeCertificateAuthority(describeRequest)
                .certificateAuthority()
                .status();
        Instant deadline = Instant.now().plus(TIMEOUT);
        while (status == CertificateAuthorityStatus.CREATING && Instant.now().isBefore(deadline)) {
            Thread.sleep(POLL_INTERVAL.toMillis());
            status = client.describeCertificateAuthority(describeRequest).certificateAuthority().status();
        }
        if (status == CertificateAuthorityStatus.ACTIVE) {
            client.updateCertificateAuthority(UpdateCertificateAuthorityRequest.builder()
                    .certificateAuthorityArn(caArn)
                    .status(CertificateAuthorityStatus.DISABLED)
                    .build());
        }
        client.deleteCertificateAuthority(DeleteCertificateAuthorityRequest.builder()
                .certificateAuthorityArn(caArn)
                .permanentDeletionTimeInDays(permanentDeletionTimeInDays)
                .build());
    }
}
```