Skip to content

Instantly share code, notes, and snippets.

@pagameba
Created November 7, 2017 17:50
Show Gist options
  • Save pagameba/16df89b4c72b010cc659d79e1f4e028d to your computer and use it in GitHub Desktop.
Save pagameba/16df89b4c72b010cc659d79e1f4e028d to your computer and use it in GitHub Desktop.
resource "aws_ecs_service" "service" {
name = "${var.name}"
cluster = "${var.ecs_cluster_id}"
task_definition = "${aws_ecs_task_definition.task.arn}"
desired_count = "${var.desired_count}"
iam_role = "${aws_iam_role.ecs_service_role.arn}"
deployment_minimum_healthy_percent = "${var.deployment_minimum_healthy_percent}"
deployment_maximum_percent = "${var.deployment_maximum_percent}"
load_balancer {
target_group_arn = "${var.alb_target_group_arn}"
container_name = "${var.name}"
container_port = "${var.container_port}"
}
placement_constraints = "${var.placement_constraints}"
placement_strategy = "${var.placement_strategy}"
depends_on = ["aws_iam_role_policy_attachment.ecs_service"]
}
resource "aws_ecs_task_definition" "task" {
family = "${var.name}"
container_definitions = <<EOF
[
{
"name": "${var.name}",
"image": "${var.image}:${var.version}",
"cpu": ${var.cpu},
"memory": ${var.memory},
"essential": true,
"portMappings": [
{
"containerPort": ${var.container_port},
"hostPort": ${var.host_port},
"protocol": "tcp"
}
],
"environment": [${join(",", data.template_file.env_vars.*.rendered)}]
}
]
EOF
}
data "template_file" "env_vars" {
count = "${var.num_env_vars}"
template = <<EOF
{"name":"${element(keys(var.env_vars), count.index)}", "value":"${lookup(var.env_vars, element(keys(var.env_vars), count.index))}"}
EOF
}
data "aws_iam_policy_document" "container_assume_role_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs.amazonaws.com"]
}
}
}
resource "aws_iam_role" "ecs_service_role" {
name = "ecs-service-role-${var.name}"
assume_role_policy = "${data.aws_iam_policy_document.container_assume_role_policy.json}"
}
resource "aws_iam_role_policy_attachment" "ecs_autoscaling" {
role = "${aws_iam_role.ecs_service_role.name}"
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceAutoscaleRole"
}
resource "aws_iam_role_policy_attachment" "ecs_service" {
role = "${aws_iam_role.ecs_service_role.name}"
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceRole"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment