LocalStack¶
Since v0.18.0
Introduction¶
The Testcontainers module for LocalStack is "a fully functional local AWS cloud stack", to develop and test your cloud and serverless apps without actually using the cloud.
Adding this module to your project dependencies¶
Please run the following command to add the LocalStack module to your Go dependencies:
go get github.com/testcontainers/testcontainers-go/modules/localstack
Usage example¶
Running LocalStack as a stand-in for multiple AWS services during a test:
ctx := context.Background()
localstackContainer, err := localstack.Run(ctx, "localstack/localstack:1.4.0")
defer func() {
if err := testcontainers.TerminateContainer(localstackContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
Environment variables listed in Localstack's README may be used to customize Localstack's configuration.
Use the testcontainers.WithEnv option when creating the LocalStackContainer to apply those variables.
Module Reference¶
Run function¶
- Since v0.32.0
Info
The RunContainer(ctx, opts...) function is deprecated and will be removed in the next major release of Testcontainers for Go.
The LocalStack module exposes one single function to create the LocalStack container, and this function receives three parameters:
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*LocalstackContainer, error)
context.Context, the Go context.string, the Docker image to use.testcontainers.ContainerCustomizer, a variadic argument for passing options.
Image¶
Use the second argument in the Run function to set a valid Docker image.
In example: Run(context.Background(), "localstack:1.4.0").
Container Options¶
When starting the Localstack container, you can pass options in a variadic way to configure it.
The following options are exposed by the testcontainers package.
Basic Options¶
WithExposedPortsSince v0.37.0WithEnvSince v0.29.0WithWaitStrategySince v0.20.0WithAdditionalWaitStrategySince v0.38.0WithWaitStrategyAndDeadlineSince v0.20.0WithAdditionalWaitStrategyAndDeadlineSince v0.38.0WithEntrypointSince v0.37.0WithEntrypointArgsSince v0.37.0WithCmdSince v0.37.0WithCmdArgsSince v0.37.0WithLabelsSince v0.37.0
Lifecycle Options¶
WithLifecycleHooksSince v0.38.0WithAdditionalLifecycleHooksSince v0.38.0WithStartupCommandSince v0.25.0WithAfterReadyCommandSince v0.28.0
Files & Mounts Options¶
WithFilesSince v0.37.0WithMountsSince v0.37.0WithTmpfsSince v0.37.0WithImageMountSince v0.37.0
Build Options¶
WithDockerfileSince v0.37.0
Logging Options¶
WithLogConsumersSince v0.28.0WithLogConsumerConfigSince v0.38.0WithLoggerSince v0.29.0
Image Options¶
WithAlwaysPullSince v0.38.0WithImageSubstitutorsSince v0.26.0WithImagePlatformSince v0.38.0
Networking Options¶
WithNetworkSince v0.27.0WithNetworkByNameSince v0.38.0WithBridgeNetworkSince v0.38.0WithNewNetworkSince v0.27.0
Advanced Options¶
WithHostPortAccessSince v0.31.0WithConfigModifierSince v0.20.0WithHostConfigModifierSince v0.20.0WithEndpointSettingsModifierSince v0.20.0CustomizeRequestSince v0.20.0WithNameSince v0.38.0WithNoStartSince v0.38.0WithProviderNot available until the next release main
Experimental Options¶
WithReuseByNameSince v0.37.0
Accessing hostname-sensitive services¶
Some Localstack APIs, such as SQS, require the container to be aware of the hostname that it is accessible on - for example, for construction of queue URLs in responses.
Testcontainers will inform Localstack of the best hostname automatically, using an environment variable for that:
- for Localstack versions 0.10.0 and above, the
HOSTNAME_EXTERNALenvironment variable will be set to hostname in the container request. - for Localstack versions 2.0.0 and above, the
LOCALSTACK_HOSTenvironment variable will be set to the hostname in the container request.
Once the variable is set:
-
when running the Localstack container directly without a custom network defined, it is expected that all calls to the container will be from the test host. As such, the container address will be used (typically localhost or the address where the Docker daemon is running).
-
when running the Localstack container with a custom network defined, it is expected that all calls to the container will be from other containers on that network.
HOSTNAME_EXTERNALwill be set to the last network alias that has been configured for the Localstack container.ctx := context.Background() newNetwork, err := network.New(ctx) if err != nil { log.Printf("failed to create network: %s", err) return } defer func() { if err := newNetwork.Remove(context.Background()); err != nil { log.Printf("failed to remove network: %s", err) } }() nwName := newNetwork.Name localstackContainer, err := localstack.Run( ctx, "localstack/localstack:0.13.0", testcontainers.WithEnv(map[string]string{"SERVICES": "s3,sqs"}), network.WithNetwork([]string{nwName}, newNetwork), ) defer func() { if err := testcontainers.TerminateContainer(localstackContainer); err != nil { log.Printf("failed to terminate container: %s", err) } }() if err != nil { log.Printf("failed to start container: %s", err) return } -
Other usage scenarios, such as where the Localstack container is used from both the test host and containers on a custom network, are not automatically supported. If you have this use case, you should set
HOSTNAME_EXTERNALmanually.
Examples using the AWS SDK for Go¶
You can use the AWS SDK for Go to create a client for the LocalStack container. The following examples show how to create a client for the S3 service, using both the SDK v1 and v2.
AWS SDK v1¶
// awsSession returns a new AWS session for the given service. To retrieve the specific AWS service client, use the
// session's client method, e.g. s3manager.NewUploader(session).
func awsSession(ctx context.Context, l *localstack.LocalStackContainer) (*session.Session, error) {
mappedPort, err := l.MappedPort(ctx, nat.Port("4566/tcp"))
if err != nil {
return &session.Session{}, err
}
provider, err := testcontainers.NewDockerProvider()
if err != nil {
return &session.Session{}, err
}
defer provider.Close()
host, err := provider.DaemonHost(ctx)
if err != nil {
return &session.Session{}, err
}
awsConfig := &aws.Config{
Region: aws.String(region),
CredentialsChainVerboseErrors: aws.Bool(true),
Credentials: credentials.NewStaticCredentials(accesskey, secretkey, token),
S3ForcePathStyle: aws.Bool(true),
Endpoint: aws.String(fmt.Sprintf("http://%s:%d", host, mappedPort.Int())),
}
return session.NewSession(awsConfig)
}
For further reference on the SDK v1, please check out the AWS docs here.
AWS SDK v2¶
type resolverV2 struct {
// you could inject additional application context here as well
}
func (*resolverV2) ResolveEndpoint(ctx context.Context, params s3.EndpointParameters) (
smithyendpoints.Endpoint, error,
) {
// delegate back to the default v2 resolver otherwise
return s3.NewDefaultEndpointResolverV2().ResolveEndpoint(ctx, params)
}
func s3Client(ctx context.Context, l *localstack.LocalStackContainer) (*s3.Client, error) {
mappedPort, err := l.MappedPort(ctx, nat.Port("4566/tcp"))
if err != nil {
return nil, err
}
provider, err := testcontainers.NewDockerProvider()
if err != nil {
return nil, err
}
defer provider.Close()
host, err := provider.DaemonHost(ctx)
if err != nil {
return nil, err
}
awsCfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion(region),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accesskey, secretkey, token)),
)
if err != nil {
return nil, err
}
// reference: https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/endpoints/#with-both
client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String("http://" + host + ":" + mappedPort.Port())
o.EndpointResolverV2 = &resolverV2{}
o.UsePathStyle = true
})
return client, nil
}
For further reference on the SDK v2, please check out the AWS docs here
Testing the module¶
The module includes unit and integration tests that can be run from its source code. To run the tests please execute the following command:
cd modules/localstack
make test
Info
At this moment, the tests for the module include tests for the S3 service, only. They live in two different Go packages of the LocalStack module,
v1 and v2, where it'll be easier to add more examples for the rest of services.