ECS Task Execution IAM Role for Elastic File System (EFS)

Nathan Peck profile picture
Nathan Peck
Senior Developer Advocate at AWS

The following CloudFormation example shows how to write a task execution role for Amazon Elastic File System (ECS) which allows ECS to mount an Elastic File System to a task.

Language: yaml
# Base task execution role
TaskExecutionRole:
  Type: AWS::IAM::Role
  Properties:
    AssumeRolePolicyDocument:
      Statement:
        - Effect: Allow
          Principal:
            Service: [ecs-tasks.amazonaws.com]
          Action: ['sts:AssumeRole']
          Condition:
            ArnLike:
              aws:SourceArn: !Sub arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:*
            StringEquals:
              aws:SourceAccount: !Ref AWS::AccountId
    ManagedPolicyArns:
      - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

# Grant additional ability to access Elastic File System
TaskAccessToEFS:
  Type: AWS::IAM::Policy
  Properties:
    Roles:
      - !Ref TaskExecutionRole
    PolicyName: AccessSecret
    PolicyDocument:
      Version: '2012-10-17'
      Statement:
        - Effect: Allow
          Action:
            - elasticfilesystem:ClientMount
            - elasticfilesystem:ClientWrite
            - elasticfilesystem:DescribeMountTargets
            - elasticfilesystem:DescribeFileSystems
          Resource: !GetAtt EFSFileSystem.Arn

This role starts out based on the default AmazonECSTaskExecutionRolePolicy managed policy provided by AWS. The base managed role has minimal permissions that allow launching a task and collecting logs, but nothing else.

By attaching additional elasticfilesystem:* actions, you can enable the ECS agent to locate and mount an Elastic File System as part of task startup.

Alternative Patterns

Not quite right for you? Try another way to do this:

AWS Copilot CLI  Launch a task with durable storage, using AWS Copilot

Use AWS Copilot to launch a task that has an attached Elastic File System. This will automatically create the right IAM roles for you.

AWS CloudFormation  Add durable storage to an ECS task, with Amazon Elastic File System

This AWS CloudFormation reference application shows how to define the full Elastic File System connection to Amazon ECS, including the appropriate security group rules.

AWS Cloud Development Kit (CDK)  Durable storage volume for AWS Fargate, using Cloud Development Kit (CDK)

This is an AWS Cloud Development Kit application that helps you to define an ECS task with an attached Elastic File System.