View a markdown version of this page

Lambda function example for the Secrets Manager extension in AWS Systems Manager Cloud Extensions - AWS Systems Manager

Lambda function example for the Secrets Manager extension in AWS Systems Manager Cloud Extensions

This example reads secrets from inside an AWS Lambda function. A Python function calls the query route and the path route on localhost:5333, signs each request with SigV4, and uses refreshNow and versionStage. It also shows the error responses for a request that isn't signed, a request with an X-Forwarded-For header, and a secret that doesn't exist.

The function uses urllib for HTTP and botocore for signing. The Python runtime of Lambda includes botocore, so the function needs no layer other than the Cloud Extensions runtime.

Before you begin, complete the following tasks:

  • Install the Cloud Extensions runtime as a layer of your function. To choose the profile that the runtime loads, set the AWS_CLOUDEXTENSIONS_PROFILE environment variable of the function to the profile name or ID.

  • Add the Secrets Manager extension to that profile, and approve the secretsmanager capability. Because every caller signs with SigV4, set the SSRF token header check to off. For the steps, see Adding the extension with the AWS CLI.

  • Use the extensionKey authentication for the profile, because this example signs requests with the access key ID and the secret key of the profile. Keep the secret key of the profile in a Secrets Manager secret. Note the ARN of the secret and the access key ID of the profile. For more information, see Authentication.

  • Make sure that the IAM execution role of the extension allows secretsmanager:GetSecretValue and secretsmanager:DescribeSecret on test-demo/*. The role also needs secretsmanager:GetSecretValue on the secret that holds the secret key of the profile, because the role of the profile reads that secret. For the policy, see Required IAM permissions.

The function reads the secret key of the profile from Secrets Manager once for each execution environment, and uses the key to sign its requests. The function needs secretsmanager:GetSecretValue on that one secret. The function role doesn't need permissions for the secrets that the extension reads. The extension reads those secrets with its execution role. The function role also needs the cloudextensions:SyncState action on all resources, which the runtime uses to retrieve the profile. For the action, see Permissions for the runtime.

Create the test secret

To create a secret with two versions, run the following commands. The second command makes the first version the AWSPREVIOUS version:

aws secretsmanager create-secret --region us-west-2 --name test-demo/db-credentials \ --secret-string '{"username":"demo-user","password":"s3cr3t-demo-1"}' aws secretsmanager put-secret-value --region us-west-2 --secret-id test-demo/db-credentials \ --secret-string '{"username":"demo-user","password":"s3cr3t-demo-2-longer"}'

Create the secret before you invoke the function for the first time.

Write the function

Save the following code as lambda_function.py:

import json import os import urllib.error import urllib.parse import urllib.request import boto3 from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import Credentials # Use localhost, not 127.0.0.1. The runtime routes by host name. BASE_URL = "http://localhost:5333/secretsmanager" # The runtime verifies the Region and the service in the credential scope of the request. REGION = os.environ["AWS_REGION"] ACCESS_KEY_ID = os.environ["EXTENSION_ACCESS_KEY_ID"] SECRET_KEY_SECRET_ID = os.environ["EXTENSION_SECRET_KEY_SECRET_ID"] _credentials = None def get_credentials(): """Read the SigV4 secret key from Secrets Manager once for each execution environment.""" global _credentials if _credentials is None: secret = boto3.client("secretsmanager").get_secret_value(SecretId=SECRET_KEY_SECRET_ID) _credentials = Credentials(ACCESS_KEY_ID, secret["SecretString"]) return _credentials class ExtensionError(Exception): """An error response from the extension or the runtime.""" def __init__(self, status, error_type, body): super().__init__(f"{status} {error_type}: {body}") self.status = status self.error_type = error_type def call(path, params=None, sign=True, headers=None): """Send a GET request to the extension, signed with SigV4, and return the response body.""" url = BASE_URL + path if params: url += "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote) request = AWSRequest(method="GET", url=url, headers=dict(headers or {})) if sign: SigV4Auth(get_credentials(), "secretsmanager", REGION).add_auth(request) http_request = urllib.request.Request(url, headers=dict(request.headers)) try: with urllib.request.urlopen(http_request, timeout=10) as response: return response.read().decode("utf-8") except urllib.error.HTTPError as error: raise ExtensionError( error.code, error.headers.get("X-Amzn-Errortype"), error.read().decode("utf-8"), ) from error def get_secret(secret_id, **options): """Query route: GET /get?secretId=ID""" return json.loads(call("/get", {"secretId": secret_id, **options})) def get_secret_by_path(secret_id, **options): """Path route: GET /ID""" return json.loads(call("/" + secret_id, options)) def summarize(secret): """Return the metadata and the user name. Never return or log a secret value.""" value = json.loads(secret["SecretString"]) return { "Name": secret["Name"], "VersionStages": secret["VersionStages"], "username": value["username"], "passwordLength": len(value["password"]), } SECRET_ID = "test-demo/db-credentials" def step_query(): return summarize(get_secret(SECRET_ID)) def step_path(): return summarize(get_secret_by_path(SECRET_ID)) def step_previous(): return summarize(get_secret(SECRET_ID, versionStage="AWSPREVIOUS")) def step_refresh(): return summarize(get_secret(SECRET_ID, refreshNow="true")) def step_errors(): cases = { "doesNotExist": lambda: call("/get", {"secretId": "test-demo/does-not-exist"}), "missingSecretId": lambda: call("/get"), "notSigned": lambda: call("/get", {"secretId": SECRET_ID}, sign=False), "xForwardedFor": lambda: call("/get", {"secretId": SECRET_ID}, headers={"X-Forwarded-For": "203.0.113.10"}), } results = {} for label, run in cases.items(): try: run() results[label] = "no error" except ExtensionError as error: results[label] = {"status": error.status, "error": error.error_type} return results STEPS = { "query": step_query, "path": step_path, "previous": step_previous, "refresh": step_refresh, "errors": step_errors, } def lambda_handler(event, context): # Run the steps that the event names, or every step if the event names none. names = (event or {}).get("steps") or list(STEPS) results = {} for name in names: try: results[name] = STEPS[name]() except ExtensionError as error: results[name] = {"status": error.status, "error": error.error_type} return results

The code works as follows:

  • get_credentials reads the secret key from Secrets Manager and combines it with the access key ID. The function reads both values from the environment variables EXTENSION_SECRET_KEY_SECRET_ID and EXTENSION_ACCESS_KEY_ID.

  • call builds the request, adds the SigV4 Authorization and X-Amz-Date headers with SigV4Auth, and sends the request with urllib. The request time must be within 5 seconds of the clock of the runtime.

  • get_secret uses the query route, GET /get?secretId=ID. get_secret_by_path uses the path route, GET /ID. Both routes use the same cache.

  • When the extension or the runtime returns an error, call raises an ExtensionError that holds the HTTP status and the X-Amzn-Errortype header. The handler reports the error and continues with the next step.

  • summarize returns the name, the version stages, the user name, and the length of the password. The function never returns or logs a secret value. Do the same in your own functions.

Create the function

To create the function with the runtime layer, run the following commands. Replace the role ARN, the layer ARN, the profile name, the access key ID, and the secret ARN with your own values. The timeout is 30 seconds, because the default of 3 seconds is too short for the first invocation.

zip function.zip lambda_function.py aws lambda create-function \ --region us-west-2 \ --function-name secrets-manager-extension-demo \ --runtime python3.12 \ --handler lambda_function.lambda_handler \ --role arn:aws:iam::111122223333:role/ExtensionDemoFunctionRole \ --zip-file fileb://function.zip \ --timeout 30 \ --layers layer-arn \ --environment "Variables={AWS_CLOUDEXTENSIONS_PROFILE=my-application,EXTENSION_ACCESS_KEY_ID=access-key-id,EXTENSION_SECRET_KEY_SECRET_ID=secret-key-secret-arn}"

The role of the function needs the AWSLambdaBasicExecutionRole managed policy, secretsmanager:GetSecretValue on the secret that holds the secret key, and cloudextensions:SyncState on all resources. Replace layer-arn with the ARN of the Cloud Extensions Lambda layer for the architecture of your function.

Create the function with AWS CloudFormation

To create the function with AWS CloudFormation instead of the AWS CLI, use the following template. The template creates the IAM role of the function, with the permissions to read the secret key and to retrieve the profile. The template also creates the function with the runtime layer and a managed policy with the permissions that the extension needs. The ExtensionLayerArn parameter reads the public parameter that holds the ARN of the Lambda extension, so a stack update picks up the latest ARN. The ProfileName parameter sets the AWS_CLOUDEXTENSIONS_PROFILE environment variable of the function. The template uses the x86_64 architecture. For arm64, set Architectures to arm64 and use the arm64 public parameter.

Save the following template as template.yaml, and put lambda_function.py in a folder named function next to it:

AWSTemplateFormatVersion: '2010-09-09' Description: Lambda function that reads secrets through the Cloud Extensions Secrets Manager extension Parameters: ExtensionLayerArn: Type: AWS::SSM::Parameter::Value<String> Default: /aws/service/aws-cloudextensions/lambda-extension/amd64/latest Description: Public parameter that holds the ARN of the Cloud Extensions Lambda extension for x86_64 ExtensionAccessKeyId: Type: String Description: SigV4 access key ID of the Cloud Extensions profile ExtensionSecretKeySecretArn: Type: String Description: ARN of the Secrets Manager secret that holds the SigV4 secret key of the profile ProfileName: Type: String Default: my-application Description: Name or ID of the Cloud Extensions profile that the runtime loads Resources: FunctionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Policies: - PolicyName: ReadSigV4SecretKey PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: secretsmanager:GetSecretValue Resource: !Ref ExtensionSecretKeySecretArn - PolicyName: SyncProfileState PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: cloudextensions:SyncState Resource: '*' ExtensionPermissionsPolicy: Type: AWS::IAM::ManagedPolicy Properties: Description: Permissions for the IAM execution role of the Secrets Manager extension PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - secretsmanager:GetSecretValue - secretsmanager:DescribeSecret Resource: !Sub arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:test-demo/* - Effect: Allow Action: secretsmanager:GetSecretValue Resource: !Ref ExtensionSecretKeySecretArn DemoFunction: Type: AWS::Lambda::Function Properties: FunctionName: secrets-manager-extension-demo Runtime: python3.12 Architectures: - x86_64 Handler: lambda_function.lambda_handler Role: !GetAtt FunctionRole.Arn Timeout: 30 Layers: - !Ref ExtensionLayerArn Environment: Variables: AWS_CLOUDEXTENSIONS_PROFILE: !Ref ProfileName EXTENSION_ACCESS_KEY_ID: !Ref ExtensionAccessKeyId EXTENSION_SECRET_KEY_SECRET_ID: !Ref ExtensionSecretKeySecretArn Code: function/ Outputs: FunctionName: Value: !Ref DemoFunction ExtensionPermissionsPolicyArn: Description: Attach this policy to the IAM execution role of the extension Value: !Ref ExtensionPermissionsPolicy

The Code property points to a local folder. To upload the folder and deploy the stack, run the following commands. Replace amzn-s3-demo-bucket with the name of an Amazon S3 bucket in us-west-2 that you own. Replace the access key ID and the secret ARN with your own values:

aws cloudformation package \ --region us-west-2 \ --template-file template.yaml \ --s3-bucket amzn-s3-demo-bucket \ --output-template-file packaged.yaml aws cloudformation deploy \ --region us-west-2 \ --template-file packaged.yaml \ --stack-name secrets-manager-extension-demo \ --capabilities CAPABILITY_IAM \ --parameter-overrides \ ExtensionAccessKeyId=access-key-id \ ExtensionSecretKeySecretArn=secret-key-secret-arn

The stack outputs the ARN of the managed policy. Attach the policy to the IAM execution role of the extension. This template doesn't create that role, because the role needs a trust policy. The trust policy allows the role that the runtime runs as to assume the role. For the trust policy, see IAM execution role. The template also doesn't create the profile, the profile entry, or the security setting. To create the profile, see Step 2: Creating a profile. To create the profile entry and the security setting, see Adding the extension with the AWS CLI.

Invoke the function

To run every step, run the following command:

aws lambda invoke \ --region us-west-2 \ --function-name secrets-manager-extension-demo \ --cli-binary-format raw-in-base64-out \ --payload '{}' \ response.json cat response.json | jq

The output of jq has one key for each step. The query and path steps return the same name, the user name demo-user, the stage AWSCURRENT, and the password length of the second version. The previous step returns the stage AWSPREVIOUS and the password length of the first version. The errors step holds the HTTP status and the error name of each case. The Errors that the Secrets Manager extension in AWS Systems Manager Cloud Extensions returns lists the expected results. notSigned returns 401 MissingAuthenticationToken, xForwardedFor and missingSecretId return 400 BadRequestException, and doesNotExist returns the ResourceNotFoundException of Secrets Manager.

If the runtime isn't running in the function, the invocation fails with a URLError and the message Connection refused. Check that you attached the layer and that the runtime started.

To run only some steps, name them in the payload, for example '{"steps": ["query", "path"]}'.

See the cache and refreshNow at work

To see the cache, change the secret, and then read it with and without refreshNow:

aws secretsmanager put-secret-value --region us-west-2 --secret-id test-demo/db-credentials \ --secret-string '{"username":"demo-user","password":"s3cr3t-demo-3"}' aws lambda invoke \ --region us-west-2 \ --function-name secrets-manager-extension-demo \ --cli-binary-format raw-in-base64-out \ --payload '{"steps": ["query", "refresh"]}' \ response.json cat response.json | jq

While the secret is in the cache and Cache TTL hasn't expired, query returns the earlier password length. refresh returns the new one. After refresh, the extension updates the cache, so a later query returns the new value too. To make the result easier to repeat, set Cache TTL to 10 for the demonstration.

Clean up

To delete the function and the test secret, run the following commands:

aws lambda delete-function --region us-west-2 --function-name secrets-manager-extension-demo aws secretsmanager delete-secret --region us-west-2 --secret-id test-demo/db-credentials \ --force-delete-without-recovery

If you created the function with AWS CloudFormation, delete the stack instead of the function:

aws cloudformation delete-stack --region us-west-2 --stack-name secrets-manager-extension-demo

Detach the managed policy from the IAM execution role of the extension before you delete the stack. Otherwise, the deletion of the policy fails.