LoginSignup
0
0

More than 3 years have passed since last update.

Terraform で書く CodeBuild -> ECR -> ECS with Vapor その3

Posted at

Terraform で書く CodeBuild -> ECR -> ECS with Vapor その1
Terraform で書く CodeBuild -> ECR -> ECS with Vapor その2

最後に ECS でタスクとサービスを作り、デプロイします。

########################
## ECS
########################
# IAM
resource "aws_iam_role" "my_ecs_role" {
  assume_role_policy = "${file("iam_role/ecs_assume_role_policy.json")}"
  name               = "my_ecs_role"
}

resource "aws_iam_policy" "policy" {
  name        = "test-policy"
  description = "A test policy"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecr:GetAuthorizationToken",
        "ecr:BatchCheckLayerAvailability",
        "ecr:GetDownloadUrlForLayer",
        "ecr:BatchGetImage",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "*"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "test-attach" {
  role = "${aws_iam_role.my_ecs_role.name}"
  policy_arn = "${aws_iam_policy.policy.arn}"
}

# ECS Cluster
resource "aws_ecs_cluster" "ecs_cluster" {
  name = "my-cluster"
}

## ECS Task Definision
data "template_file" "container_definitions" {
  template = <<EOF
[
  {
    "name": "my-container-name",
    "image": "${aws_ecr_repository.repository.repository_url}:latest",
    "essential": true,
    "portMappings": [
      {
        "containerPort": 80,
        "hostPort": 80
      }
    ]
  }
]
EOF
}

resource "aws_ecs_task_definition" "service" {
  family = "service"
  task_role_arn = "${aws_iam_role.my_ecs_role.arn}"
  container_definitions = "${data.template_file.container_definitions.rendered}"
  network_mode = "awsvpc"
  cpu = 256
  memory = 512
  requires_compatibilities = ["FARGATE"]
  execution_role_arn = "${aws_iam_role.my_ecs_role.arn}"
}

## ECS Service
resource "aws_ecs_service" "ecs_service" {
  name = "vapor-service"
  cluster = "${aws_ecs_cluster.ecs_cluster.id}"
  launch_type = "FARGATE"

  task_definition = "${aws_ecs_task_definition.service.arn}"
  desired_count = 3

  load_balancer {
    target_group_arn = "${aws_alb_target_group.target_group.arn}"
    container_name = "my-container-name"
    container_port = 80
  }

  network_configuration {
    subnets = [
      "${aws_subnet.public-a.id}",
      "${aws_subnet.public-c.id}",
    ]

    security_groups = [
      "${aws_security_group.my_security_group.id}",
    ]

    assign_public_ip = true
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0