Lambda Integration

Prerequisites

  • AWS account with appropriate permissions
  • Terraform >= 1.0
  • Lambda function with IAM permissions to access Secrets Manager

Step 1: Create the Secret

module "api_credentials" {
  source  = "registry.patterneddesigns.ca/patterneddesigns/secrets-manager/aws"
  version = "2.1.0"

  name = "prod/lambda/api-credentials"
  secret_string = jsonencode({
    api_endpoint = "https://api.example.com"
    api_key      = var.api_key
    api_secret   = var.api_secret
  })

  kms_key_id = module.kms.key_id
}

Step 2: Create Lambda Function with Secret Access

module "api_handler" {
  source  = "registry.patterneddesigns.ca/patterneddesigns/lambda-function/aws"
  version = "3.1.0"

  function_name = "api-handler"
  runtime       = "python3.12"
  handler       = "main.handler"
  source_path   = "./src"

  environment_variables = {
    SECRET_ARN = module.api_credentials.secret_arn
  }
}

resource "aws_iam_role_policy" "lambda_secrets_access" {
  name = "secrets-manager-access"
  role = module.api_handler.role_name

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "secretsmanager:GetSecretValue"
        ]
        Resource = module.api_credentials.secret_arn
      },
      {
        Effect = "Allow"
        Action = [
          "kms:Decrypt"
        ]
        Resource = module.kms.key_arn
      }
    ]
  })
}

Step 3: Retrieve Secret in Lambda Code

import boto3
import json
import os

def get_secret():
    secret_arn = os.environ['SECRET_ARN']
    client = boto3.client('secretsmanager')

    response = client.get_secret_value(SecretId=secret_arn)
    return json.loads(response['SecretString'])

def handler(event, context):
    credentials = get_secret()

    # Use credentials
    api_endpoint = credentials['api_endpoint']
    api_key = credentials['api_key']

    # Your application logic here
    return {
        'statusCode': 200,
        'body': 'Success'
    }

Step 4: Deploy and Test

Run terraform apply to deploy the infrastructure, then test the Lambda function using the AWS Console or CLI.