Vault AWS Lambda extension
AWS Lambda lets you run code without provisioning and managing servers. Lambda functions perform processing when you need it, and now can leverage Vault secrets through the The Vault Lambda Extension.
Challenge
A database within your AWS infrastructure maintains sensitive information. A periodic function is required to audit and update the data stored. This function must authenticate with Vault and receive database credentials.
Solution
Lambda Extensions are Lambda layers used to augment Lambda functions, and you can use them to give the Lambda function access to the Vault cluster. During execution, the Lambda layer packages the extension code with the main Lambda function code.
In this lab you will create an AWS Lambda function that uses the Vault Lambda Extension to authenticate with Vault, receive the database credentials, and perform the necessary queries.
Prerequisites
This tutorial requires an AWS account, Terraform, go, AWS CLI, Docker, and additional configuration to create a demonstration environment.
- Create an AWS account with AWS credentials and a EC2 key pair
- Install Terraform
- Install go
- Install AWS CLI
- Install Docker
Scenario introduction
You learn about the Vault Lambda Extension by creating a local scenario environment, using Terraform configuration to deploy supporting AWS-based infrastructure which you will then use to configure Vault for use with the AWS auth method.
Finally, you will build an example Lambda function that uses the Vault Lambda Extension to read secrets from Vault, and use Terraform to deploy it.
Create environment
You can retrieve the lambda function and terraform configuration by cloning the hashicorp-education/learn-vault-lambda-extension repository from GitHub.
This repository contains supporting content for all of the Vault learn tutorials. The content specific to this tutorial can be found in a sub-directory.
Change into the learn-vault-lambda-extension
directory.
Working directory
This tutorial assumes that you execute all following commands from within this directory.
The demonstration environment sets up a Vault server, a PostgreSQL database, and configures the database secrets engine to generate dynamic credentials. The infrastructure is described by the Terraform configuration files in the directory.
Create an environment variable named AWS_ACCESS_KEY_ID
with your AWS access
key ID.
Create an environment variable named AWS_SECRET_ACCESS_KEY
with your AWS
secret access key.
These environment variables are used by Terraform and the AWS CLI to authenticate and create resources.
Tip
The above example uses IAM user authentication. You can use any authentication method described in the AWS provider documentation.
Copy terraform.tfvars.example
and rename to terraform.tfvars
.
Edit terraform.tfvars
to override the default settings that describe your
environment.
Initialize Terraform.
The initialization retrieves the additional modules required to apply the resources defined within the configuration.
Apply Terraform to review the planned actions.
The terminal output displays the plan that it found and the resources it creates.
Enter yes
to confirm and resume.
Note
Keep in mind that answering yes at this time will create actual resources with associated costs.
When the terraform apply
command completes, the Terraform output displays the
IP addresses of the Vault server and other services created.
The output displays the database address, the container repository address, and connection information for the Vault server. The terraform configuration also generated a private key and enabled SSH login on the Vault server. An example SSH command is provided in the output.
In a new terminal session, change into the scenario directory.
Then SSH into the Vault Server.
A single Vault server is running with the filesystem storage backend. The Terraform configuration automatically initialized and unsealed the server.
Verify that Vault is ready, initialized, and unsealed.
If the value of Initialized is true and the value of Sealed is false, then the Vault server is ready for use.
Note
The Vault server was configured with the template found in ./templates/userdata-vault-server.tpl
.
The database secrets engine is already enabled and configured to communicate
with the database through credentials generated for the role lambda-function
.
Read credentials from the lambda-function
database role.
The PostgreSQL credentials are displayed as username
and password
.
Read the Dynamic Secrets: Database Secrets Engine tutorial to learn about configuring the database secrets engine.
Set the value of environment variables DB_USER
and DB_PASSWORD
to another set of credentials read from the role.
The same read operation is performed. The results are returned in JSON format,
and parsed for the username
and password
fields. These two values are then
read into the values of variables DB_USER
and DB_PASSWORD
.
The PostgreSQL client tool requires this username, password, and host address
to connect with its command-line tool. The database's address is stored in an
environment variable named DB_HOST
.
Display the database address.
Connect to the PostgreSQL database via the CLI with the credentials and host.
Your system prompt is replaced with a new prompt root=#
. Commands issued at
this prompt are executed against the PostgreSQL database running within the
container.
List all the database users.
The output displays a table of all the database credentials generated. The credentials that were recently generated appear in this list.
Disconnect from the PostgreSQL database.
Vault issued database credentials, successfully connected to the database and queried the users within the database.
Enable AWS authentication
The AWS Lambda function created in this step performs the same operation of requesting credentials and performing a query. The function needs its own set of Vault credentials that it requests through the AWS authentication engine.
Enable the AWS authentication engine.
Configure the AWS client to use the default options.
The lambda function needs credentials to query the database credentials at the configured path.
Create a policy named lambda-function
.
The policy grants the read capability to the database/creds/lambda-function
.
A policy is assigned to a token during the authentication through a role.
Read the Vault Policies tutorial to learn about defining Vault policies.
Create a role prefixed with the AWS environment name.
The Vault role connects the AWS IAM role, created by the Terraform configuration in ./iam.tf
and the Vault policy, lambda-function
. The token returned after authentication is valid for 5 minutes.
Enable Audit Device Log
You can observe the requests and responses associated with deploying the Lambda in a Vault audit device log. If you choose to try the caching example later in the scenario, the audit log is helpful for observing the lack of requests as well.
Enable a filesystem audit device.
The Vault Server is configured and ready for the AWS Lambda function to authenticate.
Tail the audit device log.
Successful output:
There is a single request and response pair present in the log.
Build and package lambda function
Return to your original terminal session for the next steps.
An AWS lambda function is code that is packaged and delivered to a specific environment where it is executed. The package is an archive or a container image.
The lambda function for this tutorial is written in Go. It reads in the location of the Vault server and credentials provided to it. It requests dynamic credentials to gain access to the PostgreSQL database and performs a query to display the current list of database users.
Clean, build, and archive the lambda function.
The demo function archive is found the path demo-function/demo-function.zip
.
Display the archived lambda function.
The archived function can now become an AWS lambda function.
Create the lambda function
The lambda function is packaged and is ready for the creation of an AWS Lambda
resource. Terraform provides the aws_lambda_function
resource
that enables you to create the lambda function with an archive or container
image.
Rename the file lambda-as_an_archive.tf.disabled
to lambda.tf
.
Display the contents of the lambda.tf
file.
Successful output:
1 2 3 4 5 6 7 8 9 101112131415161718192021222324252627282930313233
This file contains two resources. The resource to create the lambda and output to display how the lambda is executed via AWS CLI.
The aws_lambda_function
loads the packaged function found at the path defined
at filename
. To connect and authenticate with Vault several environment
variables are defined:
VAULT_ADDR
is the address of the Vault server. An AWS instance resource named `aws_instance.vault-server contains that address.VAULT_AUTH_ROLE
is the IAM role used to perform the function.VAULT_AUTH_PROVIDER
is the authentication method to use.VAULT_SECRET_PATH_DB
is the Vault path to read the database credentialsVAULT_SECRET_FILE_DB
is the path that the credentials are saved. This path/tmp/vault_secret.json
is defined in the custom function.DATABASE_URL
is an environment variable defined in the custom function.
Run terraform apply
and review the planned actions. Your terminal output
indicates the plan that it found and what resources will be created.
Enter yes
to confirm and resume.
When the terraform apply
command completes, the lambda function is created and
the additional output displays how to invoke it.
Invoke the lambda function.
The output displays the logging and the current accounts found within the database.
The lambda function successfully executed.
Check the other terminal session, and you will observe a pair of new requests and responses corresponding to the Lambda execution.
Example output:
Caching
If your use case can benefit from it, caching can be configured for the Vault Lambda Extension local proxy server so that it does not forward every request to the Vault server.
You can enable this caching by setting a VAULT_DEFAULT_CACHE_TTL
variable in your lambda.tf
configuration with a value that can be parsed as a Go time duration.
For example, to specify a 5 minute TTL you can add VAULT_DEFAULT_CACHE_TTL = "5m"
to your variables. Now when the extension is run and clients make GET requests using the header X-Vault-Cache-Control: cache
, the request will be returned directly from the cache if there's a cache hit. On a cache miss the request will be forwarded to Vault and the response returned and cached.
If you set VAULT_DEFAULT_CACHE_ENABLED
to true
as in this example, then all requests are cached; otherwise you must set the HTTP header X-Vault-Cache-Control: cache
on requests that you wish to be cached. Consult the Vault Lambda Extension documentation for more detail.
To try caching with this tutorial, you can rename the file lambda-as_an_archive_caching.tf.disabled
to lambda.tf
.
Display the contents of the lambda.tf
file.
Successful output:
1 2 3 4 5 6 7 8 9 10111213141516171819202122232425262728293031323334353637
Notice the caching specific entries in this configuration, which set the variables on lines 17 and 18.
Run terraform apply
and review the planned actions. Your terminal output
indicates the plan that it found and what resources will be created.
Enter yes
to confirm and resume.
When the terraform apply
command completes, the lambda function is modified and the additional output displays how to invoke it.
Invoke the lambda function.
Now check the other terminal with audit device log for entries. You will note that there is another pair of request and responses logged.
Invoke the lambda function once again.
Invoke the lambda function a final time.
If you check the other terminal with audit device log now, you'll note that there were no entries for the last two invocations of the Lambda.
This is because they successfully used the cache, and did not need to authenticate with Vault.
You can learn more about the caching functionality in the Vault Lambda Extension documentation.
Clean up
In the second terminal displaying the audit log, press CTRL+C
to stop tailing the log and exit from the ssh session.
Return to the first terminal where you created the cluster and use Terraform to destroy the cluster.
Destroy the AWS resources provisioned by Terraform.
Delete the state file.
Next Steps
You built, packaged and deployed a Lambda function written in Go that uses the Vault Lambda Extension, and deployed it with Terraform.
Learn more by reading the blog post Use AWS Lambda Extensions to Securely Retrieve Secrets From HashiCorp Vault or by reviewing the Vault Lambda Extension code repository.
You deployed a Vault server and database with the provided Terraform configuration. Learn more about deploying infrastructure with Terraform Getting Started - AWS.
You used the AWS lambda to authenticate with Vault, request credentials for the PostgreSQL database, and perform a Query. Learn more about Dynamic Secrets: Database Secrets Engine.
You also learned about the caching functionality available in the Vault Lambda Extension, and demonstrated it in action in the audit device logs.