Task Execution Role
Overview
Section titled “Overview”The Task Execution Role
An IAM role assumed by ecs-tasks.amazonaws.com that grants ECS permissions to pull container images and write CloudWatch logs. is assumed by the ECS agent on your behalf to pull container images from ECR and write logs to CloudWatch. This role is referenced in the task definition’s executionRoleArn field and is required for any ECS task that uses private container images or CloudWatch logging.
Terraform Configuration
Section titled “Terraform Configuration”The following HCL defines the Task Execution Role
An IAM role assumed by ecs-tasks.amazonaws.com that grants ECS permissions to pull container images and write CloudWatch logs. with an assume role policy trusting ecs-tasks.amazonaws.com and an aws:SourceAccount condition to prevent cross-account confused deputy attacks.
resource "aws_iam_role" "task_execution" { name = "${var.name}-task-execution"
assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "ecs-tasks.amazonaws.com" } Condition = { StringEquals = { "aws:SourceAccount" = data.aws_caller_identity.current.account_id } } } ] })}
resource "aws_iam_role_policy_attachment" "task_execution" { role = aws_iam_role.task_execution.name policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"}Policy Attachment
Section titled “Policy Attachment”The AmazonECSTaskExecutionRolePolicy AWS managed policy grants permissions to:
| Permission | Purpose |
|---|---|
ecr:GetAuthorizationToken | Authenticate to Amazon ECR to pull images |
ecr:BatchGetImage | Download container image layers |
ecr:GetDownloadUrlForLayer | Retrieve image layer download URLs |
logs:CreateLogStream | Create CloudWatch log streams for task output |
logs:PutLogEvents | Write container stdout/stderr to CloudWatch Logs |
Trust Policy Details
Section titled “Trust Policy Details”The trust relationship specifies ecs-tasks.amazonaws.com as the trusted principal. The aws:SourceAccount condition ensures only ECS tasks running in your own AWS account can assume this role, preventing confused deputy scenarios in multi-account environments.
Usage in Express Gateway Service
Section titled “Usage in Express Gateway Service”The Express Gateway Service
The aws_ecs_express_gateway_service Terraform resource that provisions an ECS service with managed ALB, auto scaling, and simplified configuration for HTTP/HTTPS web applications and APIs. references this role through the task definition. ECS uses it during task startup to pull the container image and configure log routing before handing control to the application container.
resource "aws_ecs_express_gateway_service" "this" { # ... primary_container { # ... execution_role_arn = aws_iam_role.task_execution.arn }}