Sub topic 7
Task execution role versus task role
This chapter assumes you know basic IAM (roles, trust policies, and permission policies), have the AWS CLI configured, and have read the chapter on writing a Fargate task definition. By the end you should be able to say which of the two roles a given permission belongs to, and diagnose the errors you get when it sits on the wrong one.
Two roles, two callers
A Fargate task definition has two separate IAM role fields. They look similar and have similar names. They are used by different callers at different times.
- The task execution role (
executionRoleArn) is used by the ECS agent, which AWS runs on your behalf. The agent uses it to set up the task before your code starts and to ship its output while it runs. - The task role (
taskRoleArn) is used by your application code. The containers receive credentials for it, and the AWS SDK picks them up automatically.
The simplest test is to ask who makes the API call. If the infrastructure makes it on behalf of the task, the permission goes on the execution role. If your code makes it, the permission goes on the task role.
| Question | Task execution role | Task role |
|---|---|---|
| Field in the task definition | `executionRoleArn` | `taskRoleArn` |
| Who uses it | ECS agent and Fargate infrastructure | Your application code |
| When it is used | Before the containers start, and for log delivery | While your code runs |
| Required on Fargate? | Only if you pull from ECR, use awslogs, or inject secrets | Only if your code calls AWS APIs |
| Typical permissions | Pull from ECR, write logs, read secrets for injection | Read an S3 bucket, write to DynamoDB, publish to SQS |
The shared trust policy
Both roles must trust the ECS tasks service. The trust policy is identical for each.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ecs-tasks.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}The trust policy controls who can assume the role. The permission policies attached to the role control what the role can do. If you see an error saying ECS is not authorized to perform sts:AssumeRole, the trust policy is the problem, not the permissions.
Building the task execution role
Save the trust policy above as trust.json, then create the role and attach the AWS managed policy.
aws iam create-role \
--role-name ecsTaskExecutionRole \
--assume-role-policy-document file://trust.json
aws iam attach-role-policy \
--role-name ecsTaskExecutionRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicyAmazonECSTaskExecutionRolePolicy grants the following:
- Pulling images from ECR (
ecr:GetAuthorizationToken,ecr:BatchGetImage,ecr:GetDownloadUrlForLayer). - Writing log streams and events to CloudWatch Logs (
logs:CreateLogStream,logs:PutLogEvents).
It does not grant access to Secrets Manager or SSM Parameter Store. The secrets block in the example task definition reads a Secrets Manager secret, so the execution role needs an extra inline policy scoped to that secret.
aws iam put-role-policy \
--role-name ecsTaskExecutionRole \
--policy-name read-prod-db-secret \
--policy-document '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db-AbCdEf"
}
]
}'Two additional cases are worth knowing:
- If the secret is encrypted with a customer managed KMS key, the execution role also needs
kms:Decrypton that key. The defaultaws/secretsmanagerkey needs no extra grant. - For SSM Parameter Store parameters, grant
ssm:GetParameterson the parameter ARN instead.
Building the task role
The task role starts empty. Grant only what your code actually calls. Suppose the web application reads objects from one S3 bucket.
aws iam create-role \
--role-name webAppTaskRole \
--assume-role-policy-document file://trust.json
aws iam put-role-policy \
--role-name webAppTaskRole \
--policy-name read-uploads-bucket \
--policy-document '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-uploads/*"
}
]
}'Your code needs no credential configuration. The ECS agent exposes a credentials endpoint to the container and sets the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable. The SDK's default credential chain finds it. This sketch uses Python with boto3:
import boto3
# No keys in code or environment: boto3 reads the task role
# credentials from the container credentials endpoint.
s3 = boto3.client("s3", region_name="us-east-1")
obj = s3.get_object(Bucket="example-uploads", Key="report.csv")
print(obj["ContentLength"])The credentials are temporary and rotate automatically. Do not bake long-lived access keys into the image or environment variables.
Why the split matters
Separating the roles gives you least privilege in both directions.
- Your application cannot use the execution role. Credentials for it are not exposed to your containers, so a compromised app cannot read every secret the agent can fetch or pull arbitrary images.
- The agent does not need your application's permissions. A change to what the code may touch never widens what the infrastructure may touch.
Use one task role per application, not one shared role for the whole cluster. A task role that several services share tends to accumulate permissions, and then a flaw in the least important service gets access to the most sensitive data.
Several services can share one execution role if their needs are the same. When secrets differ per service, give each service its own execution role scoped to its own secrets.
Common errors and what they mean
The symptom usually tells you which role is missing a permission.
| Symptom | Likely cause | Fix |
|---|---|---|
| Task stops with `CannotPullContainerError` and an ECR authorization failure | Execution role lacks ECR permissions, or is missing from the task definition | Attach `AmazonECSTaskExecutionRolePolicy` |
| `ResourceInitializationError: unable to pull secrets or registry auth` | Execution role cannot read the secret, or the task has no network path to Secrets Manager | Add `secretsmanager:GetSecretValue`, and check routes or VPC endpoints |
| No logs appear and the task stops on a log driver error | Execution role lacks `logs:CreateLogStream` or `logs:PutLogEvents`, or the log group does not exist | Fix the role, and create the `/ecs/web-app` log group |
| Application logs `AccessDenied` from S3 or DynamoDB | Task role lacks the permission | Add it to the task role |
| `ECS was unable to assume the role` | Trust policy does not name `ecs-tasks.amazonaws.com` | Correct the trust policy |
| Application gets `NoCredentialsError` | `taskRoleArn` is not set in the task definition | Add `taskRoleArn` and register a new revision |
A frequent mistake is adding S3 permissions to the execution role because that is the role everyone already has. This does nothing for your code, which never uses it.
Changing roles
The role ARNs are part of the task definition revision. Editing a role's policies takes effect for new credential requests without a new revision. Switching to a different role requires registering a new revision and updating the service to use it, which starts a deployment.
Running tasks keep the credentials they already have until those expire, so a permission change can take a short while to reach a task that is already running. Tasks you start afterwards see the change immediately.
Checking your setup
You can confirm which role a task received by describing the task definition.
aws ecs describe-task-definition \
--task-definition web-app \
--query "taskDefinition.{exec:executionRoleArn,task:taskRoleArn}"From inside a running container (using ECS Exec, covered in a later chapter), aws sts get-caller-identity returns the task role, never the execution role. This is a quick way to confirm what your code is actually running as.
Exercise
A Fargate task starts, but the application logs "AccessDenied" when it calls dynamodb:PutItem. The task also pulled its image and wrote logs without problems. Which role needs the new permission, and why?
Show answer
The task role. Your application code makes the DynamoDB call, so it uses the task role. The image pull and log delivery already work, which shows the execution role is configured correctly. Adding the permission to the execution role would have no effect, because the containers never use it.
Exercise
A new service fails with "ResourceInitializationError: unable to pull secrets or registry auth". The task definition has a secrets entry pointing at a Secrets Manager secret encrypted with a customer managed KMS key. Name two permissions to check on the execution role.
Show answer
Check secretsmanager:GetSecretValue on the secret's ARN, and kms:Decrypt on the customer managed key. The agent fetches the secret before starting the container, so both belong on the execution role, not the task role. If both are present, also check that the task has a network route to Secrets Manager.