Search code examples
amazon-web-servicesdockerterraformamazon-ecsdocker-container

How to bind host directory to ECS in terraform


I have been trying to containerise an application on ECS. I am using terraform to build the infrastructure for the same.

Now, I want to mount a host directory to the container. On plain docker i would go about doing this by using docker run -v <host_path>:<path_inside_container>. But I am unable to find the equivalent in terraform for the same.

I have tried the volume directive within aws_ecs_task_definition but I am unable to read/write from/to the host directory.

resource "aws_ecs_task_definition" "my-application"{
    family = <application_family_name>
    task_role_arn = "${aws_iam_role.ecsTaskRole.arn}"
    network_mode  = "host"

    volume {
        name = <application_files>
        host_path = "/home/my_app_dir/"
    }

    container_definitions = <container_definitions>
}

Thanks in advance.


Solution

  • What you need to do is, add a mapping in task definition after you define the volume in resource aws_ecs_task_definition.

    @Amal has answered the question with adding mountPoints in task definition. The sourceVolume in task definition has to be the same name in volume of the resource.

    What I need to mention here is,

    The part of @amal's volume code is copied from Cloudformation templates, but can't be used in terraform. There is no list with maps supported in resource aws_ecs_task_definition currently . Your exist volume code is fine.

    If you need to add more volumes, use this way

    resource "aws_ecs_task_definition" "my-application"{
        family = <application_family_name>
        task_role_arn = "${aws_iam_role.ecsTaskRole.arn}"
        network_mode  = "host"
    
        volume {
            name = <application_files>
            host_path = "/home/my_app_dir/"
        }
    
        volume {
            name = <application_files_2>
            host_path = "/home/my_app_dir-2/"
        }
    
        container_definitions = <container_definitions>
    }