Skip to content

Task Execution Role

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.

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.

main.tf
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"
}

The AmazonECSTaskExecutionRolePolicy AWS managed policy grants permissions to:

PermissionPurpose
ecr:GetAuthorizationTokenAuthenticate to Amazon ECR to pull images
ecr:BatchGetImageDownload container image layers
ecr:GetDownloadUrlForLayerRetrieve image layer download URLs
logs:CreateLogStreamCreate CloudWatch log streams for task output
logs:PutLogEventsWrite container stdout/stderr to CloudWatch Logs

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.

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.

main.tf
resource "aws_ecs_express_gateway_service" "this" {
# ...
primary_container {
# ...
execution_role_arn = aws_iam_role.task_execution.arn
}
}