Ecs

Amazon ECS Task Credentials and IAM Roles

Learn how Amazon ECS delivers temporary AWS credentials to containers, configure task and execution roles, apply least privilege, and troubleshoot IAM access securely.

Amazon ECS tasks often need to call AWS services such as Amazon S3, DynamoDB, Amazon SQS, AWS Secrets Manager, or Amazon CloudWatch. An application must be authenticated and authorized before it can make those API calls. ECS task IAM roles provide a secure way to give application containers temporary AWS credentials without placing long-term access keys in images, source code, environment variables, or task definitions.

This lesson distinguishes the ECS task role from the task execution role, explains how credentials reach containers, and shows how to configure and troubleshoot both roles.

Why ECS Tasks Need Credentials

A container that reads an object from S3, writes an item to DynamoDB, sends a message to SQS, retrieves a secret at runtime, or calls CloudWatch APIs must make an authenticated AWS request. AWS evaluates the identity making the request and the applicable permission policies.

Historically, applications commonly used an access key ID and secret access key. Long-term keys are dangerous for container workloads because they can be copied from:

  • Container images and image layers.
  • Source repositories or build logs.
  • Environment variables and task definition files.
  • Application configuration files.
  • Debug output and crash reports.

Anyone who obtains a long-term key may continue using it until it is disabled or rotated. The key may also have permissions unrelated to the specific task. ECS task roles avoid this pattern by allowing AWS Security Token Service (AWS STS) to issue short-lived credentials for a role session.

ECS IAM Role Types

ECS commonly uses two separate IAM roles. A role is an AWS identity with a trust policy and permission policies. The trust policy answers who may assume the role; permission policies answer what the assumed role may do.

Role type | Used by | Typical permissions | Configured in task definition | Should application code use it directly?

Task role | Application code inside task containers | S3, DynamoDB, SQS, Secrets Manager, or other APIs required by the workload | taskRoleArn | Yes, indirectly through the SDK or CLI credential provider

Task execution role | ECS infrastructure and the ECS agent or managed ECS workflow | Pull private images, publish logs, and retrieve supported startup secrets or parameters | executionRoleArn | No; it is for task startup and infrastructure operations

Task Role

The task role is the IAM role assumed for AWS API calls made by application code running inside the task. For example, an application that reads only objects below reports/ in one S3 bucket should receive a role allowing only that access.

Task Execution Role

The task execution role, often shortened to execution role, grants ECS permissions needed to start and operate the task. Common uses include pulling an image from a private Amazon ECR repository, sending container logs through the configured logging driver, and retrieving a secret or parameter that ECS is instructed to inject during startup.

The execution role does not automatically authorize application code. Giving the execution role DynamoDB permissions does not allow an application container to write to DynamoDB. The application needs those permissions on the task role.

When Each Role Is Needed

  • Neither role: A task may need neither role if it uses only public images, has no ECS-managed startup secrets or logs requiring AWS access, and does not call AWS APIs from its containers. This is uncommon for production workloads but possible.
  • Execution role only: A task may need an execution role when ECS must pull a private image or publish logs, but the application itself does not call AWS APIs.
  • Task role only: A task may need a task role when the task uses an image and startup configuration that require no execution-role permissions, but the application calls AWS APIs. In practice, logging or private image pulls often mean both roles are configured.
  • Both roles: This is the common pattern for an application that pulls a private image, sends logs to CloudWatch Logs, and accesses AWS services at runtime.

How ECS Delivers Temporary Credentials

AWS STS issues temporary credentials: an access key ID, secret access key, session token, and expiration time associated with an assumed role session. ECS obtains credentials for the task role and makes them available to eligible containers through a task-scoped credential endpoint.

AWS SDKs and AWS CLI tools include a container credential provider. When the application uses the standard credential provider chain, the SDK checks its supported credential sources and can retrieve credentials from the ECS endpoint. ECS commonly directs the provider using:

  • AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, which identifies a relative endpoint path supplied by ECS.
  • AWS_CONTAINER_CREDENTIALS_FULL_URI, which supplies a full endpoint URI in supported cases.

The exact endpoint implementation varies by launch type, operating system, and platform version. Applications should not construct endpoint requests themselves. Let the SDK or CLI handle retrieval, expiration, and refresh.

Credentials are rotated automatically while a task runs. Long-running applications must continue using the provider chain rather than reading credentials once and caching them forever. A properly configured SDK refreshes credentials as they approach expiration.

Credential Sources in an ECS Workload

Credential source | Where it is available | Typical consumer | Security considerations

ECS task role endpoint | Inside an eligible ECS task | Application SDK or AWS CLI | Preferred source for task AWS API calls; credentials are temporary and task-scoped

Explicit environment credentials | Process environment | SDK or CLI | Can override task credentials; avoid unless deliberately required and securely managed

Shared credentials file | A mounted or locally created file | SDK or CLI | Risky in containers if copied from a developer machine or image

EC2 instance profile | ECS container instance metadata on EC2 launch type | ECS host components | Must not become an unintended credential source for application containers

Developer or CI/CD credentials | Developer workstation or build environment | Local tools and deployment systems | Distinct from the identity used by a running ECS task

Task Definition Configuration

The task definition references the two roles by ARN. The roles must exist before ECS can register a task definition that refers to them. The same model applies to Fargate and ECS on EC2, although platform details and credential endpoint behavior should be validated for the operating system and platform version in use.

{
  "family": "orders-api",
  "taskRoleArn": "arn:aws:iam::123456789012:role/orders-api-task-role",
  "executionRoleArn": "arn:aws:iam::123456789012:role/orders-api-execution-role",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "containerDefinitions": [
    {
      "name": "orders-api",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/orders-api:1.0",
      "essential": true,
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/orders-api",
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ]
}

taskRoleArn identifies the role available to application containers. executionRoleArn identifies the role used by ECS infrastructure. For EC2 launch type, the task definition can use a compatible network mode and omit requiresCompatibilities or include EC2 as appropriate for the deployment. The role separation remains the same.

Changing either role requires a new task definition revision. Existing tasks continue using the configuration with which they were started. Register the revised definition, update the ECS service or run command to use that revision, and replace tasks through a controlled deployment.

Trust Policies and Permission Policies

Task Role Trust Policy

A role's trust policy identifies the principal allowed to assume it. An ECS task role normally trusts the ECS tasks service principal:

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

This policy does not grant S3, DynamoDB, or any other service permission. It only permits the ECS tasks service to assume the role.

Task Role Permissions Policy

An identity-based permissions policy grants actions after the role has been assumed. This example allows an application to read objects under one prefix. Object access uses an object ARN, so the bucket name and prefix must be included:

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

s3:GetObject is an object-level action. Listing a bucket is a separate operation and commonly requires s3:ListBucket on the bucket ARN, such as arn:aws:s3:::example-reports-prod. Do not add listing permission unless the application needs it.

Least privilege means limiting actions, resources, and, where appropriate, conditions. Consider prefixes, specific table or queue ARNs, encryption-key permissions, source VPC conditions, resource tags, and request attributes. Validate the resulting policy with IAM tools and test the actual application behavior.

Execution Role Trust and Permissions

The execution role normally uses the same ECS tasks service principal in its trust policy because ECS assumes it to perform task-related operations. Its permission policy commonly includes permissions needed for the selected features, such as:

  • Amazon ECR image retrieval actions for private images.
  • CloudWatch Logs actions required by the configured awslogs logging driver.
  • Permission to retrieve a referenced Secrets Manager secret or Systems Manager Parameter Store parameter when ECS performs that startup retrieval.
  • Additional permissions documented for selected ECS integrations.

Keep these policies separate. The execution role should not receive the application's database, object-store, or queue permissions simply because both roles are used by one task.

Creating and Attaching Roles

The following workflow is illustrative. Replace every example account ID, Region, ARN, role name, repository name, bucket name, and resource name with values from your environment.

aws iam create-role \
  --role-name orders-api-task-role \
  --assume-role-policy-document file://task-trust-policy.json

aws iam put-role-policy \
  --role-name orders-api-task-role \
  --policy-name ReadReportsPrefix \
  --policy-document file://s3-read-policy.json

aws iam create-role \
  --role-name orders-api-execution-role \
  --assume-role-policy-document file://execution-trust-policy.json

aws iam attach-role-policy \
  --role-name orders-api-execution-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

aws ecs register-task-definition \
  --cli-input-json file://orders-task-definition.json

aws ecs update-service \
  --cluster example-cluster \
  --service orders-api \
  --task-definition orders-api:REVISION \
  --force-new-deployment

The AWS-managed execution policy is convenient but may be broader than a carefully designed custom policy. Review its contents and use a custom policy when your security requirements call for tighter permissions. A role can have managed and inline policies, but the effective result is still subject to explicit denies, permissions boundaries, organization service control policies, and resource policies.

Using Credentials in Application Code

Initialize the SDK without embedding an access key or secret key. Configure the Region separately because credentials and Region solve different problems: credentials identify the caller, while the Region selects the regional service endpoint and resource namespace.

import boto3

# The SDK discovers ECS task credentials through its default provider chain.
s3 = boto3.client("s3", region_name="us-east-1")

response = s3.get_object(
    Bucket="example-reports-prod",
    Key="reports/today.json"
)

Equivalent SDKs in other languages generally support a default client constructor and an explicit Region setting. Do not pass aws_access_key_id or aws_secret_access_key unless you have a specific, reviewed reason to override the normal provider chain.

Provider Precedence

Credential-provider precedence differs slightly by SDK, but explicit configuration commonly has higher priority than container credentials. Environment variables such as AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN can therefore cause an application to use an unintended identity. Shared credential files, process-specific configuration, and other supported sources may also take precedence depending on the SDK.

Inspect configuration without printing secret values. Remove accidental credentials from images and task definitions, and ensure that test or deployment tooling does not inject developer credentials into production containers.

Verify the Caller Identity

STS GetCallerIdentity is a safe diagnostic operation because it returns identity metadata rather than credential values:

aws sts get-caller-identity --region us-east-1

Run it inside the application container or through an appropriate ECS exec session. An assumed-role ARN should identify the expected task role and an ECS-generated role session. Never print access keys, secret keys, session tokens, or the full response from a credential endpoint to application logs.

Common ECS Operations and Required Role

Operation | Example AWS service | Task role required | Execution role required | Notes

Application reads an S3 object | Amazon S3 | Yes | No | Grant the task role only the required object resources

Application reads or writes a DynamoDB item | DynamoDB | Yes | No | Application permissions belong on the task role

ECS pulls a private image | Amazon ECR | No | Yes | ECS infrastructure uses the execution role

ECS sends container logs | CloudWatch Logs | No | Yes | Permissions depend on the logging configuration

ECS injects a referenced startup secret | Secrets Manager or Parameter Store | No for ECS retrieval | Yes | Runtime application access is a separate path

Application retrieves or rotates a secret at runtime | Secrets Manager | Yes | No | Add runtime actions to the task role

Application sends an SQS message | Amazon SQS | Yes | No | Restrict the queue ARN and actions

Secrets: Startup Retrieval Versus Runtime Retrieval

When a task definition references a secret for ECS-managed injection, ECS uses the execution role to retrieve that value during task startup. The application then receives the configured value according to the task definition behavior.

If the application itself calls Secrets Manager at runtime, the task role needs the relevant permissions. If the application must rotate a secret, it needs the specific rotation-related permissions as well. These are different access paths and should not be conflated.

Security Boundaries and Isolation

All containers in one ECS task share the task role credentials. This is a task-level identity, not a per-container identity. A sidecar, logging helper, proxy, or diagnostic container can potentially make the same AWS API calls as the main application if it can access the task credential provider.

Suppose a task contains a low-privilege web application and a sidecar with broad access to S3 and Secrets Manager. The web application can generally use the same task credentials, so the sidecar's broad role expands the application's effective access. The safer options are to:

  • Place workloads requiring different AWS permissions in separate tasks.
  • Give the separate tasks distinct task roles.
  • Use a narrowly scoped communication interface between the workloads.
  • Remove unnecessary permissions from sidecars and application containers.

Fargate and EC2 Comparisons

With Fargate, AWS manages the underlying compute host, while the task receives its task role credentials through the supported ECS mechanism. With ECS on EC2, the EC2 container instance has a separate container instance role. That role is intended for ECS host and agent operations, not for application business access.

On EC2, an application that reaches instance-profile metadata may obtain broader container instance credentials if the host is not hardened. Configure the task role, restrict access to instance-profile credentials, and apply the appropriate metadata and network protections for the ECS agent, operating system, network mode, and platform version. Reduce the instance role to only host-level permissions needed by ECS.

Do not assume that a task role and an instance role are interchangeable. They represent different identities and should have different permission scopes.

Platform Considerations

Task roles are supported across the relevant ECS launch types, but networking mode, operating system, platform version, and Windows-specific behavior can affect how the credential endpoint is exposed. Validate the behavior for the exact Fargate platform or EC2 agent and AMI combination you operate. Do not hard-code Linux-specific endpoint assumptions into portable application code.

Task credentials are also distinct from developer credentials, CI/CD deployment credentials, and the ECS service-linked role. A CI/CD role may register a task definition or update a service; it is not the identity used by application code after the task starts.

Observability and Auditing

AWS CloudTrail records API activity for many AWS services. Calls made with a task role generally appear as activity from an assumed-role session. The session information, role ARN, timestamps, Region, API action, resource, and source details help connect an AWS request to the task context.

  • Use clear role names such as orders-api-task-role and orders-api-execution-role.
  • Tag roles with service, environment, owner, and data classification where supported by your governance model.
  • Monitor denied API calls and investigate repeated authorization failures.
  • Alert on unexpected services, Regions, resources, or unusually broad permissions.
  • Review CloudTrail session information together with ECS task events and deployment records.

CloudTrail may not by itself provide every application-level detail. Correlate the assumed-role session with ECS task IDs, service deployments, application logs, and request tracing while avoiding secret and credential logging.

Operational Credential Lifecycle

Task Startup

When ECS starts a task, it uses the execution role for required infrastructure operations, establishes the task environment, and makes task role credentials available to eligible containers. The application should use the SDK provider chain rather than expecting credential values in its own configuration.

During Task Execution

Temporary credentials expire and are refreshed while the task is running. SDK clients should tolerate refreshes and transient errors. Avoid copying credentials into a permanent application cache, writing them to disk, or logging them.

Task Stop and Replacement

When a task stops, its task credentials are no longer intended for use. A replacement task receives a new role session and temporary credentials. If permissions change, register a new task definition revision or update the role policy according to your change process, then perform a controlled rolling deployment. Verify newly started tasks before terminating all healthy old tasks when the change is high risk.

Troubleshooting Task Credentials

Symptom | Likely cause | How to verify | Corrective action

Application receives AccessDenied | Missing task-role action or resource; unexpected credential source; resource policy, boundary, SCP, or explicit deny | Run aws sts get-caller-identity; inspect effective policies and CloudTrail | Correct the task role or relevant resource policy; remove unintended credential overrides

Task fails before the application starts | Execution role lacks ECR, logging, secret, or parameter permissions | Inspect stopped-task reason and ECS service events | Correct the execution role, not the task role

SDK reports no credentials | Old task definition is deployed; invalid task role ARN; bad trust policy; disabled provider; not actually running in ECS | Check active task definition, task details, trust policy, and non-secret environment settings | Deploy the correct revision and restore standard provider behavior

Application uses broad EC2 instance permissions | Container can reach instance-profile credentials or task role is missing | Confirm caller identity and review EC2 metadata access | Assign a task role, protect metadata access, and reduce instance role permissions

Role change has no effect | Existing tasks still use an older revision or deployment has not replaced them | Compare service task definition revision and caller identity on new tasks | Update the service and complete a controlled rolling deployment

Sidecar accesses application-only resources | Containers in one task share task credentials | Review task composition and caller identity from the sidecar | Split tasks or redesign the sidecar boundary

AccessDenied Investigation

  1. Run aws sts get-caller-identity inside the affected task without exposing credential material.
  2. Confirm that the ARN corresponds to the intended task role.
  3. Inspect the task role's identity-based policies, including action and resource scope.
  4. Check the target resource policy, permissions boundary, organization service control policy, and possible explicit denies.
  5. Use CloudTrail and service-specific logs to identify the exact denied action, resource, Region, and caller.

Practical Example: S3-Reading Application

Create a task role whose trust policy allows ECS tasks to assume it. Attach the narrowly scoped S3 policy shown earlier, using the correct bucket and prefix. Reference the role with taskRoleArn:

"taskRoleArn": "arn:aws:iam::123456789012:role/reports-reader-task-role"

In the application, create the S3 client with the SDK's default credentials and an explicit Region. The SDK discovers the ECS task credentials automatically. The application can read the allowed prefix, but requests for unrelated buckets, prefixes, or actions should fail.

Practical Example: Execution Role Versus Task Role

Consider an application that pulls a private ECR image, writes logs to CloudWatch Logs, and reads and writes DynamoDB items.

  • The execution role receives the ECR and log-delivery permissions required by ECS.
  • The task role receives only the DynamoDB actions and table ARN required by the application.
  • Adding DynamoDB permissions only to the execution role does not authorize application code.
  • Adding ECR image-pull permissions to the task role is unnecessary because ECS infrastructure performs the image pull.

Exam-Relevant Notes

  • Task role: permissions for code inside containers.
  • Execution role: permissions for ECS startup and infrastructure operations.
  • Trust policy: identifies who may assume a role.
  • Permissions policy: grants or denies actions after assumption.
  • Temporary credentials: are issued by STS, expire, and are refreshed through the standard provider chain.
  • All containers in one task share the task role, so task roles are not per-container security boundaries.
  • On EC2 launch type, the container instance role is distinct from the task role.
  • Changing a referenced role generally requires a new task definition revision and replacement of running tasks for the change to take effect.

Summary

Use an ECS task role for AWS API calls made by application code and a separate execution role for ECS operations such as private image pulls, log delivery, and supported startup secret retrieval. Configure the roles in taskRoleArn and executionRoleArn, give each a correct ECS trust policy, and apply least-privilege permissions independently.

Let AWS SDKs and the AWS CLI retrieve and refresh temporary credentials through the ECS container credential provider. Verify identity with GetCallerIdentity, protect EC2 instance-profile credentials, isolate containers with different permission needs, and use CloudTrail plus ECS deployment data to audit and troubleshoot access.