Sub topic 2
Task execution role versus task role
Assume you know Docker, IAM, VPC networking, security groups, and basic AWS CLI usage. This chapter connects those concepts in a Fargate service.
Task execution role versus task role
A task execution role gives the ECS agent permissions needed to start a task. It commonly allows Fargate to pull an image from Amazon ECR, write logs to CloudWatch Logs, and retrieve injected secrets.
A task role gives the application inside the container permission to call AWS APIs. For example, an application might use its task role to read from an S3 bucket. Do not put application permissions on the execution role.
Both roles trust ecs-tasks.amazonaws.com, but their permissions have different owners: the ECS agent uses the execution role, while your application uses the task role.
Networking tasks with `awsvpc`
Fargate tasks use awsvpc networking. Each task receives its own elastic network interface (ENI), private IP address, subnets, and security group rules.
For a web service, place tasks in private subnets and allow the Application Load Balancer's security group to reach the task security group on the application port. The task security group should not allow broad inbound access from the internet.
Sending container logs to CloudWatch Logs
Configure the awslogs driver in the task definition. The execution role needs the CloudWatch Logs permissions. Create the log group first, or configure your deployment process to create it.
{
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789012:role/webAppTaskRole",
"networkMode": "awsvpc",
"containerDefinitions": [{
"name": "web",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/web-app:1.0.0",
"secrets": [{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db"
}],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/web-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "web"
}
}
}]
}Injecting secrets and configuration
Use plain environment entries for non-sensitive configuration, such as APP_ENV. Use secrets for passwords and tokens. ECS retrieves the secret before starting the container and exposes it as an environment variable.
The execution role needs permission to read the referenced Secrets Manager secret. If the application retrieves the secret itself at runtime, that permission belongs on the task role instead.
>``callout note >Environment variables can appear in diagnostic output. Avoid printing secret values in logs. >``
Running a long-lived service
An ECS service maintains a desired number of task replicas. It replaces failed tasks and can attach tasks to a load balancer. A desired count of 2 provides basic redundancy across available subnets.
Exercise
Which role should allow the application to read an S3 bucket?
Show answer
The task role, because the application makes the S3 API call.