Search code examples
amazon-web-servicesamazon-kmslocalstackaws-sdk-java-2.0

How do I set up LocalStackContainer for KMS using the AWS Java SDK v2?


My KMSClient is being instantiated way before LocalStack is started and I don't know how I should initialise my KmsClientBuilder to override the endpoint.

KmsClient.builder().endpointOverride("some sort of static value")).build();

LocalStackContainer = new LocalStackContainer(DockerImageName.parse("localstack/localstack:2.3.0").withServices(LocalStackContainer.Service.KMS)

Solution

  • You should instantiate the LocalStack container first before trying to create a KMS client.

    Then as per docs, you need to instantiate your client(s) with the right:

    • endpoint
    • credentials
    • region

    For KMS (and other clients), this should work:

    import org.testcontainers.containers.localstack.LocalStackContainer;
    import org.testcontainers.utility.DockerImageName;
    import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
    import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
    import software.amazon.awssdk.regions.Region;
    import software.amazon.awssdk.services.kms.KmsClient;
    ...
    
    DockerImageName image = DockerImageName.parse("localstack/localstack:2.3.0");
    
    LocalStackContainer container = new LocalStackContainer(image)
            .withServices(LocalStackContainer.Service.KMS);
    
    KmsClient client = KmsClient.builder()
            .endpointOverride(container.getEndpoint())
            .credentialsProvider(
                    StaticCredentialsProvider.create(
                            AwsBasicCredentials.create(container.getAccessKey(), container.getSecretKey())
                    )
            )
            .region(Region.of(container.getRegion()))
            .build();