Building Lambda Functions and Rotating Secrets using Terraform!
Journey: 📊 Community Builder 📊
Subject matter: Building on AWS
Task: Building Lambda Functions and Rotating Secrets using Terraform!
This week, I used Terraform to create a Lambda Function and store values in Secrets Manager!
In this scenario, I configured Secrets Manager to use a Lambda Fn to rotate a Secret every 30 days, all done via Terraform.
The idea of this environment is to play with products and services, rather than create Highly Available architectures.
Resource credit: This architecture was created using guidance from Donovan Hoang Here.
What did I use to build this environment?
- Visual Studio Code platform
- Terraform
- AWS CLI
- AWS Management Console
What is built?
- A Lambda Function
- A new Secret
- A Secrets Manager rotation policy
In this task, I created a Terraform structure capable of creating a Secret in Secrets Manager with a rotation policy, integrated with AWS Lambda.
Having never played with Secrets Manager before (outside of AWS Cloud Quest roles), I thought it worth some time to configure and generally mess about with it for a while to refresh my memory.
In utilising Secrets Manager, you are able to dramatically enhance your organisations security. Instead of storing credentials as hard-coded entries in your app source code, you can use the code to make calls to Secrets Manager to retrieve the values securely.
Secrets are encrypted at rest using KMS keys and strict access control policies can be set using IAM. Also, using automatic password rotation ensures a further layer of security, without the requirement for manual intervention.
Once I had applied the Terraform, AWS Lambda, and AWS Secrets Manager were automatically configured.
My Lambda Function had the correct permissions to be able to interact with Secrets Manager and Secrets Manager was configured with the base key value from my Terraform request.
I recalled my secret in the console, checked the rotation policy, and then manually rotated the secret successfully.
My Lambda function code, integrated with Secrets Manager was able to set a new password value which I confirmed by viewing it in the console.
As my rotation policy is set to rotate every 30 days, I could now leave my setup alone safe in the knowledge that it will work without any further configuration.
There was only one more thing to do now… terraform destroy!
Some of the highlights…
Terraform structure:
Terraform main.tf:
Terraform init:
Terraform apply:
(Click to enlarge)
Lambda fn:
Lambda code:
Lambda settings:
Lambda role:
Lambda policy:
Secrets Manager:
Rotation settings:
Secret key:
Manual rotation:
Terraform Destroy:
My interpretation of the architecture:
I hope you have enjoyed the article!