Back to all patterns

Table of Contents

About

Development Tool

cloudformation

Type

pattern

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

ECS task execution IAM role that allows mounting an Elastic File System (EFS)

Nathan Peck
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.

# 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.