Getting an admin access key out of running containers and onto ECS task roles
Five ECS services were running with an administrator's access key in their environment variables. This is the order I used to move them onto a scoped task role, the Go SDK detail that can break S3 on the way, and the checks that prove the key is really gone.
Five ECS services were starting every container with an administrator's access key in the environment. Backend, jobs, and three non-production copies of them. So every one of those containers could do anything in the AWS account, including delete it. The key belonged to a personal admin user that was also used to run Terraform (yes, it was mine).
Nobody planned it like that. The app needed S3, somebody needed a key that works, and the admin key worked. It sat there for months. It came out during our VAPT, the same read-only review I wrote about in running a safe VAPT on your AWS account using AWS CLI, and it was one of the first things we fixed.
In this blog we will look at the order I used to move those services onto a task role, one SDK detail that can break every S3 call on the way, and the checks I ran before deleting the key.
The order matters
There is a tempting shortcut: delete the key first and let things break. Don't. Five services would have lost S3 at the same moment, and two of them were production.
The order I followed was this:
- Create a task role with only the S3 access the app really uses.
- Remove the four credential variables from every task definition.
- Confirm the code falls back to the default credential chain when those variables are missing.
- Redeploy every service, including the odd ones nobody touches.
- Delete the key, then the console login.
Steps 2 and 3 look independent but they are basically one change. If the code still expects the variables, removing them is an outage.
A task role scoped to one bucket
The old setup effectively had AdministratorAccess. The role I made for the backend can list one bucket and read, write and delete objects in it. That's all.
data "aws_iam_policy_document" "ecs_tasks_trust" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "backend_task" {
name = "backend-task"
assume_role_policy = data.aws_iam_policy_document.ecs_tasks_trust.json
}
data "aws_iam_policy_document" "backend_s3" {
statement {
sid = "ListTheOneBucket"
actions = ["s3:ListBucket"]
resources = ["arn:aws:s3:::${var.docs_bucket}"]
}
statement {
sid = "ObjectsInTheOneBucket"
actions = [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
]
resources = ["arn:aws:s3:::${var.docs_bucket}/*"]
}
}
resource "aws_iam_role_policy" "backend_s3" {
name = "s3-docs"
role = aws_iam_role.backend_task.id
policy = data.aws_iam_policy_document.backend_s3.json
}
s3:ListBucket goes on the bucket ARN and the object actions go on bucket/*. Mix those up and you get AccessDenied on list calls while uploads work fine, which can eat a good half hour before you spot it. I checked this with terraform validate on Terraform 1.17 and AWS provider 6.x.
The role goes into the task definition as taskRoleArn. Keep it separate from the execution role. The execution role is what the ECS agent uses to pull the image and fetch secrets, the task role is what your code gets. If you want the longer explanation of those two, it is in IAM explained by writing policies.
One honest note here. Bucket-level scoping was a big step from admin, but one task role shared by production and test services is still one role. That is its own topic.
The SDK detail that breaks S3
Our Go backend read the key from config and built static credentials from it. The plan was simple: remove the variables, the config fields go empty, the SDK finds the task role.
It does not work like that. If you pass empty strings to the static provider, it doesn't fall through to the next provider in the chain. It returns an error at request time. In the v1 SDK that error is ErrStaticCredentialsEmpty; in v2 the static provider returns StaticCredentialsEmptyError, "static credentials are empty". Either way every S3 call fails after deploy.
So the fix in code was a guard. Pin static keys only when both halves are set, otherwise leave the credentials provider alone:
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
// loadAWSConfig pins static keys only when BOTH halves are set. Otherwise it
// leaves the provider alone, so the default chain finds the ECS task role.
func loadAWSConfig(ctx context.Context) (aws.Config, error) {
var opts []func(*config.LoadOptions) error
id, secret := os.Getenv("APP_AWS_KEY_ID"), os.Getenv("APP_AWS_SECRET")
if id != "" && secret != "" {
opts = append(opts, config.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(id, secret, ""),
))
}
return config.LoadDefaultConfig(ctx, opts...)
}
func main() {
ctx := context.Background()
cfg, err := loadAWSConfig(ctx)
if err != nil {
log.Fatalf("load aws config: %v", err)
}
creds, err := cfg.Credentials.Retrieve(ctx)
if err != nil {
log.Fatalf("retrieve credentials: %v", err)
}
fmt.Println("credential source:", creds.Source)
who, err := sts.NewFromConfig(cfg).GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
if err != nil {
log.Fatalf("get caller identity: %v", err)
}
fmt.Println("running as:", aws.ToString(who.Arn))
}
I built this against aws-sdk-go-v2/config v1.33 and ran go vet on it. Inside a Fargate task with no key variables, the source should print CredentialsEndpointProvider and the ARN should be an assumed-role/backend-task/... session. That is the container credentials endpoint ECS sets up through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI. If you still see a static source, something is still feeding a key in.
A thing to watch: the default chain reads AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from the environment before it ever gets to the container endpoint. So if those standard names are in the task definition, they win over the task role, even with no code at all reading them.
Removing the variables and redeploying
I removed the four credential entries from the container definitions and registered a new revisions. Then each service got a new deployment. The non-production services are where people forget, because nobody deploys them that week. We did all five in the same change itself.
Registering a new revision changes nothing for running tasks. Only a deployment does that, so check what is actually running:
aws ecs describe-services --cluster my-cluster --services backend \
--query 'services[0].deployments[].{rev:taskDefinition,status:status,running:runningCount}'
Also, removing a variable from the new revision doesn't remove it from the old ones. Old revisions stay readable with ecs:DescribeTaskDefinition, and as I found earlier, deregistering an ECS task definition does not delete it. Keep that in mind when you decide how urgent rotation is.
Checks before deleting the key
This small script is read-only. It checks the user's keys, the login profile, and whether any running service still has a credential-shaped variable:
#!/usr/bin/env bash
# Read-only checks after moving services from a user's access key to task roles.
set -euo pipefail
USER_NAME="${1:?usage: checks.sh <iam-user-name> [cluster]}"
CLUSTER="${2:-my-cluster}"
echo "== access keys left on ${USER_NAME} (want 0)"
aws iam list-access-keys --user-name "$USER_NAME" \
--query 'length(AccessKeyMetadata)' --output text
echo "== console login profile (want NoSuchEntity)"
aws iam get-login-profile --user-name "$USER_NAME" 2>&1 | tail -n 1 || true
echo "== services still carrying credential variables (want none)"
for svc in $(aws ecs list-services --cluster "$CLUSTER" --query 'serviceArns[]' --output text); do
td=$(aws ecs describe-services --cluster "$CLUSTER" --services "$svc" \
--query 'services[0].taskDefinition' --output text)
aws ecs describe-task-definition --task-definition "$td" \
--query 'taskDefinition.containerDefinitions[].environment[].name' --output json \
| jq -r --arg td "${td##*/}" '.[] | select(test("AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN)$")) | "\($td) \(.)"'
done
Run it once before deleting (expect 1 key) and once after (expect 0). The jq filter only catches the standard names, so add your app's own names if it used custom ones like ours did.
Before deleting, look at when the key was last used (OLD_KEY_ID is the key's ID from list-access-keys):
aws iam get-access-key-last-used --access-key-id "$OLD_KEY_ID" \
--query 'AccessKeyLastUsed.[LastUsedDate,ServiceName,Region]' --output text
If the last use is older than your final deploy, nothing is using it. If it is newer, something you forgot is still holding it. A cron job, a laptop, a CI runner, who knows. Deactivating it first with aws iam update-access-key --status Inactive and waiting a day is the cautious version; deactivation can be reverted back, deletion cannot.
Deleting the key and the login
The key went first, then the console login profile. That user had a console password with no recorded use, so instead of enrolling MFA for it we just deleted the login. Fewer things to protect.
Terraform needed a new identity after that, because it was running on the same key. I made a dedicated CLI-only user for it, with no console login, created outside Terraform. Why outside? If Terraform manages the key it authenticates with, a plan can propose deleting its own key halfway through an apply. Not a fun way to find out.
After the change, CloudTrail is last check. Events from the apps should show userIdentity.type as AssumedRole with the task role's session, and the old user should show nothing at all:
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=Username,AttributeValue=old-admin-user \
--start-time "$(date -u -v-1d +%Y-%m-%dT%H:%M:%SZ)" \
--query 'Events[].[EventTime,EventName]' --output text
That date -v-1d is the macOS form; on Linux use date -u -d '1 day ago' +%Y-%m-%dT%H:%M:%SZ. An empty result is what you want. Anything else means a caller you missed.