craig
craig

Reputation: 3

Pass command as variable to ECS task definition

Is there a way to pass a Docker command as a Terraform variable to the ECS task definition that is defined in Terraform?

Upvotes: 0

Views: 2069

Answers (2)

mohit
mohit

Reputation: 2491

You can try the below method to take the command as a variable with template condition if nothing is passed from the root module. service.json

[
  {
    ...
    ],
    %{ if command != "" }
    "command"  : [${command}],
    %{ endif ~}
    ...
  }
]

container.tf

data "template_file" "container_def" {
  count    = 1
  template = file("${path.module}/service.json")
  vars = {
    command        = var.command != "" ? join(",", formatlist("\"%s\"", var.command)) : ""
  }
}

main.tf

module "example" {
...
     command                 = ["httpd", "-f", "-p", "8080"]
...
}

variables.tf

variable "command" {
  default = ""
}

Upvotes: 0

David Maze
David Maze

Reputation: 158848

According to the aws_ecs_task_definition documentation, the container_definitions property is an unparsed JSON object that's an array of container definitions as you'd pass directly to the AWS APIs. One of the properties of that object is a command.

Paraphrasing the documentation somewhat, you'd come up with a sample task definition like:

resource "aws_ecs_task_definition" "service" {
  family                = "service"
  container_definitions = <<DEFINITIONS
[
  {
    "name": "first",
    "image": "service-first",
    "command": ["httpd", "-f", "-p", "8080"],
    "cpu": 10,
    "memory": 512,
    "essential": true
  }
]
DEFINITIONS
}

Upvotes: 2

Related Questions