Skip to content

AWS Emulator

AWS Emulator is a local emulator of the AWS APIs. It runs a single HTTPS endpoint, generates a self-signed certificate and credentials during the startup, and requires each request to be signed with these credentials.

Note

AWS does not publish an official AWS Emulator image yet. The examples use an unofficial community image. Any image works as long as it uses the aws-emulator executable as its entrypoint.

Add the following dependency to your project file:

NuGet
1
dotnet add package Testcontainers.AwsEmulator

You can start an AWS Emulator container instance from any .NET application. This example uses the default configuration:

1
private readonly AwsEmulatorContainer _awsEmulatorContainer = new AwsEmulatorBuilder(TestSession.GetImageFromDockerfile()).Build();

This example uses xUnit.net's IAsyncLifetime interface to manage the lifecycle of the container. The container is started in the InitializeAsync method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the DisposeAsync method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public async ValueTask InitializeAsync()
{
    await _awsEmulatorContainer.StartAsync()
        .ConfigureAwait(false);

    // The emulator generates the certificate and the credentials during the
    // startup. Read them after the container has started.
    var certificate = await _awsEmulatorContainer.GetCertificateAsync(TestContext.Current.CancellationToken)
        .ConfigureAwait(true);

    var credentials = await _awsEmulatorContainer.GetCredentialsAsync(TestContext.Current.CancellationToken)
        .ConfigureAwait(true);

    _httpClientFactory = new AwsEmulatorHttpClientFactory(certificate);
    _awsCredentials = new BasicAWSCredentials(credentials.AccessKey, credentials.SecretKey);
}

public async ValueTask DisposeAsync()
{
    _httpClientFactory?.Dispose();

    await _awsEmulatorContainer.DisposeAsync()
        .ConfigureAwait(false);
}

[Fact]
[Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))]
[Trait(AwsService, "s3")]
public async Task GetObjectReturnsPutObject()
{
    // Given
    const string helloWorld = "Hello, World!";

    var bucketName = Guid.NewGuid().ToString("D");

    var objectKey = Guid.NewGuid().ToString("D");

    var config = new AmazonS3Config();
    config.ServiceURL = _awsEmulatorContainer.GetConnectionString();
    config.AuthenticationRegion = AwsEmulatorBuilder.Region;
    config.HttpClientFactory = _httpClientFactory;
    config.ForcePathStyle = true;

    using var client = new AmazonS3Client(_awsCredentials, config);

    var putObjectRequest = new PutObjectRequest();
    putObjectRequest.BucketName = bucketName;
    putObjectRequest.Key = objectKey;
    putObjectRequest.ContentBody = helloWorld;

    // When
    _ = await client.PutBucketAsync(bucketName, TestContext.Current.CancellationToken)
        .ConfigureAwait(true);

    _ = await client.PutObjectAsync(putObjectRequest, TestContext.Current.CancellationToken)
        .ConfigureAwait(true);

    using var objectResponse = await client.GetObjectAsync(bucketName, objectKey, TestContext.Current.CancellationToken)
        .ConfigureAwait(true);

    using var streamReader = new StreamReader(objectResponse.ResponseStream);

    var content = await streamReader.ReadToEndAsync(TestContext.Current.CancellationToken)
        .ConfigureAwait(true);

    // Then
    Assert.Equal(helloWorld, content);
    Assert.Equal(_awsEmulatorContainer.GetConnectionString(), _awsEmulatorContainer.GetConnectionString(ConnectionMode.Host));
}

The test example creates an S3 bucket, uploads an object and downloads it again. Use GetConnectionString() as the service URL of the AWS client and AwsEmulatorBuilder.Region as the authentication region.

The test example uses the following NuGet dependencies:

1
2
3
4
5
6
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<PackageReference Include="coverlet.collector"/>
<PackageReference Include="xunit.runner.visualstudio"/>
<PackageReference Include="xunit.v3"/>
<PackageReference Include="AWSSDK.S3"/>
<PackageReference Include="AWSSDK.SQS"/>

To execute the tests, use the command dotnet test from a terminal.

Tip

For the complete source code of this example and additional information, please refer to our test projects.

Access AWS Emulator

The emulator generates its credentials and its certificate during the startup. Read them after the container has started:

Gets the AWS Emulator connection string
1
var connectionString = _awsEmulatorContainer.GetConnectionString();
Gets the AWS Emulator certificate
1
var certificate = await _awsEmulatorContainer.GetCertificateAsync();
Gets the AWS Emulator credentials
1
var credentials = await _awsEmulatorContainer.GetCredentialsAsync();

The emulator rejects requests that are not signed with the generated credentials. The credentials are valid for the emulator instance only and cannot authenticate to AWS.

Trust the certificate

The emulator accepts HTTPS requests only. Instead of accepting any certificate, configure the AWS client to trust the self-signed certificate of the emulator instance. In this example, the HTTP client factory validates the certificate against the certificate of the emulator. The factory is assigned to the HttpClientFactory property of the AWS client configuration, as shown in the usage example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public sealed class AwsEmulatorHttpClientFactory : HttpClientFactory, IDisposable
{
    private readonly SocketsHttpHandler _httpMessageHandler = new SocketsHttpHandler();

    public AwsEmulatorHttpClientFactory(X509Certificate2 certificate)
    {
        // Trust only the self-signed certificate of the emulator instance.
        _httpMessageHandler.SslOptions.CertificateChainPolicy = new X509ChainPolicy();
        _httpMessageHandler.SslOptions.CertificateChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
        _httpMessageHandler.SslOptions.CertificateChainPolicy.CustomTrustStore.Add(certificate);
        _httpMessageHandler.SslOptions.CertificateChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
    }

    public override HttpClient CreateHttpClient(IClientConfig clientConfig)
    {
        return new HttpClient(_httpMessageHandler, false);
    }

    public void Dispose()
    {
        _httpMessageHandler.Dispose();
    }
}

Note

The certificate is valid for localhost, 127.0.0.1 and ::1. If the Docker host is reached through another hostname or IP address, the certificate validation fails because of the name mismatch.

Limitations

Some AWS services return URLs or open additional listeners for their resources. These URLs contain the address and port of the emulator inside the container, and the module does not rewrite them or map the additional ports. For example, the SQS queue URL contains the container port. The AWS client uses it to identify the queue, but sends the requests to the configured service URL.

The module reads the generated certificate and credentials from a directory that depends on the HOME environment variable and the port of the emulator. Do not override them, otherwise GetCertificateAsync() and GetCredentialsAsync() fail.

Default configuration

The builder applies the following default configuration:

  • Port: 9297 (see AwsEmulatorBuilder.AwsEmulatorPort)
  • Environment variable: HOME=/tmp/testcontainers-aws
  • Environment variable: EMULATOR_TELEMETRY=off
  • Command: --bind 0.0.0.0 --port 9297 --auth on
  • Wait strategy: Waits until the HTTPS request GET /__admin/health to port 9297 is completed successfully.