V4 Signatures with Go on Lambda
The AWS Go SDK’s V4 Signer requires Credentials. While you can create Credentials
with an access key and secret, when you’re running in Lambda you should get the credentials from your function’s assumed role. The documentation doesn’t provide a clear example of how to do this, but it’s easy.
Credentials
can be found in session.Session.Config.Credentials
. The following snippet will create a v4.Signer
with the credentials from the configured session. Setting the SharedConfigState
to session.SharedConfigEnable
will ensure that the config is based on ~/.aws/config
and ~/.aws/credentials
.
package main
func main() {
awsSess, err := session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
})
if err != nil {
log.Fatalf("failed creating session: %s", err)
}
signer := v4.NewSigner(awsSess.Config.Credentials)
// signer can now be used to sign requests.
}
Demo
I have published a sample project called go-lambda-v4-signature
on GitHub so you can see this in action. The function can be run locally or as a Lambda function. It will use whatever credentials are provided by the session to retrieve a list of your S3 buckets and log them.