ECSをGitHubActionでCI/CDをやる

aws configureとtestrepoをリポジトリーとして作っておく。
まずはECRにpushします。

```Dockerfile
FROM nginx:mainline-alpine

COPY index.html /usr/share/nginx/html/
```

```index.html
Hello World!
```

```
docker build -t hello_world .

docker run -it --rm -p 80:80 hello_world

docker images

aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin アカウント名.dkr.ecr.ap-northeast-1.amazonaws.com

docker tag hello_world アカウント名.dkr.ecr.ap-northeast-1.amazonaws.com/testrepo:latest

docker push アカウント名.dkr.ecr.ap-northeast-1.amazonaws.com/testrepo:latest
```
次にTerraformでECS環境を構築します。
```main.tf
provider "aws" {
  region = "ap-northeast-1" # 東京リージョン（必要に応じて変更）
}

# VPC の設定（簡略化のため既存の VPC を想定）
data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}
resource "aws_ecs_cluster" "app_cluster" {
  name = "app-cluster"
}

resource "aws_ecs_service" "app_service" {
  name            = "app-service"
  cluster         = aws_ecs_cluster.app_cluster.id
  task_definition = aws_ecs_task_definition.app.arn
  launch_type     = "FARGATE"

  network_configuration {
    subnets          = ["subnet-0c0b17fe43556d272 ", "subnet-0e490e7b684f3b4aa"] # VPCのサブネットIDを指定
    security_groups  = ["sg-004dc4b11a48fddcf"] # セキュリティグループIDを指定
    assign_public_ip = true
  }

  desired_count = 1
}

# ECS クラスタ
resource "aws_ecs_cluster" "main" {
  name = "ecs-cluster"
}

# ECS タスク定義
data "aws_iam_role" "ecs_task_execution_role" {
  name = "ecsTaskExecutionRole"
}

resource "aws_ecs_task_definition" "app" {
  family                   = "app-task"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = "256"
  memory                   = "512"
  execution_role_arn       = data.aws_iam_role.ecs_task_execution_role.arn

  container_definitions = jsonencode([
    {
      name      = "app"
      image     = "アカウント名.dkr.ecr.ap-northeast-1.amazonaws.com/testrepo:latest"
      essential = true
      memory    = 512
      cpu       = 256
    }
  ])
}

```

これでHello World！がECSのpublic IPに出ます。
次にこれをgithub Actionでやります。
ECSのGUIの画面でタスク定義のJSONファイルをコピーします。
コピーしたのをtestrepo-task-revision1.jsonにはりつけます。

ツリー構造
```
 .git/
 .github/
 Dockerfile
 README.md
 index.html
 testrepo-task-revision1.json
```

```.github/workflows/deploy-aws.yml

name: Deploy to Amazon ECS

on:
  push:
    branches: [ "main" ]

env:
  AWS_REGION: ap-northeast-1                   # set this to your preferred AWS region, e.g. us-west-1
  ECR_REPOSITORY: testrepo           # set this to your Amazon ECR repository name
  ECS_SERVICE: app-service               # set this to your Amazon ECS service name
  ECS_CLUSTER: app-cluster              # set this to your Amazon ECS cluster name
  ECS_TASK_DEFINITION: testrepo-task-revision1.json 
                                               # file, e.g. .aws/task-definition.json
  CONTAINER_NAME: app         # set this to the name of the container in the
                                               # containerDefinitions section of your task definition

permissions:
  contents: read

jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest
    environment: production

    steps:
    - name: Checkout
      uses: actions/checkout@v4

    - name: Configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: ${{ env.AWS_REGION }}

    - name: Login to Amazon ECR
      id: login-ecr
      uses: aws-actions/amazon-ecr-login@v1

    - name: Build, tag, and push image to Amazon ECR
      id: build-image
      env:
        ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        IMAGE_TAG: ${{ github.sha }}
      run: |
        # Build a docker container and
        # push it to ECR so that it can
        # be deployed to ECS.
        docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
        docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
        echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT

    - name: Fill in the new image ID in the Amazon ECS task definition
      id: task-def
      uses: aws-actions/amazon-ecs-render-task-definition@v1
      with:
        task-definition: ${{ env.ECS_TASK_DEFINITION }}
        container-name: ${{ env.CONTAINER_NAME }}
        image: ${{ steps.build-image.outputs.image }}

    - name: Deploy Amazon ECS task definition
      uses: aws-actions/amazon-ecs-deploy-task-definition@v1
      with:
        task-definition: ${{ steps.task-def.outputs.task-definition }}
        service: ${{ env.ECS_SERVICE }}
        cluster: ${{ env.ECS_CLUSTER }}
        wait-for-service-stability: true
```

index.htmlの内容を変更してこれで準備が整いました。
```
git init
git remote add origin リポジトリのURL
git commit -m'first'
git push origin main
```
でgithubActionが動いてdeployできるはずです。