Aws

AWS ECS Task Credentials and IAM Task Roles

Learn how ECS task roles provide temporary AWS credentials to containers, how task and execution roles differ, how SDKs retrieve credentials, and how to troubleshoot access securely.

Applications running in Amazon ECS often need to call AWS services such as Amazon S3, DynamoDB, Amazon SQS, Secrets Manager, or CloudWatch Logs. An ECS task role gives application containers temporary AWS credentials for those calls without placing long-lived access keys in the image or source code.

This lesson explains the difference between ECS IAM roles, how credentials reach a container, how AWS SDKs use them, and how to configure least-privilege access.

What ECS task credentials are for

Temporary credentials are time-limited AWS credentials consisting of an access key ID, secret access key, session token, and expiration time. ECS obtains credentials for a task role and makes them available to containers in that task.

The application normally does not need to request or rotate these values itself. A current AWS SDK or the AWS CLI uses the AWS SDK default credential provider chain: an ordered set of credential sources that includes ECS container credentials when the application is running in an ECS task.

For example, a web service can use its task role to read objects from S3, send messages to SQS, or write records to DynamoDB. The service code specifies the AWS operation and region, while the SDK obtains credentials through the container environment.

See also AWS temporary credentials for the general STS credential model.

ECS IAM roles compared

ECS commonly involves a task role and a task execution role. ECS tasks running on Amazon EC2 also depend on the EC2 container instance role, which is associated with an instance profile.

Task role: Configured with taskRoleArn. Used by application containers at runtime. It typically permits access to application resources such as S3 buckets, DynamoDB tables, SQS queues, or Secrets Manager secrets. Its permissions are available to containers in the task through task credentials.

Task execution role: Configured with executionRoleArn. Used by the ECS agent or Fargate infrastructure for supporting operations such as pulling private images, retrieving referenced secrets, and sending logs. Its permissions do not automatically become available to application code.

EC2 container instance role: Assigned to the EC2 instance through an instance profile. It supports the ECS agent and host-level operations. It must be protected from unintended access by containers.

A frequent configuration error is putting application permissions on executionRoleArn and expecting application code to use them. Runtime permissions belong on the role referenced by taskRoleArn.

How ECS delivers credentials

ECS injects the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable into containers that have task-role credentials. Its value identifies a task-local path on the ECS credential endpoint.

The SDK uses that path with the ECS endpoint to retrieve a temporary access key ID, secret access key, session token, expiration time, and role identity. The SDK refreshes credentials before they expire when it uses the supported default provider chain.

The endpoint is task-local and commonly uses the address 169.254.170.2. Applications should not normally call it directly; the SDK should manage retrieval and refresh.

Never copy credentials into a container image, task definition environment variables, configuration files, source code, or logs. Session tokens and endpoint responses must be treated as secrets.

Fargate, EC2, and credential isolation

AWS Fargate

Fargate supplies task credentials to containers through the ECS task credential endpoint. Fargate infrastructure uses the execution role for supported startup and integration operations, while application code should use the task role.

ECS on Amazon EC2

On EC2, the container instance has an instance profile. If a container can reach the EC2 instance metadata credential path or otherwise bypasses ECS credential isolation, it may obtain permissions intended for the host. Those permissions can be much broader than the application needs.

Use ECS-supported task credential isolation, keep the instance profile narrowly scoped, and avoid exposing instance-profile credentials to containers. The awsvpc network mode gives each task its own elastic network interface and is relevant to network separation, but it does not replace correct IAM configuration or endpoint protection.

Review EC2 instance-profile and container credential behavior carefully when operating ECS on EC2. The task role should be the normal runtime identity for application code.

Creating and attaching a task role

1. Create a trust policy

The role trust policy allows the ECS tasks service principal to assume the role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ecs-tasks.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

This is a trust policy, not an identity policy. It answers the question “who may assume this role?”

2. Attach a least-privilege identity policy

An identity policy answers the question “what may the assumed role do?” For a service that reads objects from one bucket, a narrow policy might be:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": "arn:aws:s3:::example-application-bucket/*"
    }
  ]
}

Grant only the actions and resource ARNs required by the workload. If the application lists a bucket, it may separately need s3:ListBucket on the bucket ARN itself. Do not add broad permissions merely to make an error disappear.

3. Reference the role in the task definition

{
  "family": "example-service",
  "taskRoleArn": "arn:aws:iam::123456789012:role/example-service-task-role",
  "executionRoleArn": "arn:aws:iam::123456789012:role/example-service-execution-role",
  "containerDefinitions": [
    {
      "name": "application",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/example-service:latest"
    }
  ]
}

Register a revised task definition and deploy the new revision through the ECS service, or run a task using that revision. Existing tasks do not necessarily acquire a changed role assignment until they are replaced.

Using task credentials in application code

Standard SDK configuration should specify the region separately from credentials. Do not provide static access keys when the application is running in ECS.

# Example AWS CLI use inside an ECS task
aws sts get-caller-identity

In application code, create the service client using the SDK's normal default configuration. For example, an S3 client should receive a region from supported configuration or explicit application settings, while credentials are discovered automatically.

When the task role is configured correctly, an API request made from the task is authorized as an assumed role session for that task role. If the same container is run locally, it does not automatically have ECS task credentials. Use an approved local developer profile, environment-specific identity, or another local credential method instead.

Credential sources and expected use

ECS task credentials: Appropriate for applications running in ECS. They rotate automatically before expiration. Use the SDK default provider chain and do not expose endpoint responses.

Local developer AWS profile: Appropriate for local development. The profile is managed outside the container or supplied through an approved development method. Do not copy production credentials into local images.

CI/CD workload identity: Appropriate for deployment automation. Use the identity mechanism supported by the CI/CD platform and grant only deployment permissions.

Static access keys: Avoid for ECS workloads. They do not rotate automatically and create a serious leakage risk if placed in images, environment variables, source code, or logs.

Inspecting credential availability

During a controlled debugging session, check whether ECS supplied the relative credential path:

printenv AWS_CONTAINER_CREDENTIALS_RELATIVE_URI

A nonempty value indicates that the container has a task credential path. It does not prove that the role has the required permissions.

You can query the endpoint during secure, non-production diagnosis:

curl -s "http://169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}"

Do not save or print the returned secret fields. If the response must be examined, redact the access key ID, secret access key, and session token before handling it. The document includes role identity and an expiration time, along with credential values. Treat the entire response as sensitive.

The safer application-level test is often:

aws sts get-caller-identity

This confirms the AWS principal visible to the CLI without requiring you to display the credential document.

Metadata is not credentials

Amazon ECS container metadata endpoints provide task and container information such as identifiers, status, network details, and resource data. They are related task-local observability endpoints, but they are distinct from the ECS credential endpoint. Protect credential endpoint responses more strictly than ordinary metadata.

Security and least privilege

  • Use one task role per permission boundary where practical instead of sharing a broad role across unrelated applications.
  • Restrict actions and resources to the minimum required. Use exact bucket prefixes, table ARNs, queue ARNs, secret ARNs, and KMS key ARNs where possible.
  • Use IAM conditions when appropriate, including resource tags, source VPC endpoints, or encryption-context constraints.
  • Do not log process environments, HTTP authorization headers, SDK debug output, or credential endpoint responses.
  • Remember that containers in the same ECS task can generally access that task's task-role credentials. Put sensitive workloads in separate tasks when they require different trust or permission boundaries.
  • Protect EC2 instance-profile credentials from containers and keep the instance role separate from application permissions.

Credential lifecycle and rotation

Task credentials are temporary. ECS replaces them before expiration, and supported SDK providers discover the current values when refreshing.

Indefinitely caching an access key, secret key, and session token causes intermittent failures after the cached session expires. Do not persist task credentials or implement manual caching unless the implementation correctly handles expiration and refresh. Prefer a current AWS SDK with its managed ECS credential provider.

After changing the task role assignment or its permissions, register and deploy the appropriate task definition revision or restart tasks when operationally appropriate. Replacing tasks also helps ensure that new configuration is active consistently.

Common ECS credential problems

No credentials found: The likely causes are a missing taskRoleArn, execution of the application outside ECS, static credential settings overriding the container provider, or an obsolete SDK. Verify the task definition and environment, remove unnecessary overrides, upgrade the SDK, and use the default provider chain.

Access denied: The task role may lack the action, use the wrong resource ARN, or be blocked by an explicit deny, permissions boundary, resource policy, or AWS Organizations service control policy. Check the exact principal, action, and resource.

Expired token: Custom credential caching or an outdated SDK may be using expired session credentials. Use the current SDK provider and remove indefinite caching.

Application uses the wrong role: Runtime permissions may have been added to executionRoleArn instead of taskRoleArn, or the task may be using an older revision. Inspect the running task definition and caller identity.

Credential endpoint is unreachable: The environment variable may be missing, a proxy or network rule may interfere with the task-local endpoint, or the process may not be running in the expected ECS task. Check task status, container configuration, proxy exclusions, launch type, networking, and SDK support.

Systematic troubleshooting workflow

  1. Confirm that the running task definition contains the intended taskRoleArn, not only an executionRoleArn.
  2. Confirm that the role ARN is valid and that its trust policy names ecs-tasks.amazonaws.com.
  3. Check AWS_CONTAINER_CREDENTIALS_RELATIVE_URI inside the running container without exposing secrets.
  4. Run aws sts get-caller-identity or the SDK equivalent to identify the principal actually making the request.
  5. Compare the failed API call with the task policy: verify action name, region, account, resource ARN, bucket prefix, table index, queue, secret, or KMS key.
  6. Check explicit denies, permissions boundaries, resource-based policies, and AWS Organizations service control policies.
  7. Use ECS task events and application error messages for startup and configuration clues.
  8. Use CloudTrail to identify the assumed task-role session, denied action, resource, and source context.
  9. Use IAM policy simulation where applicable, remembering that simulation may not include every resource-policy or organization-level condition.

Practical example: S3 read access

A web service needs read-only access to objects under one application bucket. Create a role trusted by ECS tasks, attach a policy containing only s3:GetObject for arn:aws:s3:::example-application-bucket/*, and set that role as taskRoleArn.

The application creates an S3 client without access keys. The SDK retrieves task credentials, signs the request, and refreshes the credentials as necessary. If the service also needs to list objects, add the narrowly scoped s3:ListBucket permission on the bucket ARN after confirming that requirement.

Practical example: separate startup and runtime permissions

Suppose a task pulls an image from Amazon ECR, sends logs to CloudWatch Logs, and sends application messages to SQS. The execution role supports the image pull, referenced secret retrieval, and log delivery integrations. The task role contains sqs:SendMessage for the required queue.

The application must not depend on the execution role's permissions. If the application receives an SQS access-denied error, add the minimum required permission to the task role and investigate policy restrictions; do not broaden the execution role.

Exam-relevant notes

  • taskRoleArn is the application runtime role; executionRoleArn is the ECS infrastructure support role.
  • The ECS credential environment variable identifies a relative endpoint path, not the credentials themselves.
  • Temporary credentials include a session token and expiration time.
  • Current AWS SDKs normally retrieve and refresh ECS credentials automatically.
  • Credentials in an ECS task are not automatically available to a locally run container.
  • All containers in one task generally share access to that task's credentials, so separate tasks may be necessary for isolation.