Give the task an IAM role. The steps:
- Create an IAM role. Its trust policy (the rule that says who may use the role) allows
ecs-tasks.amazonaws.comto assume it. - Attach a policy that allows the needed DynamoDB actions on the table.
- Set the role as the task role in the task definition.
ECS then gets temporary credentials for that role from STS (Security Token Service, the AWS service that issues short-lived credentials). ECS gives them to the containers through a local credentials endpoint. The AWS SDK for JavaScript v3 uses a default credential provider chain: a list of places it checks for credentials, in order. This chain checks the container endpoint automatically, so new DynamoDBClient({}) just works. The credentials are short-lived, and they are refreshed before they expire.
Lambda and EC2 work the same way. Lambda uses an execution role, and EC2 uses an instance profile. No secret ever lives in your image, repo or .env file. To remove access, you just edit the role.
- Create an IAM role that trusts ecs-tasks.amazonaws.com, and set it as the task role.
- ECS provides temporary STS credentials through a container credentials endpoint.
- The SDK's default credential provider chain finds these credentials automatically.
- Lambda uses an execution role and EC2 uses an instance profile, which is the same idea.
- No long-lived keys live in code, images or env files.