Sub topic 11
Referencing values from CloudFormation and AWS compute services
This chapter assumes you can read CloudFormation YAML, know what a Lambda function, an ECS task and an EC2 instance role are, and have already created parameters and secrets in the earlier chapters. It covers how templates and compute services receive those values without hard-coding them.
Three moments when a value can be resolved
A reference to a parameter or secret is resolved at one of three times. The time decides who can see the value and how soon a change takes effect.
- Deploy time. CloudFormation reads the value while it creates or updates the stack and writes it into the resource's properties.
- Start time. The compute service reads the value when a task, container or instance starts and injects it as an environment variable.
- Run time. Your code calls Parameter Store or Secrets Manager itself, usually through a cache.
Run-time reads are the only path that picks up a rotated secret without a redeploy or restart. Keep this in mind when you choose a pattern.
Deploy-time references in CloudFormation
CloudFormation offers two ways to read Parameter Store values. Both resolve the value during stack operations.
SSM parameter types
A template parameter of type AWS::SSM::Parameter::Value<String> takes the name of an SSM parameter as its value and resolves it when the stack is created or updated.
Parameters:
DbHost:
Type: AWS::SSM::Parameter::Value<String>
Default: /myapp/prod/db/hostYou then use !Ref DbHost anywhere in the template. The resolved value appears in the console's parameter list for the stack. Use this type only for non-sensitive values. It does not support SecureString parameters.
Dynamic references
A dynamic reference is a string of the form {{resolve:service:...}} placed directly in a property. The three you will use are:
| Reference | Reads | Typical use |
|---|---|---|
| `{{resolve:ssm:/path/name}}` | String or StringList parameter | Hostnames, feature flags, AMI IDs |
| `{{resolve:ssm-secure:/path/name:version}}` | SecureString parameter | Only in properties that CloudFormation lists as supported |
| `{{resolve:secretsmanager:secret-id:SecretString:json-key:version-stage:version-id}}` | Secrets Manager secret | Passwords for resources that need one at creation |
For Secrets Manager, every segment after the secret ID is optional. Empty segments are kept as colons. This reads the password key of the current version:
Resources:
Database:
Type: AWS::RDS::DBInstance
Properties:
Engine: postgres
DBInstanceClass: db.t3.micro
AllocatedStorage: "20"
MasterUsername: '{{resolve:secretsmanager:myapp/prod/db:SecretString:username}}'
MasterUserPassword: '{{resolve:secretsmanager:myapp/prod/db:SecretString:password}}'Dynamic references have rules that cause most template errors:
- The principal running the stack operation needs read permission. That is you, or the stack's service role. Grant
ssm:GetParameterfor parameters andsecretsmanager:GetSecretValuefor secrets. The role must also be able to use the KMS key if a customer managed key encrypts the value. - CloudFormation resolves the reference only when the stack is created or updated. A later rotation does not change a resource that already received the old value.
- The resolved value is placed into the resource property. If that property is visible in the resource's configuration, the secret is visible there too. Lambda environment variables are an example: anyone with
lambda:GetFunctionConfigurationcan read them. ssm-secureworks only in specific resource properties. A property that is not on the supported list fails the stack. Check the CloudFormation documentation for the resource before you rely on it.
Letting AWS manage the secret
For databases, a better choice than reading a secret into the template is to avoid handling the password at all. A AWS::SecretsManager::Secret resource with GenerateSecretString creates a random password. A AWS::SecretsManager::SecretTargetAttachment links it to the database. RDS can also create and rotate the master password itself when you set ManageMasterUserPassword: true. In both designs the password never appears in your template or in the stack's parameters.
Lambda: pass names, fetch at run time
The pattern from the earlier example is to resolve non-sensitive values at deploy time and hand the function only the name of each secret:
Environment:
Variables:
DB_HOST: '{{resolve:ssm:/myapp/prod/db/host}}'
DB_SECRET_NAME: myapp/prod/dbThe function's execution role then needs secretsmanager:GetSecretValue on that secret, plus kms:Decrypt if a customer managed key is used.
Each Lambda execution environment is reused across many invocations. Read the secret once outside the handler and keep it in a module-level variable. A cold start pays one API call, and warm invocations pay none.
The AWS Parameters and Secrets Lambda Extension does this caching for you. You add it as a Lambda layer. It runs a local HTTP server on port 2773, and your code calls it instead of the AWS API. Look up the layer ARN for your Region and architecture in the AWS documentation. Requests must carry the function's session token in a header:
import json
import os
import urllib.parse
import urllib.request
ENDPOINT = "http://localhost:2773"
def _get(path, query):
url = f"{ENDPOINT}{path}?{urllib.parse.urlencode(query)}"
request = urllib.request.Request(
url,
headers={"X-Aws-Parameters-Secrets-Token": os.environ["AWS_SESSION_TOKEN"]},
)
with urllib.request.urlopen(request) as response:
return json.loads(response.read())
def handler(event, context):
secret = _get("/secretsmanager/get", {"secretId": os.environ["DB_SECRET_NAME"]})
creds = json.loads(secret["SecretString"])
return {"user": creds["username"]}The extension's cache has a time-to-live, which you set with the SSM_PARAMETER_STORE_TTL and SECRETS_MANAGER_TTL environment variables. The default is 300 seconds. A rotated secret can therefore be stale for up to that long.
ECS: secrets in the task definition
ECS can inject a secret or parameter as a container environment variable when the task starts. In the container definition, each entry in Secrets has a variable Name and a ValueFrom ARN. The following fragment belongs inside an AWS::ECS::TaskDefinition resource:
ContainerDefinitions:
- Name: app
Image: public.ecr.aws/docker/library/nginx:latest
Secrets:
- Name: DB_PASSWORD
ValueFrom: !Sub "${DbSecret}:password::"
- Name: DB_HOST
ValueFrom: !Sub "arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/myapp/prod/db/host"Here DbSecret is an AWS::SecretsManager::Secret resource in the same template, and !Ref on it returns its ARN. The suffix :password:: selects one JSON key. Its parts are json-key:version-stage:version-id, and the empty parts mean the current version.
Points that cause failures:
- The task execution role pulls the value, not the task role. Give the execution role
secretsmanager:GetSecretValue,ssm:GetParameters, andkms:Decryptas needed. - Values are read once, when the task starts. After a rotation, running tasks keep the old value until you start new tasks, for example with a forced new deployment.
- Selecting a JSON key on Fargate needs platform version 1.4.0 or later.
- The value becomes a plain environment variable inside the container. Any process in the container, and anything that dumps the environment, can read it.
EC2 and Kubernetes
EC2 instances read values through their instance profile. A user data script or startup service calls aws ssm get-parameters-by-path or aws secretsmanager get-secret-value with the role's credentials. Nothing is stored on the instance except what you write to disk.
On Amazon EKS, the Kubernetes Secrets Store CSI Driver with the AWS provider mounts secrets as files in a pod. It can also sync them into Kubernetes secrets. Access is granted to a pod's service account through IAM roles for service accounts.
Choosing a mechanism
| Mechanism | Resolved | Sees rotation | Value is visible in |
|---|---|---|---|
| SSM parameter type | Stack create or update | On next stack update | Stack parameter list |
| Dynamic reference | Stack create or update | On next stack update | Resource properties |
| ECS `Secrets` | Task start | On next task start | Container environment |
| Lambda extension or SDK | Cache refresh | After TTL expires | Memory only |
Exercise
A stack uses {{resolve:secretsmanager:myapp/prod/db:SecretString:password}} for the MasterUserPassword of an RDS instance. Rotation changes the secret every 30 days. The stack is not updated in that time. Which password does the database use, and what would you change so that application code always uses the current one?
Show answer
The database keeps the password that CloudFormation resolved at the last create or update, because dynamic references resolve only during stack operations. Rotation updates the secret but not the database unless a rotation function also changes the database user. To avoid the mismatch, let Secrets Manager or RDS own the password (a generated secret with a target attachment, or ManageMasterUserPassword), and have the application read the secret by name at run time through a cache with a short TTL.
Exercise
An ECS task fails to start with an access denied error when pulling a secret listed under Secrets. The task role already allows secretsmanager:GetSecretValue. What is the most likely cause?
Show answer
The permission was granted to the task role. ECS uses the task execution role to inject Secrets values at start, so that role needs secretsmanager:GetSecretValue on the secret, and kms:Decrypt if a customer managed key encrypts it.