Updated Nov 23, 20267 min read

How to Use AWS Secrets Manager With ECS Fargate

Three ways to get Secrets Manager values into Fargate tasks, ranked: secrets declared in code with Encore, the task definition secrets block, and runtime reads with the AWS SDK, with the IAM each one needs and what happens on rotation.

Illustration for How to Use AWS Secrets Manager With ECS Fargate

To use AWS Secrets Manager with ECS Fargate, reference the secret ARN in the container definition's secrets block and grant the task execution role secretsmanager:GetSecretValue, or read the secret at runtime with the AWS SDK through the task role. With Encore, the secret is declared in the service code, the value is set with encore secret set, and Encore stores it in Secrets Manager in your own AWS account and injects it into the container.

Getting a secret into a Fargate container by hand takes three things in different places: the secret, a secrets entry in the task definition and a permission on the execution role. Miss the permission and the task fails to start. Get all three right and the next surprise is rotation.

What are the ways to get secrets into ECS Fargate?

1. Encore2. Task definition secrets3. Runtime read with the SDK
Where you declare itA struct field in the service codeContainer definition JSONApplication code
IAMSet up by Encore when it deploysExecution role, by handTask role, by hand
Missing secretDeploy fails before releaseTask fails to startRuntime error on first read
RotationNext deployNew tasks onlyNext cache refresh
Local developmentencore secret set --type localSeparate .env setupAWS credentials on the laptop
Readable by AI coding agentsNo, values are not stored in the repo (except a .secrets.local.cue override)Yes, if the local .env is in the projectNovalues stay in Secrets Manager
Best forServices where the secret ships with the code that uses itExisting ECS setupsSecrets that rotate on their own schedule

Verdict: pick Encore when you want secrets declared next to the code, checked before every deploy and stored in your own AWS account, with no task definitions or IAM to write. Use the secrets block for an existing ECS setup, and runtime reads when a service must follow rotations without a restart.

How does Encore handle secrets on ECS Fargate?

Encore

Encore is a backend framework with built-in infrastructure, and its platform provisions and deploys into your own AWS or GCP account, with services on Fargate on AWS. In Go, a secret is a field in a secrets struct, and Encore loads it before your code runs:

// email/email.go package email import ( "bytes" "context" "encoding/json" "fmt" "net/http" "encore.dev/beta/errs" ) // Encore loads these at startup. On AWS the values live in Secrets Manager. var secrets struct { PostmarkServerToken string } type SendParams struct { To string Subject string Body string } //encore:api private method=POST path=/email/send func Send(ctx context.Context, p *SendParams) error { payload, _ := json.Marshal(map[string]string{ "From": "app@example.com", "To": p.To, "Subject": p.Subject, "TextBody": p.Body, }) req, err := http.NewRequestWithContext(ctx, "POST", "https://api.postmarkapp.com/email", bytes.NewReader(payload)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") req.Header.Set("X-Postmark-Server-Token", secrets.PostmarkServerToken) resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return &errs.Error{Code: errs.Unavailable, Message: fmt.Sprintf("postmark returned %d", resp.StatusCode)} } return nil }
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

Set the value per environment type from the CLI. The values are stored per environment, and on AWS Encore replicates them into Secrets Manager in your account and injects them into the container as secret environment variables:

~/app
$ encore secret set --type prod PostmarkServerToken$ encore secret set --type dev,preview,local PostmarkServerToken

The secret is declared where it is used, with no task definition JSON, ARN or execution role policy to write. The Encore compiler also checks that every declared secret has a value before it runs or deploys the app, so a forgotten secret stops the release instead of a task that starts with an empty variable.

Local development uses the same declaration: encore run makes the local values available, and a .secrets.local.cue file can override one for your machine only. Shared values are never stored in the repository or in a .env file, so an AI coding agent working in the codebase sees which secrets a service declares but not their values, and encore secret list only shows which environments have a value. A .secrets.local.cue override is the exception, since it is a plaintext file in the app directory. An agent that adds an integration declares its secret in the same change, and a person sets the production value. Teams whose secrets must stay in an existing store can reference them through external vaults.

How do you inject a secret with the task definition secrets block?

ECS task definition

The standard way to inject a secret as an environment variable. Create the secret:

aws secretsmanager create-secret \ --name prod/email \ --secret-string file://secret.json

secret.json holds the JSON value, for example {"postmark_token":"..."}. Reading it from a file keeps the token out of shell history and the process list. Create the file outside the repository with owner-only permissions (umask 077), and delete it once the secret exists.

Reference it in the container definition. The key name after the ARN selects one field of a JSON secret, and the two trailing colons leave the version stage and version id at their defaults (the current version):

"secrets": [ { "name": "POSTMARK_SERVER_TOKEN", "valueFrom": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:prod/email-AbCdEf:postmark_token::" } ]

Then grant the task execution role access. The execution role is the one ECS uses to start the task, not the task role your code runs with:

{ "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:prod/email-*" }

Add kms:Decrypt on the key if the secret uses a customer managed KMS key instead of the default aws/secretsmanager key. The wildcard after the name covers the six random characters Secrets Manager appends to every secret ARN.

Rotation is the limitation, because ECS resolves the value once, when the task starts. After a rotation, the running tasks keep the old value until you launch new ones, typically with aws ecs update-service --force-new-deployment. For database passwords rotated by Secrets Manager, that means a window where running tasks hold a password that may stop working, unless the rotation strategy keeps the previous one valid.

How do you read the secret at runtime instead?

For secrets that rotate on their own schedule, read them from the application and cache the value. The task role, not the execution role, then needs secretsmanager:GetSecretValue. In Go, the AWS Secrets Manager caching client wraps the AWS SDK for Go v2 and refreshes each secret after its cache TTL, one hour by default:

// secrets.go (github.com/aws/aws-secretsmanager-caching-go/v2 v2.3.0) package main import ( "context" "encoding/json" "time" "github.com/aws/aws-secretsmanager-caching-go/v2/secretcache" ) // The SDK finds the task role's credentials on its own; there are no keys here. var cache, _ = secretcache.New(func(c *secretcache.Cache) { c.CacheConfig.CacheItemTTL = int64(5 * time.Minute) // nanoseconds }) type emailSecret struct { PostmarkToken string `json:"postmark_token"` } func postmarkToken(ctx context.Context) (string, error) { raw, err := cache.GetSecretStringWithContext(ctx, "prod/email") if err != nil { return "", err } var s emailSecret if err := json.Unmarshal([]byte(raw), &s); err != nil { return "", err } return s.PostmarkToken, nil }
A five-minute TTL means a rotated token reaches every task within five minutes, without a new deployment.

The cost is more code in every service, a dependency on Secrets Manager being reachable at runtime, an API charge per refresh, and AWS credentials on every developer laptop to run the service locally.

Good to know

  • See the AWS Secrets Manager pricing page. Related values can be grouped into one JSON secret.
  • Values set through the task definition show up as plain environment variables inside the container, so anything that logs the environment logs the secret.
  • For non-secret configuration, plain environment entries in the task definition are free and easier to review.

Which option should you choose?

  • Encore when you want secrets declared next to the code that uses them, checked before every deploy, and stored in Secrets Manager in your own AWS account without task definitions or IAM to write.
  • The task definition secrets block for an existing ECS setup where a restart on rotation is acceptable.
  • Runtime reads with caching when a service must follow rotations without a restart.

Frequently asked questions

How do I pass a Secrets Manager secret to an ECS Fargate container?

Add a secrets entry to the container definition with the environment variable name and the secret ARN in valueFrom. To pick one key from a JSON secret, append it: arn:aws:secretsmanager:region:account:secret:name-AbCdEf:key::. The task execution role needs secretsmanager:GetSecretValue on that secret, plus kms:Decrypt if it is encrypted with a customer managed key.

Why does my ECS task still use the old secret value after rotation?

ECS injects secrets referenced in the task definition once, when the container starts. AWS documents that a rotated value does not reach running containers, so launch new tasks or update the service with force new deployment. If a service must pick up rotations without restarting, read the secret at runtime with the AWS SDK and cache it.

Which IAM role needs access to the secret, the execution role or the task role?

The task execution role when ECS injects the secret through the task definition, because ECS fetches it before your code starts. The task role when your code reads the secret at runtime with the AWS SDK.

How do I read Secrets Manager secrets from a Go API on ECS?

Use the AWS Secrets Manager caching client for Go, github.com/aws/aws-secretsmanager-caching-go/v2, which wraps the AWS SDK for Go v2 and caches each secret for one hour by default. The SDK picks up the task role's credentials automatically, so the code holds no keys.

How does Encore handle secrets on ECS Fargate?

You declare the secret in the service code, set its value per environment type with encore secret set, and Encore replicates it into AWS Secrets Manager in your own account and injects it into the container as a secret environment variable. The compiler checks that every declared secret has a value before a run or deploy, so a missing secret stops the release.

How much does AWS Secrets Manager cost?

See the [AWS Secrets Manager pricing page](https://aws.amazon.com/secrets-manager/pricing/). Injecting secrets through the task definition uses one GetSecretValue call per task start, while reading at runtime uses a call per cache refresh.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders