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¶
WithExposedPorts
Since v0.37.0WithEnv
Since v0.29.0WithWaitStrategy
Since v0.20.0WithAdditionalWaitStrategy
Not available until the next release mainWithWaitStrategyAndDeadline
Since v0.20.0WithAdditionalWaitStrategyAndDeadline
Not available until the next release mainWithEntrypoint
Since v0.37.0WithEntrypointArgs
Since v0.37.0WithCmd
Since v0.37.0WithCmdArgs
Since v0.37.0WithLabels
Since v0.37.0
Lifecycle Options¶
WithLifecycleHooks
Not available until the next release mainWithAdditionalLifecycleHooks
Not available until the next release mainWithStartupCommand
Since v0.25.0WithAfterReadyCommand
Since v0.28.0
Files & Mounts Options¶
WithFiles
Since v0.37.0WithMounts
Since v0.37.0WithTmpfs
Since v0.37.0WithImageMount
Since v0.37.0
Build Options¶
WithDockerfile
Since v0.37.0
Logging Options¶
WithLogConsumers
Since v0.28.0WithLogConsumerConfig
Not available until the next release mainWithLogger
Since v0.29.0
Image Options¶
WithAlwaysPull
Not available until the next release mainWithImageSubstitutors
Since v0.26.0WithImagePlatform
Not available until the next release main
Networking Options¶
WithNetwork
Since v0.27.0WithNetworkByName
Not available until the next release mainWithBridgeNetwork
Not available until the next release mainWithNewNetwork
Since v0.27.0
Advanced Options¶
WithHostPortAccess
Since v0.31.0WithConfigModifier
Since v0.20.0WithHostConfigModifier
Since v0.20.0WithEndpointSettingsModifier
Since v0.20.0CustomizeRequest
Since v0.20.0WithName
Not available until the next release mainWithNoStart
Not available until the next release main
Experimental Options¶
WithReuseByName
Since 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_EXTERNAL
environment variable will be set to hostname in the container request. - for Localstack versions 2.0.0 and above, the
LOCALSTACK_HOST
environment 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_EXTERNAL
will 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_EXTERNAL
manually.
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.