How can I configure IAM task roles in Amazon ECS to avoid "Access Denied" errors?
4 minute read
How to configure IAM task roles in Amazon ECS to resolve an "Access Denied" error message when my application makes AWS API calls.
If you don't configure IAM task roles correctly, you can receive "Access Denied" error messages when your application makes AWS API calls.
To avoid this error, provide your AWS Identity and Access Management (IAM) task role in the task definition for Amazon Elastic Container Service (Amazon ECS). Your tasks can use this IAM role for AWS API calls. The IAM task role must have all the permissions required by your application. If a task can't find the IAM task role due to configuration issues, then the Amazon Elastic Compute Cloud (Amazon EC2) instance role is used.
To correctly configure IAM roles for your task, check the following:
Confirm that the ECS container agent is running
To confirm that the ECS container agent is running, run the following command:
Turn on IAM roles in your ECS container agent configuration file
1. Open your /etc/ecs/ecs.config file.
2. To turn on IAM roles for tasks in containers with bridge and default network modes, set ECS_ENABLE_TASK_IAM_ROLE to true. See the following example:
3. To turn on IAM roles for tasks in containers with the host network mode, set ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST to true. See the following example:
4. To update the configuration file, restart the AECS container agent by running either of the following commands:
For Amazon ECS-optimized Amazon Linux AMIs:
sudo stop ecs
sudo start ecs
For Amazon ECS-optimized Amazon Linux 2 AMIs:
sudo systemctl restart ecs
Confirm that your IAM policy has the correct trust relationship with your Amazon ECS tasks
Make the credential path environment variable available to non-PID 1 processes
The environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is available only to PID 1 processes within a container. If the container is running multiple processes or init processes (such as wrapper script, start script, or supervisord), the environment variable is unavailable to non-PID 1 processes.
To set your environment variable so that it's available to non-PID 1 processes, export the environment variable in the .profile file. For example, run the following command to export the variable in the Dockerfile for your container image:
RUN echo 'export $(strings /proc/1/environ | grep AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)' >> /root/.profile
Now additional processes can access the environment variable.
Note: There's a dependency on the strings and grep commands when you export the environment variable.