「AWS Hands-on for Beginners Amazon Elastic Container Service 入門 コンテナイメージを作って動かしてみよう」をAWS CLIでやってみる

https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-ECS-2022-reg-event.html?trk=aws_introduction_page

上記、「AWS Hands-on for Beginners Amazon Elastic Container Service 入門 コンテナイメージを作って動かしてみよう」 をAWS CLIでやってみる

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3297641/9e698f65-79ee-93b1-0df7-76309da0d8cf.png)

ハンズオンから引用

:::note warn
以降、CloudShellで実施
:::
# 02 コンテナイメージを作成するための、Cloud9 環境を構築する
## 変数
```bash:コマンド
# Cloud9環境名
CLOUD9_ENVIRONMENT_NAME="h4b-ecs" \
&& echo ${CLOUD9_ENVIRONMENT_NAME}

# インスタンスタイプ
INSTANCE_TYPE="t3.small" \
&& echo ${INSTANCE_TYPE}

# プラットフォーム
CLOUD9_IMAGE_ID="resolve:ssm:/aws/service/cloud9/amis/amazonlinux-2-x86_64" \
&& echo ${CLOUD9_IMAGE_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # Cloud9環境名
[cloudshell-user@ip-10-132-94-73 ~]$ CLOUD9_ENVIRONMENT_NAME="h4b-ecs" \
> && echo ${CLOUD9_ENVIRONMENT_NAME}
h4b-ecs
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # インスタンスタイプ
[cloudshell-user@ip-10-132-94-73 ~]$ INSTANCE_TYPE="t3.small" \
> && echo ${INSTANCE_TYPE}
t3.small
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # プラットフォーム
[cloudshell-user@ip-10-132-94-73 ~]$ CLOUD9_IMAGE_ID="resolve:ssm:/aws/service/cloud9/amis/amazonlinux-2-x86_64" \
> && echo ${CLOUD9_IMAGE_ID}
resolve:ssm:/aws/service/cloud9/amis/amazonlinux-2-x86_64
```
## 作成
```bash:コマンド
# Cloud9環境作成
CLOUD9_ENVIRONMENT_ID=$(
    aws cloud9 create-environment-ec2 \
        --name ${CLOUD9_ENVIRONMENT_NAME} \
        --instance-type ${INSTANCE_TYPE} \
        --image-id ${CLOUD9_IMAGE_ID} \
        --connection-type CONNECT_SSM \
        --automatic-stop-time-minutes 30 \
        --query environmentId \
        --output text
) \
&& echo ${CLOUD9_ENVIRONMENT_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # Cloud9環境作成
[cloudshell-user@ip-10-132-94-73 ~]$ CLOUD9_ENVIRONMENT_ID=$(
>     aws cloud9 create-environment-ec2 \
>         --name ${CLOUD9_ENVIRONMENT_NAME} \
>         --instance-type ${INSTANCE_TYPE} \
>         --image-id ${CLOUD9_IMAGE_ID} \
>         --connection-type CONNECT_SSM \
>         --automatic-stop-time-minutes 30 \
>         --query environmentId \
>         --output text
> ) \
> && echo ${CLOUD9_ENVIRONMENT_ID}
e2fc48dcc1ac453fbeaea7f97c179d65
```
:::note warn
以降、Cloud9で実施
:::
## docker コマンドの確認
```bash:コマンド
docker version

```
```bash:出力
admin:~/environment $ docker version
Client:
 Version:           25.0.5
 API version:       1.44
 Go version:        go1.22.5
 Git commit:        5dc9bcc
 Built:             Mon Jul 29 17:21:34 2024
 OS/Arch:           linux/amd64
 Context:           default

Server:
 Engine:
  Version:          25.0.6
  API version:      1.44 (minimum version 1.24)
  Go version:       go1.22.5
  Git commit:       b08a51f
  Built:            Mon Jul 29 17:22:09 2024
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.7.20
  GitCommit:        8fc6bcff51318944179630522a095cc9dbf9f353
 runc:
  Version:          1.1.13
  GitCommit:        58aa9203c123022138b22cf96540c284876a7910
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
```
# 03 コンテナイメージを作成して動かす その1
## Dockerfile作成
```bash:コマンド
cat << EOF > Dockerfile
FROM ubuntu:18.04

# Install dependencies
RUN apt-get update && \
 apt-get -y install apache2

# Install apache and write hello world message
RUN echo 'Hello World!' > /var/www/html/index.html

# Configure apache
RUN echo '. /etc/apache2/envvars' > /root/run_apache.sh && \
 echo 'mkdir -p /var/run/apache2' >> /root/run_apache.sh && \
 echo 'mkdir -p /var/lock/apache2' >> /root/run_apache.sh && \ 
 echo '/usr/sbin/apache2 -D FOREGROUND' >> /root/run_apache.sh && \ 
 chmod 755 /root/run_apache.sh

EXPOSE 80

CMD /root/run_apache.sh
EOF

```
```bash:出力
admin:~/environment $ cat << EOF > Dockerfile
> FROM ubuntu:18.04
> 
> # Install dependencies
> RUN apt-get update && \
>  apt-get -y install apache2
> 
> # Install apache and write hello world message
> RUN echo 'Hello World!' > /var/www/html/index.html
> 
> # Configure apache
> RUN echo '. /etc/apache2/envvars' > /root/run_apache.sh && \
>  echo 'mkdir -p /var/run/apache2' >> /root/run_apache.sh && \
>  echo 'mkdir -p /var/lock/apache2' >> /root/run_apache.sh && \ 
>  echo '/usr/sbin/apache2 -D FOREGROUND' >> /root/run_apache.sh && \ 
>  chmod 755 /root/run_apache.sh
> 
> EXPOSE 80
> 
> CMD /root/run_apache.sh
> EOF
```
## ノーブレークスペース削除
```bash:コマンド
sed -i "s/$(echo -ne '\u200b')//g" Dockerfile

```
```bash:出力
admin:~/environment $ sed -i "s/$(echo -ne '\u200b')//g" Dockerfile
```
## DockerImage一覧事前確認
```bash:コマンド
docker images

```
```bash:出力
admin:~/environment $ docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
```
## コンテナイメージを作成
```bash:コマンド
docker build -t hello-world .

```
```bash:出力
admin:~/environment $ docker build -t hello-world .
[+] Building 27.8s (8/8) FINISHED                                                                                                                                                                                                     docker:default
 => [internal] load build definition from Dockerfile                                                                                                                                                                                            0.0s
 => => transferring dockerfile: 569B                                                                                                                                                                                                            0.0s
 => [internal] load metadata for docker.io/library/ubuntu:18.04                                                                                                                                                                                 1.8s
 => [internal] load .dockerignore                                                                                                                                                                                                               0.0s
 => => transferring context: 2B                                                                                                                                                                                                                 0.0s
 => [1/4] FROM docker.io/library/ubuntu:18.04@sha256:152dc042452c496007f07ca9127571cb9c29697f42acbfad72324b2bb2e43c98                                                                                                                           2.4s
 => => resolve docker.io/library/ubuntu:18.04@sha256:152dc042452c496007f07ca9127571cb9c29697f42acbfad72324b2bb2e43c98                                                                                                                           0.0s
 => => sha256:152dc042452c496007f07ca9127571cb9c29697f42acbfad72324b2bb2e43c98 1.33kB / 1.33kB                                                                                                                                                  0.0s
 => => sha256:dca176c9663a7ba4c1f0e710986f5a25e672842963d95b960191e2d9f7185ebe 424B / 424B                                                                                                                                                      0.0s
 => => sha256:f9a80a55f492e823bf5d51f1bd5f87ea3eed1cb31788686aa99a2fb61a27af6a 2.30kB / 2.30kB                                                                                                                                                  0.0s
 => => sha256:7c457f213c7634afb95a0fb2410a74b7b5bc0ba527033362c240c7a11bef4331 25.69MB / 25.69MB                                                                                                                                                0.6s
 => => extracting sha256:7c457f213c7634afb95a0fb2410a74b7b5bc0ba527033362c240c7a11bef4331                                                                                                                                                       1.7s
 => [2/4] RUN apt-get update &&  apt-get -y install apache2                                                                                                                                                                                    21.5s
 => [3/4] RUN echo 'Hello World!' > /var/www/html/index.html                                                                                                                                                                                    0.4s 
 => [4/4] RUN echo '. /etc/apache2/envvars' > /root/run_apache.sh &&  echo 'mkdir -p /var/run/apache2' >> /root/run_apache.sh &&  echo 'mkdir -p /var/lock/apache2' >> /root/run_apache.sh &&  echo '/usr/sbin/apache2 -D FOREGROUND' >> /root  0.4s 
 => exporting to image                                                                                                                                                                                                                          1.2s 
 => => exporting layers                                                                                                                                                                                                                         1.2s 
 => => writing image sha256:7b980724c411c2561bac001828833b4308b85c4df7763906d72e79261734087b                                                                                                                                                    0.0s 
 => => naming to docker.io/library/hello-world                                                                                                                                                                                                  0.0s 
```
## DockerImage一覧事後確認
```bash:コマンド
docker images

```
```bash:出力
admin:~/environment $ docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
hello-world   latest    7b980724c411   31 seconds ago   205MB
```
# 04 コンテナイメージを作成して動かす その2
## コンテナ一覧事前確認
```bash:コマンド
docker ps

```
```bash:出力
admin:~/environment $ docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
```
## コンテナ起動
```bash:コマンド
docker run -d -p 8080:80 --name h4b-local-run hello-world

```
```bash:出力
admin:~/environment $ docker run -d -p 8080:80 --name h4b-local-run hello-world
d808c0fbf30b4bd81f7a50d1497335cdb6ed31ab6e1d2a9195ed5fea203268b3
```
## コンテナ一覧事後確認
```bash:コマンド
docker ps

```
```bash:出力
admin:~/environment $ docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED          STATUS         PORTS                                   NAMES
d808c0fbf30b   hello-world   "/bin/sh -c /root/ru…"   10 seconds ago   Up 9 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   h4b-local-run
```
## コンテナ動作確認
```bash:コマンド
curl localhost:8080

```
```bash:出力
admin:~/environment $ curl localhost:8080
Hello World!
```
## コンテナへのログイン
```bash:コマンド
docker exec -i -t h4b-local-run bash

```
```bash:出力
admin:~/environment $ docker exec -i -t h4b-local-run bash
root@d808c0fbf30b:/# 
```
## コンテナ内ファイル確認
```bash:コマンド
pwd
ls -la
cd /root 
ls -la
cat run_apache.sh
cd /var/www/html/
ls -la
cat index.html

```
```bash:出力
root@d808c0fbf30b:/# pwd
/
root@d808c0fbf30b:/# ls -la
total 8
drwxr-xr-x   1 root root   28 Sep  1 03:59 .
drwxr-xr-x   1 root root   28 Sep  1 03:59 ..
-rwxr-xr-x   1 root root    0 Sep  1 03:59 .dockerenv
drwxr-xr-x   2 root root 4096 May 30  2023 bin
drwxr-xr-x   2 root root    6 Apr 24  2018 boot
drwxr-xr-x   5 root root  340 Sep  1 03:59 dev
drwxr-xr-x   1 root root   66 Sep  1 03:59 etc
drwxr-xr-x   2 root root    6 Apr 24  2018 home
drwxr-xr-x   1 root root   45 May 23  2017 lib
drwxr-xr-x   2 root root   34 May 30  2023 lib64
drwxr-xr-x   2 root root    6 May 30  2023 media
drwxr-xr-x   2 root root    6 May 30  2023 mnt
drwxr-xr-x   2 root root    6 May 30  2023 opt
dr-xr-xr-x 187 root root    0 Sep  1 03:59 proc
drwx------   1 root root   27 Sep  1 03:58 root
drwxr-xr-x   1 root root   33 Sep  1 03:59 run
drwxr-xr-x   2 root root 4096 May 30  2023 sbin
drwxr-xr-x   2 root root    6 May 30  2023 srv
dr-xr-xr-x  13 root root    0 Sep  1 03:59 sys
drwxrwxrwt   1 root root    6 Sep  1 03:58 tmp
drwxr-xr-x   1 root root   53 May 30  2023 usr
drwxr-xr-x   1 root root   17 Sep  1 03:58 var
root@d808c0fbf30b:/# cd /root 
root@d808c0fbf30b:~# ls -la
total 12
drwx------ 1 root root   27 Sep  1 03:58 .
drwxr-xr-x 1 root root   28 Sep  1 03:59 ..
-rw-r--r-- 1 root root 3106 Apr  9  2018 .bashrc
-rw-r--r-- 1 root root  148 Aug 17  2015 .profile
-rwxr-xr-x 1 root root  108 Sep  1 03:58 run_apache.sh
root@d808c0fbf30b:~# cat run_apache.sh
. /etc/apache2/envvars
mkdir -p /var/run/apache2
mkdir -p /var/lock/apache2
/usr/sbin/apache2 -D FOREGROUND
root@d808c0fbf30b:~# cd /var/www/html/
root@d808c0fbf30b:/var/www/html# ls -la
total 4
drwxr-xr-x 1 root root 24 Sep  1 03:58 .
drwxr-xr-x 1 root root 18 Sep  1 03:58 ..
-rw-r--r-- 1 root root 13 Sep  1 03:58 index.html
root@d808c0fbf30b:/var/www/html# cat index.html
Hello World!
```
## コンテナからのログアウト
```bash:コマンド
exit

```
```bash:出力
root@d808c0fbf30b:/var/www/html# exit
exit
admin:~/environment $ 
```
:::note warn
以降、CloudShellで実施
:::
# 05 コンテナイメージを、ECR にアップロードする
## プライベートリポジトリ作成
```bash:コマンド
# プライベートリポジトリ名
REPOSITORY_NAME="h4b-ecs-helloworld" \
&& echo ${REPOSITORY_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # プライベートリポジトリ名
[cloudshell-user@ip-10-132-94-73 ~]$ REPOSITORY_NAME="h4b-ecs-helloworld" \
> && echo ${REPOSITORY_NAME}
h4b-ecs-helloworld
```
## 作成
```bash:コマンド
# プライベートリポジトリ作成
aws ecr create-repository \
    --repository-name ${REPOSITORY_NAME} \
    --image-scanning-configuration scanOnPush=true

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # プライベートリポジトリ作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecr create-repository \
>     --repository-name ${REPOSITORY_NAME} \
>     --image-scanning-configuration scanOnPush=true
{
    "repository": {
        "repositoryArn": "arn:aws:ecr:ap-northeast-1:999999999999:repository/h4b-ecs-helloworld",
        "registryId": "999999999999",
        "repositoryName": "h4b-ecs-helloworld",
        "repositoryUri": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld",
        "createdAt": "2024-09-01T04:01:14.519000+00:00",
        "imageTagMutability": "MUTABLE",
        "imageScanningConfiguration": {
            "scanOnPush": true
        },
        "encryptionConfiguration": {
            "encryptionType": "AES256"
        }
    }
}
```
## 確認
```bash:コマンド
# 詳細
aws ecr describe-repositories \
    --repository-names ${REPOSITORY_NAME}

# URI取得
REPOSITORYURI=$(
    aws ecr describe-repositories \
        --repository-names ${REPOSITORY_NAME} \
        --query repositories[].repositoryUri \
        --output text
) \
&& echo ${REPOSITORYURI}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # 詳細
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecr describe-repositories \
>     --repository-names ${REPOSITORY_NAME}
{
    "repositories": [
        {
            "repositoryArn": "arn:aws:ecr:ap-northeast-1:999999999999:repository/h4b-ecs-helloworld",
            "registryId": "999999999999",
            "repositoryName": "h4b-ecs-helloworld",
            "repositoryUri": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld",
            "createdAt": "2024-09-01T04:01:14.519000+00:00",
            "imageTagMutability": "MUTABLE",
            "imageScanningConfiguration": {
                "scanOnPush": true
            },
            "encryptionConfiguration": {
                "encryptionType": "AES256"
            }
        }
    ]
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # URI取得
[cloudshell-user@ip-10-132-94-73 ~]$ REPOSITORYURI=$(
>     aws ecr describe-repositories \
>         --repository-names ${REPOSITORY_NAME} \
>         --query repositories[].repositoryUri \
>         --output text
> ) \
> && echo ${REPOSITORYURI}
999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld
```
## リポジトリ内のイメージ確認
```bash:コマンド
aws ecr list-images --repository-name ${REPOSITORY_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecr list-images --repository-name ${REPOSITORY_NAME}
{
    "imageIds": []
}
```
:::note warn
以降、Cloud9で実施
:::
## コンテナイメージを作成
```bash:コマンド
# リポジトリURI指定
REPOSITORYURI=999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld \
&& echo ${REPOSITORYURI}

# イメージ作成
docker build -t ${REPOSITORYURI}:0.0.1 .

```
```bash:出力
admin:~/environment $ # リポジトリURI指定
admin:~/environment $ REPOSITORYURI=999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld \
> && echo ${REPOSITORYURI}
999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld
admin:~/environment $ 
admin:~/environment $ # イメージ作成
admin:~/environment $ docker build -t ${REPOSITORYURI}:0.0.1 .
[+] Building 0.6s (8/8) FINISHED                                                                                                                                                                                                      docker:default
 => [internal] load build definition from Dockerfile                                                                                                                                                                                            0.0s
 => => transferring dockerfile: 569B                                                                                                                                                                                                            0.0s
 => [internal] load metadata for docker.io/library/ubuntu:18.04                                                                                                                                                                                 0.5s
 => [internal] load .dockerignore                                                                                                                                                                                                               0.0s
 => => transferring context: 2B                                                                                                                                                                                                                 0.0s
 => [1/4] FROM docker.io/library/ubuntu:18.04@sha256:152dc042452c496007f07ca9127571cb9c29697f42acbfad72324b2bb2e43c98                                                                                                                           0.0s
 => CACHED [2/4] RUN apt-get update &&  apt-get -y install apache2                                                                                                                                                                              0.0s
 => CACHED [3/4] RUN echo 'Hello World!' > /var/www/html/index.html                                                                                                                                                                             0.0s
 => CACHED [4/4] RUN echo '. /etc/apache2/envvars' > /root/run_apache.sh &&  echo 'mkdir -p /var/run/apache2' >> /root/run_apache.sh &&  echo 'mkdir -p /var/lock/apache2' >> /root/run_apache.sh &&  echo '/usr/sbin/apache2 -D FOREGROUND' >  0.0s
 => exporting to image                                                                                                                                                                                                                          0.0s
 => => exporting layers                                                                                                                                                                                                                         0.0s
 => => writing image sha256:7b980724c411c2561bac001828833b4308b85c4df7763906d72e79261734087b                                                                                                                                                    0.0s
 => => naming to 999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1                                                                                                                                                     0.0s
```
## DockerImage一覧確認
```bash:コマンド
docker images

```
```bash:出力
admin:~/environment $ docker images
REPOSITORY                                                             TAG       IMAGE ID       CREATED         SIZE
999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld   0.0.1     7b980724c411   4 minutes ago   205MB
hello-world                                                            latest    7b980724c411   4 minutes ago   205MB
```
## ECRログイン
```bash:コマンド
aws ecr get-login-password | docker login --username AWS --password-stdin ${REPOSITORYURI}

```
```bash:出力
admin:~/environment $ aws ecr get-login-password | docker login --username AWS --password-stdin ${REPOSITORYURI}
WARNING! Your password will be stored unencrypted in /home/ec2-user/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
```
## ECRへアップロード
```bash:コマンド
docker push ${REPOSITORYURI}:0.0.1

```
```bash:出力
admin:~/environment $ docker push ${REPOSITORYURI}:0.0.1
The push refers to repository [999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld]
8d652e6bb8c7: Pushed 
063eefad8995: Pushed 
6338b19070f0: Pushed 
548a79621a42: Pushed 
0.0.1: digest: sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7 size: 1155
```
:::note warn
以降、CloudShellで実施
:::
## リポジトリ内のイメージ確認
```bash:コマンド
aws ecr list-images --repository-name ${REPOSITORY_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecr list-images --repository-name ${REPOSITORY_NAME}
{
    "imageIds": [
        {
            "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
            "imageTag": "0.0.1"
        }
    ]
}
```
# 06 VPC の作成
:::note info
VPC名：h4b-ecs
アベイラビリティーゾーン：２
パブリックサブネット：２
プライベートサブネット：０
NATゲートウェイ：なし
VPNエンドポイント：S3ゲートウェイ
:::
## 変数
```bash:コマンド
# VPC名
VPC_NAME="h4b-ecs-vpc" \
&& echo ${VPC_NAME}

# サブネット名
AZ1_PUB_NAME="h4b-ecs-subnet-public1-ap-northeast-1a" \
&& echo ${AZ1_PUB_NAME}

AZ2_PUB_NAME="h4b-ecs-subnet-public2-ap-northeast-1c" \
&& echo ${AZ2_PUB_NAME}

# VPC CIDR block
VPC_CIDR_BLOCK="10.0.0.0/16" \
&& echo ${VPC_CIDR_BLOCK}

# サブネット CIDR block
AZ1_PUB_CIDR_BLOCK="10.0.0.0/20" \
&& echo ${AZ1_PUB_CIDR_BLOCK}

AZ2_PUB_CIDR_BLOCK="10.0.16.0/20" \
&& echo ${AZ2_PUB_CIDR_BLOCK}

# アベイラビリティーゾーン
AZ_1="ap-northeast-1a" \
&& echo ${AZ_1}

AZ_2="ap-northeast-1c" \
&& echo ${AZ_1}

# インターネットゲートウェイ名
IGW_NAME='h4b-ecs-igw' \
&& echo ${IGW_NAME}

# パブリックルートテーブル名
PUB_RT_NAME='h4b-ecs-rtb-public' \
&& echo ${PUB_RT_NAME}

# エンドポイント
END_POINT='h4b-ecs-vpce-s3' \
&& echo ${END_POINT}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # VPC名
[cloudshell-user@ip-10-132-94-73 ~]$ VPC_NAME="h4b-ecs-vpc" \
> && echo ${VPC_NAME}
h4b-ecs-vpc
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # サブネット名
[cloudshell-user@ip-10-132-94-73 ~]$ AZ1_PUB_NAME="h4b-ecs-subnet-public1-ap-northeast-1a" \
> && echo ${AZ1_PUB_NAME}
h4b-ecs-subnet-public1-ap-northeast-1a
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ AZ2_PUB_NAME="h4b-ecs-subnet-public2-ap-northeast-1c" \
> && echo ${AZ2_PUB_NAME}
h4b-ecs-subnet-public2-ap-northeast-1c
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # VPC CIDR block
[cloudshell-user@ip-10-132-94-73 ~]$ VPC_CIDR_BLOCK="10.0.0.0/16" \
> && echo ${VPC_CIDR_BLOCK}
10.0.0.0/16
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # サブネット CIDR block
[cloudshell-user@ip-10-132-94-73 ~]$ AZ1_PUB_CIDR_BLOCK="10.0.0.0/20" \
> && echo ${AZ1_PUB_CIDR_BLOCK}
10.0.0.0/20
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ AZ2_PUB_CIDR_BLOCK="10.0.16.0/20" \
> && echo ${AZ2_PUB_CIDR_BLOCK}
10.0.16.0/20
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # アベイラビリティーゾーン
[cloudshell-user@ip-10-132-94-73 ~]$ AZ_1="ap-northeast-1a" \
> && echo ${AZ_1}
ap-northeast-1a
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ AZ_2="ap-northeast-1c" \
> && echo ${AZ_1}
ap-northeast-1a
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # インターネットゲートウェイ名
[cloudshell-user@ip-10-132-94-73 ~]$ IGW_NAME='h4b-ecs-igw' \
> && echo ${IGW_NAME}
h4b-ecs-igw
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # パブリックルートテーブル名
[cloudshell-user@ip-10-132-94-73 ~]$ PUB_RT_NAME='h4b-ecs-rtb-public' \
> && echo ${PUB_RT_NAME}
h4b-ecs-rtb-public
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # エンドポイント
[cloudshell-user@ip-10-132-94-73 ~]$ END_POINT='h4b-ecs-vpce-s3' \
> && echo ${END_POINT}
h4b-ecs-vpce-s3
```
## VPC作成
```bash:コマンド
# VPC作成
aws ec2 create-vpc \
    --cidr-block ${VPC_CIDR_BLOCK} \
    --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${VPC_NAME}}]"

# ID取得
VPC_ID=$(
    aws ec2 describe-vpcs \
        --filters "Name=tag:Name,Values=${VPC_NAME}" \
        --query "Vpcs[0].VpcId" \
        --output text\
)\
&& echo ${VPC_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # VPC作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 create-vpc \
>     --cidr-block ${VPC_CIDR_BLOCK} \
>     --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${VPC_NAME}}]"
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-0e7d97fbb33a62ce1",
        "State": "pending",
        "VpcId": "vpc-0753931619fb7ce9c",
        "OwnerId": "999999999999",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-084235b745e1877eb",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Name",
                "Value": "h4b-ecs-vpc"
            }
        ]
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ID取得
[cloudshell-user@ip-10-132-94-73 ~]$ VPC_ID=$(
>     aws ec2 describe-vpcs \
>         --filters "Name=tag:Name,Values=${VPC_NAME}" \
>         --query "Vpcs[0].VpcId" \
>         --output text\
> )\
> && echo ${VPC_ID}
vpc-0753931619fb7ce9c
```
## サブネット作成
```bash:コマンド
# 第1アベイラビリティーゾーンのパブリックサブネット
aws ec2 create-subnet \
    --vpc-id ${VPC_ID} \
    --cidr-block ${AZ1_PUB_CIDR_BLOCK} \
    --availability-zone ${AZ_1} \
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ1_PUB_NAME}}]"

# 第2アベイラビリティーゾーンのパブリックサブネット
aws ec2 create-subnet \
    --vpc-id ${VPC_ID} \
    --cidr-block ${AZ2_PUB_CIDR_BLOCK} \
    --availability-zone ${AZ_2} \
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ2_PUB_NAME}}]"

# ID取得
# 第1アベイラビリティーゾーンのパブリックサブネット
AZ1_PUB_ID=$( \
    aws ec2 describe-subnets \
      --filters Name=vpc-id,Values=${VPC_ID} \
                Name=tag:Name,Values="${AZ1_PUB_NAME}" \
      --query "Subnets[].SubnetId" \
      --output text \
) \
&& echo ${AZ1_PUB_ID}

# 第2アベイラビリティーゾーンのパブリックサブネット
AZ2_PUB_ID=$( \
    aws ec2 describe-subnets \
      --filters Name=vpc-id,Values=${VPC_ID} \
                Name=tag:Name,Values="${AZ2_PUB_NAME}" \
      --query "Subnets[].SubnetId" \
      --output text \
) \
&& echo ${AZ2_PUB_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # 第1アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 create-subnet \
>     --vpc-id ${VPC_ID} \
>     --cidr-block ${AZ1_PUB_CIDR_BLOCK} \
>     --availability-zone ${AZ_1} \
>     --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ1_PUB_NAME}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1a",
        "AvailabilityZoneId": "apne1-az4",
        "AvailableIpAddressCount": 4091,
        "CidrBlock": "10.0.0.0/20",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-00212e581b04af6ee",
        "VpcId": "vpc-0753931619fb7ce9c",
        "OwnerId": "999999999999",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "h4b-ecs-subnet-public1-ap-northeast-1a"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:999999999999:subnet/subnet-00212e581b04af6ee",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # 第2アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 create-subnet \
>     --vpc-id ${VPC_ID} \
>     --cidr-block ${AZ2_PUB_CIDR_BLOCK} \
>     --availability-zone ${AZ_2} \
>     --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ2_PUB_NAME}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1c",
        "AvailabilityZoneId": "apne1-az1",
        "AvailableIpAddressCount": 4091,
        "CidrBlock": "10.0.16.0/20",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0d47fd735f5035e47",
        "VpcId": "vpc-0753931619fb7ce9c",
        "OwnerId": "999999999999",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "h4b-ecs-subnet-public2-ap-northeast-1c"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:999999999999:subnet/subnet-0d47fd735f5035e47",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ID取得
[cloudshell-user@ip-10-132-94-73 ~]$ # 第1アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-94-73 ~]$ AZ1_PUB_ID=$( \
>     aws ec2 describe-subnets \
>       --filters Name=vpc-id,Values=${VPC_ID} \
>                 Name=tag:Name,Values="${AZ1_PUB_NAME}" \
>       --query "Subnets[].SubnetId" \
>       --output text \
> ) \
> && echo ${AZ1_PUB_ID}
subnet-00212e581b04af6ee
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # 第2アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-94-73 ~]$ AZ2_PUB_ID=$( \
>     aws ec2 describe-subnets \
>       --filters Name=vpc-id,Values=${VPC_ID} \
>                 Name=tag:Name,Values="${AZ2_PUB_NAME}" \
>       --query "Subnets[].SubnetId" \
>       --output text \
> ) \
> && echo ${AZ2_PUB_ID}
subnet-0d47fd735f5035e47
```
## インターネットゲートウェイ作成
```bash:コマンド
# インターネットゲートウェイ作成
aws ec2 create-internet-gateway \
    --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${IGW_NAME}}]"

# インターネットゲートウェイID取得
IGW_ID=$(
    aws ec2 describe-internet-gateways \
        --filters Name=tag:Name,Values=${IGW_NAME} \
        --query "InternetGateways[].InternetGatewayId" \
        --output text
) \
&& echo ${IGW_ID}

# インターネットゲートウェイをVPCにアタッチ
aws ec2 attach-internet-gateway \
    --vpc-id ${VPC_ID} \
    --internet-gateway-id ${IGW_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # インターネットゲートウェイ作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 create-internet-gateway \
>     --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${IGW_NAME}}]"
{
    "InternetGateway": {
        "Attachments": [],
        "InternetGatewayId": "igw-01a5e3395fc1ffbc2",
        "OwnerId": "999999999999",
        "Tags": [
            {
                "Key": "Name",
                "Value": "h4b-ecs-igw"
            }
        ]
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # インターネットゲートウェイID取得
[cloudshell-user@ip-10-132-94-73 ~]$ IGW_ID=$(
>     aws ec2 describe-internet-gateways \
>         --filters Name=tag:Name,Values=${IGW_NAME} \
>         --query "InternetGateways[].InternetGatewayId" \
>         --output text
> ) \
> && echo ${IGW_ID}
igw-01a5e3395fc1ffbc2
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # インターネットゲートウェイをVPCにアタッチ
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 attach-internet-gateway \
>     --vpc-id ${VPC_ID} \
>     --internet-gateway-id ${IGW_ID}
```
## ルートテーブル作成
```bash:コマンド
# ルートテーブル作成
aws ec2 create-route-table \
    --vpc-id ${VPC_ID} \
    --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${PUB_RT_NAME}}]"

# ルートテーブルID取得
PUB_RT_ID=$(
    aws ec2 describe-route-tables \
        --filters Name=vpc-id,Values=${VPC_ID} \
                  Name=tag:Name,Values="${PUB_RT_NAME}" \
        --query "RouteTables[].RouteTableId" \
        --output text
) \
&& echo ${PUB_RT_ID}

# デフォルトルート作成
aws ec2 create-route \
    --route-table-id ${PUB_RT_ID} \
    --destination-cidr-block 0.0.0.0/0 \
    --gateway-id ${IGW_ID}

# サブネット関連付け
aws ec2 associate-route-table \
    --subnet-id ${AZ1_PUB_ID} \
    --route-table-id ${PUB_RT_ID}

aws ec2 associate-route-table \
    --subnet-id ${AZ2_PUB_ID} \
    --route-table-id ${PUB_RT_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ルートテーブル作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 create-route-table \
>     --vpc-id ${VPC_ID} \
>     --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${PUB_RT_NAME}}]"
{
    "RouteTable": {
        "Associations": [],
        "PropagatingVgws": [],
        "RouteTableId": "rtb-0bfe376ef3698c1a5",
        "Routes": [
            {
                "DestinationCidrBlock": "10.0.0.0/16",
                "GatewayId": "local",
                "Origin": "CreateRouteTable",
                "State": "active"
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "h4b-ecs-rtb-public"
            }
        ],
        "VpcId": "vpc-0753931619fb7ce9c",
        "OwnerId": "999999999999"
    },
    "ClientToken": "dab14392-63fd-4c69-8674-48907142f8eb"
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ルートテーブルID取得
[cloudshell-user@ip-10-132-94-73 ~]$ PUB_RT_ID=$(
>     aws ec2 describe-route-tables \
>         --filters Name=vpc-id,Values=${VPC_ID} \
>                   Name=tag:Name,Values="${PUB_RT_NAME}" \
>         --query "RouteTables[].RouteTableId" \
>         --output text
> ) \
> && echo ${PUB_RT_ID}
rtb-0bfe376ef3698c1a5
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # デフォルトルート作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 create-route \
>     --route-table-id ${PUB_RT_ID} \
>     --destination-cidr-block 0.0.0.0/0 \
>     --gateway-id ${IGW_ID}
{
    "Return": true
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # サブネット関連付け
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 associate-route-table \
>     --subnet-id ${AZ1_PUB_ID} \
>     --route-table-id ${PUB_RT_ID}
{
    "AssociationId": "rtbassoc-03319c297b41b360a",
    "AssociationState": {
        "State": "associated"
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 associate-route-table \
>     --subnet-id ${AZ2_PUB_ID} \
>     --route-table-id ${PUB_RT_ID}
{
    "AssociationId": "rtbassoc-08e5994a386c0816d",
    "AssociationState": {
        "State": "associated"
    }
}
```
## セキュリティグループルールの追加
```bash:コマンド
# 変数設定 (セキュリティグループID取得)
SECURITY_GROUP_NAME="default" \
&& echo ${SECURITY_GROUP_NAME}

SECURITY_GROUP_ID=$( \
    aws ec2 describe-security-groups \
        --filters Name=vpc-id,Values=${VPC_ID} \
                  Name=group-name,Values=${SECURITY_GROUP_NAME} \
        --query "SecurityGroups[].GroupId" \
        --output text
) \
&& echo ${SECURITY_GROUP_ID}

# ルール追加
aws ec2 authorize-security-group-ingress \
    --group-id ${SECURITY_GROUP_ID} \
    --protocol tcp \
    --port 80 \
    --cidr 0.0.0.0/0

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # 変数設定 (セキュリティグループID取得)
[cloudshell-user@ip-10-132-94-73 ~]$ SECURITY_GROUP_NAME="default" \
> && echo ${SECURITY_GROUP_NAME}
default
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ SECURITY_GROUP_ID=$( \
>     aws ec2 describe-security-groups \
>         --filters Name=vpc-id,Values=${VPC_ID} \
>                   Name=group-name,Values=${SECURITY_GROUP_NAME} \
>         --query "SecurityGroups[].GroupId" \
>         --output text
> ) \
> && echo ${SECURITY_GROUP_ID}
sg-0439ac82bbca00d99
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ルール追加
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 authorize-security-group-ingress \
>     --group-id ${SECURITY_GROUP_ID} \
>     --protocol tcp \
>     --port 80 \
>     --cidr 0.0.0.0/0
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0271d410d3bd0275f",
            "GroupId": "sg-0439ac82bbca00d99",
            "GroupOwnerId": "999999999999",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}
```
# 07 ECS クラスター・タスク定義の作成
## 変数
```bash:コマンド
# IAMロール名
ROLE_NAME="ecsTaskExecutionRole" \
&& echo ${ROLE_NAME}

# ポリシーARN
POLICY_ARN="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" \
&& echo ${POLICY_ARN}

# クラスター名
CLUSTER_NAME="h4b-ecs-cluster" \
&& echo ${CLUSTER_NAME}

# タスク定義ファミリー
TASK_REGISTER_FAMILY="h4b-ecs-task-definition" \
&& echo ${TASK_REGISTER_FAMILY}

# コンテナ名
CONTAINER_NAME="apache-helloworld" \
&& echo ${CONTAINER_NAME}

# アカウントID
ACCOUNT_ID="999999999999" \
&& echo ${ACCOUNT_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # IAMロール名
[cloudshell-user@ip-10-132-94-73 ~]$ ROLE_NAME="ecsTaskExecutionRole" \
> && echo ${ROLE_NAME}
ecsTaskExecutionRole
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ポリシーARN
[cloudshell-user@ip-10-132-94-73 ~]$ POLICY_ARN="arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" \
> && echo ${POLICY_ARN}
arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # クラスター名
[cloudshell-user@ip-10-132-94-73 ~]$ CLUSTER_NAME="h4b-ecs-cluster" \
> && echo ${CLUSTER_NAME}
h4b-ecs-cluster
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク定義ファミリー
[cloudshell-user@ip-10-132-94-73 ~]$ TASK_REGISTER_FAMILY="h4b-ecs-task-definition" \
> && echo ${TASK_REGISTER_FAMILY}
h4b-ecs-task-definition
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # コンテナ名
[cloudshell-user@ip-10-132-94-73 ~]$ CONTAINER_NAME="apache-helloworld" \
> && echo ${CONTAINER_NAME}
apache-helloworld
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # アカウントID
[cloudshell-user@ip-10-132-94-73 ~]$ ACCOUNT_ID="999999999999" \
> && echo ${ACCOUNT_ID}
999999999999
```
## IAMロール作成
```bash:コマンド
# 信頼関係ポリシードキュメントの作成
ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "ecs-tasks.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
EOF
) \
&& echo ${ASSUME_ROLE_POLICY_DOCUMENT}

# JSONフォーマットの確認
echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool

# IAMロールの作成
aws iam create-role \
    --role-name ${ROLE_NAME} \
    --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}"

# ARN取得
ROLE_ARN=$(
    aws iam get-role \
        --role-name ${ROLE_NAME} \
        --query 'Role.Arn' --output text
) \
&& echo ${ROLE_ARN}

# IAMロールにポリシーをアタッチ
aws iam attach-role-policy \
    --role-name ${ROLE_NAME} \
    --policy-arn ${POLICY_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # 信頼関係ポリシードキュメントの作成
[cloudshell-user@ip-10-132-94-73 ~]$ ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
> {
>     "Version": "2008-10-17",
>     "Statement": [
>         {
>             "Sid": "",
>             "Effect": "Allow",
>             "Principal": {
>                 "Service": "ecs-tasks.amazonaws.com"
>             },
>             "Action": "sts:AssumeRole"
>         }
>     ]
> }
> EOF
> ) \
> && echo ${ASSUME_ROLE_POLICY_DOCUMENT}
{ "Version": "2008-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "ecs-tasks.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-132-94-73 ~]$ echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "ecs-tasks.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # IAMロールの作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws iam create-role \
>     --role-name ${ROLE_NAME} \
>     --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}"
{
    "Role": {
        "Path": "/",
        "RoleName": "ecsTaskExecutionRole",
        "RoleId": "AROAWFKRCMKOSRQ57SWHC",
        "Arn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole",
        "CreateDate": "2024-09-01T04:07:15+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2008-10-17",
            "Statement": [
                {
                    "Sid": "",
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "ecs-tasks.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ARN取得
[cloudshell-user@ip-10-132-94-73 ~]$ ROLE_ARN=$(
>     aws iam get-role \
>         --role-name ${ROLE_NAME} \
>         --query 'Role.Arn' --output text
> ) \
> && echo ${ROLE_ARN}
arn:aws:iam::999999999999:role/ecsTaskExecutionRole
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # IAMロールにポリシーをアタッチ
[cloudshell-user@ip-10-132-94-73 ~]$ aws iam attach-role-policy \
>     --role-name ${ROLE_NAME} \
>     --policy-arn ${POLICY_ARN}
```
## ECSクラスターの作成
```bash:コマンド
# ECSクラスターの作成
aws ecs create-cluster \
    --cluster-name ${CLUSTER_NAME} 

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ECSクラスターの作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs create-cluster \
>     --cluster-name ${CLUSTER_NAME} 
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
        "clusterName": "h4b-ecs-cluster",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "runningTasksCount": 0,
        "pendingTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "disabled"
            }
        ],
        "capacityProviders": [],
        "defaultCapacityProviderStrategy": []
    }
}
```
## タスク定義の作成
### タスク定義JSON
```bash:コマンド
# タスク定義JSON
TASK_JSON=$(cat << EOF
{
    "family": "${TASK_REGISTER_FAMILY}",
    "containerDefinitions": [
        {
            "name": "${CONTAINER_NAME}",
            "image": "${REPOSITORYURI}:0.0.1",
            "cpu": 0,
            "portMappings": [
                {
                    "name": "${CONTAINER_NAME}-80-tcp",
                    "containerPort": 80,
                    "hostPort": 80,
                    "protocol": "tcp",
                    "appProtocol": "http"
                }
            ],
            "essential": true,
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "/ecs/${TASK_REGISTER_FAMILY}",
                    "mode": "non-blocking",
                    "awslogs-create-group": "true",
                    "max-buffer-size": "25m",
                    "awslogs-region": "ap-northeast-1",
                    "awslogs-stream-prefix": "ecs"
                },
                "secretOptions": []
            },
            "systemControls": []
        }
    ],
    "executionRoleArn": "${ROLE_ARN}",
    "networkMode": "awsvpc",
    "requiresCompatibilities": [
        "FARGATE"
    ],
    "cpu": "1024",
    "memory": "3072",
    "runtimePlatform": {
        "cpuArchitecture": "X86_64",
        "operatingSystemFamily": "LINUX"
    }
}
EOF
) \
&& echo ${TASK_JSON}

# JSONフォーマットの確認
echo ${TASK_JSON} | python -m json.tool

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク定義JSON
[cloudshell-user@ip-10-132-94-73 ~]$ TASK_JSON=$(cat << EOF
> {
>     "family": "${TASK_REGISTER_FAMILY}",
>     "containerDefinitions": [
>         {
>             "name": "${CONTAINER_NAME}",
>             "image": "${REPOSITORYURI}:0.0.1",
>             "cpu": 0,
>             "portMappings": [
>                 {
>                     "name": "${CONTAINER_NAME}-80-tcp",
>                     "containerPort": 80,
>                     "hostPort": 80,
>                     "protocol": "tcp",
>                     "appProtocol": "http"
>                 }
>             ],
>             "essential": true,
>             "environment": [],
>             "environmentFiles": [],
>             "mountPoints": [],
>             "volumesFrom": [],
>             "ulimits": [],
>             "logConfiguration": {
>                 "logDriver": "awslogs",
>                 "options": {
>                     "awslogs-group": "/ecs/${TASK_REGISTER_FAMILY}",
>                     "mode": "non-blocking",
>                     "awslogs-create-group": "true",
>                     "max-buffer-size": "25m",
>                     "awslogs-region": "ap-northeast-1",
>                     "awslogs-stream-prefix": "ecs"
>                 },
>                 "secretOptions": []
>             },
>             "systemControls": []
>         }
>     ],
>     "executionRoleArn": "${ROLE_ARN}",
>     "networkMode": "awsvpc",
>     "requiresCompatibilities": [
>         "FARGATE"
>     ],
>     "cpu": "1024",
>     "memory": "3072",
>     "runtimePlatform": {
>         "cpuArchitecture": "X86_64",
>         "operatingSystemFamily": "LINUX"
>     }
> }
> EOF
> ) \
> && echo ${TASK_JSON}
{ "family": "h4b-ecs-task-definition", "containerDefinitions": [ { "name": "apache-helloworld", "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1", "cpu": 0, "portMappings": [ { "name": "apache-helloworld-80-tcp", "containerPort": 80, "hostPort": 80, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [], "environmentFiles": [], "mountPoints": [], "volumesFrom": [], "ulimits": [], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/h4b-ecs-task-definition", "mode": "non-blocking", "awslogs-create-group": "true", "max-buffer-size": "25m", "awslogs-region": "ap-northeast-1", "awslogs-stream-prefix": "ecs" }, "secretOptions": [] }, "systemControls": [] } ], "executionRoleArn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole", "networkMode": "awsvpc", "requiresCompatibilities": [ "FARGATE" ], "cpu": "1024", "memory": "3072", "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" } }
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-132-94-73 ~]$ echo ${TASK_JSON} | python -m json.tool
{
    "family": "h4b-ecs-task-definition",
    "containerDefinitions": [
        {
            "name": "apache-helloworld",
            "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
            "cpu": 0,
            "portMappings": [
                {
                    "name": "apache-helloworld-80-tcp",
                    "containerPort": 80,
                    "hostPort": 80,
                    "protocol": "tcp",
                    "appProtocol": "http"
                }
            ],
            "essential": true,
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "/ecs/h4b-ecs-task-definition",
                    "mode": "non-blocking",
                    "awslogs-create-group": "true",
                    "max-buffer-size": "25m",
                    "awslogs-region": "ap-northeast-1",
                    "awslogs-stream-prefix": "ecs"
                },
                "secretOptions": []
            },
            "systemControls": []
        }
    ],
    "executionRoleArn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole",
    "networkMode": "awsvpc",
    "requiresCompatibilities": [
        "FARGATE"
    ],
    "cpu": "1024",
    "memory": "3072",
    "runtimePlatform": {
        "cpuArchitecture": "X86_64",
        "operatingSystemFamily": "LINUX"
    }
}
```
### 作成
```bash:コマンド
# タスク定義の作成
aws ecs register-task-definition \
    --cli-input-json "${TASK_JSON}" \
    --no-cli-pager

# タスク定義のARN取得
TASK_DEFINITION_ARN=$(
    aws ecs describe-task-definition \
        --task-definition ${TASK_REGISTER_FAMILY} \
        --query taskDefinition.taskDefinitionArn \
        --output text
) \
&& echo ${TASK_DEFINITION_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク定義の作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs register-task-definition \
>     --cli-input-json "${TASK_JSON}" \
>     --no-cli-pager
{
    "taskDefinition": {
        "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "containerDefinitions": [
            {
                "name": "apache-helloworld",
                "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                "cpu": 0,
                "portMappings": [
                    {
                        "containerPort": 80,
                        "hostPort": 80,
                        "protocol": "tcp",
                        "name": "apache-helloworld-80-tcp",
                        "appProtocol": "http"
                    }
                ],
                "essential": true,
                "environment": [],
                "environmentFiles": [],
                "mountPoints": [],
                "volumesFrom": [],
                "ulimits": [],
                "logConfiguration": {
                    "logDriver": "awslogs",
                    "options": {
                        "awslogs-group": "/ecs/h4b-ecs-task-definition",
                        "mode": "non-blocking",
                        "awslogs-create-group": "true",
                        "max-buffer-size": "25m",
                        "awslogs-region": "ap-northeast-1",
                        "awslogs-stream-prefix": "ecs"
                    },
                    "secretOptions": []
                },
                "systemControls": []
            }
        ],
        "family": "h4b-ecs-task-definition",
        "executionRoleArn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole",
        "networkMode": "awsvpc",
        "revision": 11,
        "volumes": [],
        "status": "ACTIVE",
        "requiresAttributes": [
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
            },
            {
                "name": "ecs.capability.execution-role-awslogs"
            },
            {
                "name": "com.amazonaws.ecs.capability.ecr-auth"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28"
            },
            {
                "name": "ecs.capability.execution-role-ecr-pull"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
            },
            {
                "name": "ecs.capability.task-eni"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
            }
        ],
        "placementConstraints": [],
        "compatibilities": [
            "EC2",
            "FARGATE"
        ],
        "runtimePlatform": {
            "cpuArchitecture": "X86_64",
            "operatingSystemFamily": "LINUX"
        },
        "requiresCompatibilities": [
            "FARGATE"
        ],
        "cpu": "1024",
        "memory": "3072",
        "registeredAt": "2024-09-01T04:08:23.830000+00:00",
        "registeredBy": "arn:aws:iam::999999999999:user/admin"
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク定義のARN取得
[cloudshell-user@ip-10-132-94-73 ~]$ TASK_DEFINITION_ARN=$(
>     aws ecs describe-task-definition \
>         --task-definition ${TASK_REGISTER_FAMILY} \
>         --query taskDefinition.taskDefinitionArn \
>         --output text
> ) \
> && echo ${TASK_DEFINITION_ARN}
arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11
```
### 確認
```bash:コマンド
# タスク定義の確認
aws ecs describe-task-definition \
    --task-definition ${TASK_REGISTER_FAMILY} \
    --no-cli-pager

# 最新のタスク定義リビジョン番号を取得
TASKDEFINITION_REVISION_NO=$(
    aws ecs describe-task-definition \
        --task-definition ${TASK_REGISTER_FAMILY} \
        --query 'taskDefinition.revision'
) \
&& echo ${TASKDEFINITION_REVISION_NO}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク定義の確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-task-definition \
>     --task-definition ${TASK_REGISTER_FAMILY} \
>     --no-cli-pager
{
    "taskDefinition": {
        "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "containerDefinitions": [
            {
                "name": "apache-helloworld",
                "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                "cpu": 0,
                "portMappings": [
                    {
                        "containerPort": 80,
                        "hostPort": 80,
                        "protocol": "tcp",
                        "name": "apache-helloworld-80-tcp",
                        "appProtocol": "http"
                    }
                ],
                "essential": true,
                "environment": [],
                "environmentFiles": [],
                "mountPoints": [],
                "volumesFrom": [],
                "ulimits": [],
                "logConfiguration": {
                    "logDriver": "awslogs",
                    "options": {
                        "awslogs-group": "/ecs/h4b-ecs-task-definition",
                        "mode": "non-blocking",
                        "awslogs-create-group": "true",
                        "max-buffer-size": "25m",
                        "awslogs-region": "ap-northeast-1",
                        "awslogs-stream-prefix": "ecs"
                    },
                    "secretOptions": []
                },
                "systemControls": []
            }
        ],
        "family": "h4b-ecs-task-definition",
        "executionRoleArn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole",
        "networkMode": "awsvpc",
        "revision": 11,
        "volumes": [],
        "status": "ACTIVE",
        "requiresAttributes": [
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
            },
            {
                "name": "ecs.capability.execution-role-awslogs"
            },
            {
                "name": "com.amazonaws.ecs.capability.ecr-auth"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28"
            },
            {
                "name": "ecs.capability.execution-role-ecr-pull"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
            },
            {
                "name": "ecs.capability.task-eni"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
            }
        ],
        "placementConstraints": [],
        "compatibilities": [
            "EC2",
            "FARGATE"
        ],
        "runtimePlatform": {
            "cpuArchitecture": "X86_64",
            "operatingSystemFamily": "LINUX"
        },
        "requiresCompatibilities": [
            "FARGATE"
        ],
        "cpu": "1024",
        "memory": "3072",
        "registeredAt": "2024-09-01T04:08:23.830000+00:00",
        "registeredBy": "arn:aws:iam::999999999999:user/admin"
    },
    "tags": []
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # 最新のタスク定義リビジョン番号を取得
[cloudshell-user@ip-10-132-94-73 ~]$ TASKDEFINITION_REVISION_NO=$(
>     aws ecs describe-task-definition \
>         --task-definition ${TASK_REGISTER_FAMILY} \
>         --query 'taskDefinition.revision'
> ) \
> && echo ${TASKDEFINITION_REVISION_NO}
11
```
# 08 サービスの作成・ブラウザからアクセス
:::note info
ファミリー：h4b-ecs-task-definition
サービス名：h4b-ecs-service
必要なタスク：2
ロードバランサーの種類：Application Load Balancer
ロードバランサー名：h4b-ecs-alb
ポート：80
プロトコル：HTTP
ターゲットグループ名：h4b-ecs-targetgroup
プロトコル：HTTP
:::
## 変数
```bash:コマンド
# ターゲットタイプ
Target_GROUP_TYPE="ip" \
&& echo ${Target_GROUP_TYPE}

# ターゲットグループ名
Target_GROUP_NAME="h4b-ecs-targetgroup" \
&& echo ${Target_GROUP_NAME}

# ターゲットグループ プロトコル
Target_GROUP_PROTOCOL="HTTP" \
&& echo ${Target_GROUP_PROTOCOL}

# ターゲットグループ ポート
Target_GROUP_PORT="80" \
&& echo ${Target_GROUP_PORT}

# ターゲットグループ プロトコルバージョン
Target_GROUP_PROTOCOLVERSION="HTTP1" \
&& echo ${Target_GROUP_PROTOCOLVERSION}

# ヘルスチェックプロトコル
HEALTH_CHECK_PROTOCOL="HTTP" \
&& echo ${HEALTH_CHECK_PROTOCOL}

# ロードバランサー名
LB_NAME="h4b-ecs-alb" \
&& echo ${LB_NAME}

# リスナー プロトコル
LISTENER_PROTOCOL="HTTP" \
&& echo ${LISTENER_PROTOCOL}

# リスナー ポート
LISTENER_PORT="80" \
&& echo ${LISTENER_PORT}

# サービス名
SERVICE_NAME="h4b-ecs-service" \
&& echo ${SERVICE_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットタイプ
[cloudshell-user@ip-10-132-94-73 ~]$ Target_GROUP_TYPE="ip" \
> && echo ${Target_GROUP_TYPE}
ip
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットグループ名
[cloudshell-user@ip-10-132-94-73 ~]$ Target_GROUP_NAME="h4b-ecs-targetgroup" \
> && echo ${Target_GROUP_NAME}
h4b-ecs-targetgroup
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットグループ プロトコル
[cloudshell-user@ip-10-132-94-73 ~]$ Target_GROUP_PROTOCOL="HTTP" \
> && echo ${Target_GROUP_PROTOCOL}
HTTP
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットグループ ポート
[cloudshell-user@ip-10-132-94-73 ~]$ Target_GROUP_PORT="80" \
> && echo ${Target_GROUP_PORT}
80
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットグループ プロトコルバージョン
[cloudshell-user@ip-10-132-94-73 ~]$ Target_GROUP_PROTOCOLVERSION="HTTP1" \
> && echo ${Target_GROUP_PROTOCOLVERSION}
HTTP1
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ヘルスチェックプロトコル
[cloudshell-user@ip-10-132-94-73 ~]$ HEALTH_CHECK_PROTOCOL="HTTP" \
> && echo ${HEALTH_CHECK_PROTOCOL}
HTTP
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ロードバランサー名
[cloudshell-user@ip-10-132-94-73 ~]$ LB_NAME="h4b-ecs-alb" \
> && echo ${LB_NAME}
h4b-ecs-alb
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # リスナー プロトコル
[cloudshell-user@ip-10-132-94-73 ~]$ LISTENER_PROTOCOL="HTTP" \
> && echo ${LISTENER_PROTOCOL}
HTTP
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # リスナー ポート
[cloudshell-user@ip-10-132-94-73 ~]$ LISTENER_PORT="80" \
> && echo ${LISTENER_PORT}
80
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # サービス名
[cloudshell-user@ip-10-132-94-73 ~]$ SERVICE_NAME="h4b-ecs-service" \
> && echo ${SERVICE_NAME}
h4b-ecs-service
```
## ターゲットグループ作成
```bash:コマンド
# ターゲットグループ作成
aws elbv2 create-target-group \
    --name ${Target_GROUP_NAME} \
    --protocol ${Target_GROUP_PROTOCOL} \
    --port ${Target_GROUP_PORT} \
    --vpc-id ${VPC_ID} \
    --target-type ${Target_GROUP_TYPE} \
    --health-check-protocol ${HEALTH_CHECK_PROTOCOL}

# ARN取得
TARGET_GROUP_ARN=$(
    aws elbv2 describe-target-groups \
        --names ${Target_GROUP_NAME} \
        --query 'TargetGroups[*].TargetGroupArn' \
        --output text
) \
&& echo ${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットグループ作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws elbv2 create-target-group \
>     --name ${Target_GROUP_NAME} \
>     --protocol ${Target_GROUP_PROTOCOL} \
>     --port ${Target_GROUP_PORT} \
>     --vpc-id ${VPC_ID} \
>     --target-type ${Target_GROUP_TYPE} \
>     --health-check-protocol ${HEALTH_CHECK_PROTOCOL}
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
            "TargetGroupName": "h4b-ecs-targetgroup",
            "Protocol": "HTTP",
            "Port": 80,
            "VpcId": "vpc-0753931619fb7ce9c",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/",
            "Matcher": {
                "HttpCode": "200"
            },
            "TargetType": "ip",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ARN取得
[cloudshell-user@ip-10-132-94-73 ~]$ TARGET_GROUP_ARN=$(
>     aws elbv2 describe-target-groups \
>         --names ${Target_GROUP_NAME} \
>         --query 'TargetGroups[*].TargetGroupArn' \
>         --output text
> ) \
> && echo ${TARGET_GROUP_ARN}
arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c
```
## ALBの作成
```bash:コマンド
# ロードバランサー作成
aws elbv2 create-load-balancer \
    --name ${LB_NAME} \
    --type application \
    --scheme internet-facing \
    --ip-address-type ipv4 \
    --subnets ${AZ1_PUB_ID} ${AZ2_PUB_ID} \
    --security-groups ${SECURITY_GROUP_ID}

# ARN取得
LB_ARN=$(
    aws elbv2 describe-load-balancers \
        --names ${LB_NAME} \
        --query 'LoadBalancers[*].LoadBalancerArn' \
        --output text
) \
&& echo ${LB_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ロードバランサー作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws elbv2 create-load-balancer \
>     --name ${LB_NAME} \
>     --type application \
>     --scheme internet-facing \
>     --ip-address-type ipv4 \
>     --subnets ${AZ1_PUB_ID} ${AZ2_PUB_ID} \
>     --security-groups ${SECURITY_GROUP_ID}
{
    "LoadBalancers": [
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/h4b-ecs-alb/3a43861bfe018cab",
            "DNSName": "h4b-ecs-alb-2111226423.ap-northeast-1.elb.amazonaws.com",
            "CanonicalHostedZoneId": "Z14GRHDCWA56QT",
            "CreatedTime": "2024-09-01T04:09:54.417000+00:00",
            "LoadBalancerName": "h4b-ecs-alb",
            "Scheme": "internet-facing",
            "VpcId": "vpc-0753931619fb7ce9c",
            "State": {
                "Code": "provisioning"
            },
            "Type": "application",
            "AvailabilityZones": [
                {
                    "ZoneName": "ap-northeast-1a",
                    "SubnetId": "subnet-00212e581b04af6ee",
                    "LoadBalancerAddresses": []
                },
                {
                    "ZoneName": "ap-northeast-1c",
                    "SubnetId": "subnet-0d47fd735f5035e47",
                    "LoadBalancerAddresses": []
                }
            ],
            "SecurityGroups": [
                "sg-0439ac82bbca00d99"
            ],
            "IpAddressType": "ipv4"
        }
    ]
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ARN取得
[cloudshell-user@ip-10-132-94-73 ~]$ LB_ARN=$(
>     aws elbv2 describe-load-balancers \
>         --names ${LB_NAME} \
>         --query 'LoadBalancers[*].LoadBalancerArn' \
>         --output text
> ) \
> && echo ${LB_ARN}
arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/h4b-ecs-alb/3a43861bfe018cab
```
## リスナーの追加
```bash:コマンド
# リスナーの追加
aws elbv2 create-listener \
    --load-balancer-arn ${LB_ARN} \
    --protocol ${LISTENER_PROTOCOL} \
    --port ${LISTENER_PORT} \
    --default-actions Type=forward,TargetGroupArn=${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # リスナーの追加
[cloudshell-user@ip-10-132-94-73 ~]$ aws elbv2 create-listener \
>     --load-balancer-arn ${LB_ARN} \
>     --protocol ${LISTENER_PROTOCOL} \
>     --port ${LISTENER_PORT} \
>     --default-actions Type=forward,TargetGroupArn=${TARGET_GROUP_ARN}
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/h4b-ecs-alb/3a43861bfe018cab/2fb7a73b60570861",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/h4b-ecs-alb/3a43861bfe018cab",
            "Port": 80,
            "Protocol": "HTTP",
            "DefaultActions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ]
        }
    ]
}
```
## ネットワーク設定用JSON
```bash:コマンド
# ネットワーク設定
NETWORK_CONFIGURATION_JSON=$(cat << EOF
{
    "awsvpcConfiguration": {
        "subnets": [
            "${AZ1_PUB_ID}",
            "${AZ2_PUB_ID}"
        ],
        "securityGroups": [
            "${SECURITY_GROUP_ID}"
        ],
        "assignPublicIp": "ENABLED"
    }
}
EOF
) \
&& echo ${NETWORK_CONFIGURATION_JSON}

# JSONフォーマットの確認
echo ${NETWORK_CONFIGURATION_JSON} | python -m json.tool

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ネットワーク設定
[cloudshell-user@ip-10-132-94-73 ~]$ NETWORK_CONFIGURATION_JSON=$(cat << EOF
> {
>     "awsvpcConfiguration": {
>         "subnets": [
>             "${AZ1_PUB_ID}",
>             "${AZ2_PUB_ID}"
>         ],
>         "securityGroups": [
>             "${SECURITY_GROUP_ID}"
>         ],
>         "assignPublicIp": "ENABLED"
>     }
> }
> EOF
> ) \
> && echo ${NETWORK_CONFIGURATION_JSON}
{ "awsvpcConfiguration": { "subnets": [ "subnet-00212e581b04af6ee", "subnet-0d47fd735f5035e47" ], "securityGroups": [ "sg-0439ac82bbca00d99" ], "assignPublicIp": "ENABLED" } }
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-132-94-73 ~]$ echo ${NETWORK_CONFIGURATION_JSON} | python -m json.tool
{
    "awsvpcConfiguration": {
        "subnets": [
            "subnet-00212e581b04af6ee",
            "subnet-0d47fd735f5035e47"
        ],
        "securityGroups": [
            "sg-0439ac82bbca00d99"
        ],
        "assignPublicIp": "ENABLED"
    }
}
```
## ロードバランシング設定用JSON
```bash:コマンド
# ロードバランシング設定
LOAD_BALANCERS_JSON=$(cat << EOF
{
    "targetGroupArn": "${TARGET_GROUP_ARN}",
    "containerName": "${CONTAINER_NAME}",
    "containerPort": 80
}
EOF
) \
&& echo ${LOAD_BALANCERS_JSON}

# JSONフォーマットの確認
echo ${LOAD_BALANCERS_JSON} | python -m json.tool

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ロードバランシング設定
[cloudshell-user@ip-10-132-94-73 ~]$ LOAD_BALANCERS_JSON=$(cat << EOF
> {
>     "targetGroupArn": "${TARGET_GROUP_ARN}",
>     "containerName": "${CONTAINER_NAME}",
>     "containerPort": 80
> }
> EOF
> ) \
> && echo ${LOAD_BALANCERS_JSON}
{ "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c", "containerName": "apache-helloworld", "containerPort": 80 }
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-132-94-73 ~]$ echo ${LOAD_BALANCERS_JSON} | python -m json.tool
{
    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
    "containerName": "apache-helloworld",
    "containerPort": 80
}
```
## クラスター内サービスの作成
```bash:コマンド
# サービスの作成
aws ecs create-service \
    --cluster ${CLUSTER_NAME} \
    --service-name ${SERVICE_NAME} \
    --task-definition ${TASK_DEFINITION_ARN} \
    --desired-count 2 \
    --launch-type FARGATE \
    --network-configuration "${NETWORK_CONFIGURATION_JSON}" \
    --load-balancers "${LOAD_BALANCERS_JSON}" \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # サービスの作成
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs create-service \
>     --cluster ${CLUSTER_NAME} \
>     --service-name ${SERVICE_NAME} \
>     --task-definition ${TASK_DEFINITION_ARN} \
>     --desired-count 2 \
>     --launch-type FARGATE \
>     --network-configuration "${NETWORK_CONFIGURATION_JSON}" \
>     --load-balancers "${LOAD_BALANCERS_JSON}" \
>     --no-cli-pager
{
    "service": {
        "serviceArn": "arn:aws:ecs:ap-northeast-1:999999999999:service/h4b-ecs-cluster/h4b-ecs-service",
        "serviceName": "h4b-ecs-service",
        "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
        "loadBalancers": [
            {
                "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                "containerName": "apache-helloworld",
                "containerPort": 80
            }
        ],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 0,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": false,
                "rollback": false
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "deployments": [
            {
                "id": "ecs-svc/2975423510966026190",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
                "desiredCount": 0,
                "pendingCount": 0,
                "runningCount": 0,
                "failedTasks": 0,
                "createdAt": "2024-09-01T04:11:29.087000+00:00",
                "updatedAt": "2024-09-01T04:11:29.087000+00:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-00212e581b04af6ee",
                            "subnet-0d47fd735f5035e47"
                        ],
                        "securityGroups": [
                            "sg-0439ac82bbca00d99"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "IN_PROGRESS",
                "rolloutStateReason": "ECS deployment ecs-svc/2975423510966026190 in progress."
            }
        ],
        "roleArn": "arn:aws:iam::999999999999:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [],
        "createdAt": "2024-09-01T04:11:29.087000+00:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-00212e581b04af6ee",
                    "subnet-0d47fd735f5035e47"
                ],
                "securityGroups": [
                    "sg-0439ac82bbca00d99"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::999999999999:user/admin",
        "enableECSManagedTags": false,
        "propagateTags": "NONE",
        "enableExecuteCommand": false
    }
}
```
## クラスター内サービスの確認
### クラスター内サービスの確認
```bash:コマンド
# サービスの確認
aws ecs describe-services \
    --cluster ${CLUSTER_NAME} \
    --services ${SERVICE_NAME} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # サービスの確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-services \
>     --cluster ${CLUSTER_NAME} \
>     --services ${SERVICE_NAME} \
>     --no-cli-pager
{
    "services": [
        {
            "serviceArn": "arn:aws:ecs:ap-northeast-1:999999999999:service/h4b-ecs-cluster/h4b-ecs-service",
            "serviceName": "h4b-ecs-service",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "loadBalancers": [
                {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                    "containerName": "apache-helloworld",
                    "containerPort": 80
                }
            ],
            "serviceRegistries": [],
            "status": "ACTIVE",
            "desiredCount": 2,
            "runningCount": 0,
            "pendingCount": 1,
            "launchType": "FARGATE",
            "platformVersion": "LATEST",
            "platformFamily": "Linux",
            "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "deploymentConfiguration": {
                "deploymentCircuitBreaker": {
                    "enable": false,
                    "rollback": false
                },
                "maximumPercent": 200,
                "minimumHealthyPercent": 100
            },
            "deployments": [
                {
                    "id": "ecs-svc/2975423510966026190",
                    "status": "PRIMARY",
                    "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
                    "desiredCount": 1,
                    "pendingCount": 1,
                    "runningCount": 0,
                    "failedTasks": 0,
                    "createdAt": "2024-09-01T04:11:29.087000+00:00",
                    "updatedAt": "2024-09-01T04:11:40.593000+00:00",
                    "launchType": "FARGATE",
                    "platformVersion": "1.4.0",
                    "platformFamily": "Linux",
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-00212e581b04af6ee",
                                "subnet-0d47fd735f5035e47"
                            ],
                            "securityGroups": [
                                "sg-0439ac82bbca00d99"
                            ],
                            "assignPublicIp": "ENABLED"
                        }
                    },
                    "rolloutState": "IN_PROGRESS",
                    "rolloutStateReason": "ECS deployment ecs-svc/2975423510966026190 in progress."
                }
            ],
            "roleArn": "arn:aws:iam::999999999999:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
            "events": [
                {
                    "id": "c9a01a56-f61c-4a48-8b0b-871a6400cad4",
                    "createdAt": "2024-09-01T04:11:41.475000+00:00",
                    "message": "(service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c)."
                }
            ],
            "createdAt": "2024-09-01T04:11:29.087000+00:00",
            "placementConstraints": [],
            "placementStrategy": [],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-00212e581b04af6ee",
                        "subnet-0d47fd735f5035e47"
                    ],
                    "securityGroups": [
                        "sg-0439ac82bbca00d99"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            },
            "healthCheckGracePeriodSeconds": 0,
            "schedulingStrategy": "REPLICA",
            "deploymentController": {
                "type": "ECS"
            },
            "createdBy": "arn:aws:iam::999999999999:user/admin",
            "enableECSManagedTags": false,
            "propagateTags": "NONE",
            "enableExecuteCommand": false
        }
    ],
    "failures": []
}
```
### クラスター内サービス一覧
```bash:コマンド
# サービス一覧
aws ecs list-services \
    --cluster ${CLUSTER_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # サービス一覧
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs list-services \
>     --cluster ${CLUSTER_NAME}
{
    "serviceArns": [
        "arn:aws:ecs:ap-northeast-1:999999999999:service/h4b-ecs-cluster/h4b-ecs-service"
    ]
}
```
### タスクリストの確認
```bash:コマンド
# タスクリストの確認
aws ecs list-tasks \
    --cluster ${CLUSTER_NAME} \
    --service-name ${SERVICE_NAME}

# タスクリストの取得
TASK_LISTS=$(
    aws ecs list-tasks \
    --cluster ${CLUSTER_NAME} \
    --service-name ${SERVICE_NAME} \
    --query taskArns \
    --output text
) \
&& echo ${TASK_LISTS}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスクリストの確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs list-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --service-name ${SERVICE_NAME}
{
    "taskArns": [
        "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
        "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c"
    ]
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスクリストの取得
[cloudshell-user@ip-10-132-94-73 ~]$ TASK_LISTS=$(
>     aws ecs list-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --service-name ${SERVICE_NAME} \
>     --query taskArns \
>     --output text
> ) \
> && echo ${TASK_LISTS}
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c
```
### タスク詳細の確認
```bash:コマンド
# タスク詳細の確認
aws ecs describe-tasks \
    --cluster ${CLUSTER_NAME} \
    --tasks ${TASK_LISTS} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク詳細の確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --tasks ${TASK_LISTS} \
>     --no-cli-pager
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "08b1ce55-2d34-4baa-91fe-80214bcd5c10",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-00212e581b04af6ee"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-09bfdad6866cb6295"
                        },
                        {
                            "name": "macAddress",
                            "value": "06:43:c7:bc:69:b7"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.13.115"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "ap-northeast-1a",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2024-09-01T04:12:43.823000+00:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c/4797e8e3-6b3a-402a-ae40-b3b9a0c1e980",
                    "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld@sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "runtimeId": "37dd830477fc4f5b8e11bbdfac88ae8c-860549998",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "08b1ce55-2d34-4baa-91fe-80214bcd5c10",
                            "privateIpv4Address": "10.0.13.115"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2024-09-01T04:12:39.953000+00:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:h4b-ecs-service",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "apache-helloworld"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2024-09-01T04:12:50.738000+00:00",
            "pullStoppedAt": "2024-09-01T04:12:59.740000+00:00",
            "startedAt": "2024-09-01T04:13:11.382000+00:00",
            "startedBy": "ecs-svc/2975423510966026190",
            "tags": [],
            "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "version": 4,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        },
        {
            "attachments": [
                {
                    "id": "3c68c53e-a087-41a4-99a7-7e290d06646a",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-0d47fd735f5035e47"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-0e2aec3c63efa1abf"
                        },
                        {
                            "name": "macAddress",
                            "value": "0a:b1:89:d3:4a:f5"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.16.55"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "ap-northeast-1c",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2024-09-01T04:11:45.072000+00:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c/79371dae-14ff-4567-9449-d093df27a8cf",
                    "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                    "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "runtimeId": "96f27181cb8e480793a548b98447e44c-860549998",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "3c68c53e-a087-41a4-99a7-7e290d06646a",
                            "privateIpv4Address": "10.0.16.55"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2024-09-01T04:11:41.378000+00:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:h4b-ecs-service",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "apache-helloworld"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2024-09-01T04:12:00.423000+00:00",
            "pullStoppedAt": "2024-09-01T04:12:06.322000+00:00",
            "startedAt": "2024-09-01T04:12:28.976000+00:00",
            "startedBy": "ecs-svc/2975423510966026190",
            "tags": [],
            "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "version": 5,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        }
    ],
    "failures": []
}
```
### サービスのDNS名を取得
```bash:コマンド
# サービスのDNS名を取得
SERVICE_URL=$(
    aws elbv2 describe-load-balancers \
        --load-balancer-arn ${LB_ARN} \
        --query 'LoadBalancers[].DNSName' \
        --output text
) \
&& echo ${SERVICE_URL}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # サービスのDNS名を取得
[cloudshell-user@ip-10-132-94-73 ~]$ SERVICE_URL=$(
>     aws elbv2 describe-load-balancers \
>         --load-balancer-arn ${LB_ARN} \
>         --query 'LoadBalancers[].DNSName' \
>         --output text
> ) \
> && echo ${SERVICE_URL}
h4b-ecs-alb-2111226423.ap-northeast-1.elb.amazonaws.com
```
### アクセス確認
```bash:コマンド
curl ${SERVICE_URL}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ curl ${SERVICE_URL}
Hello World!
```
### サービスイベント確認
```bash:コマンド
aws ecs describe-services \
    --cluster ${CLUSTER_NAME} \
    --services ${SERVICE_NAME} \
    --query 'services[0].events[*].[id, createdAt, message]' \
    --output table

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-services \
>     --cluster ${CLUSTER_NAME} \
>     --services ${SERVICE_NAME} \
>     --query 'services[0].events[*].[id, createdAt, message]' \
>     --output table
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                                                     DescribeServices                                                                                                                     |
+--------------------------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  b1d2cf97-622c-4dc1-9bf7-30b2be8ebcec|  2024-09-01T04:13:26.555000+00:00 |  (service h4b-ecs-service) has reached a steady state.                                                                                                                        |
|  68fc1a52-add2-4bd9-bec7-1b94f352d9bc|  2024-09-01T04:13:26.554000+00:00 |  (service h4b-ecs-service) (deployment ecs-svc/2975423510966026190) deployment completed.                                                                                     |
|  5f6758fd-977b-4811-b9c6-8033c98e85bf|  2024-09-01T04:13:07.843000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)   |
|  712ea0fb-172a-41e5-aff3-3aa2c148bc31|  2024-09-01T04:12:40.035000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 37dd830477fc4f5b8e11bbdfac88ae8c).                                                                                      |
|  e18f719e-c9b0-40ae-a618-49f6b3b0c277|  2024-09-01T04:12:20.525000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)   |
|  c9a01a56-f61c-4a48-8b0b-871a6400cad4|  2024-09-01T04:11:41.475000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c).                                                                                      |
+--------------------------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
```
# 09 コンテナの自動復旧、スケールアウトをやってみる
## タスク1のアクセス確認
```bash:コマンド
# タスク1 ID抽出
TASK1_ID=$(echo ${TASK_LISTS} | awk '{print $1}') \
&& echo ${TASK1_ID}

# タスク1のインタフェースID取得
NETWORK_INTERFACE1_ID=$(
    aws ecs describe-tasks \
        --cluster ${CLUSTER_NAME} \
        --tasks ${TASK1_ID} \
        --query 'tasks[].attachments[].details[?name==`networkInterfaceId`].value' \
        --output text
) \
&& echo ${NETWORK_INTERFACE1_ID} 

# タスク1のパブリックIP取得
TASK1_PUBLIC_IP=$(
    aws ec2 describe-network-interfaces \
        --network-interface-ids ${NETWORK_INTERFACE1_ID}  \
        --query 'NetworkInterfaces[].Association.PublicIp' \
        --output text
) \
&& echo ${TASK1_PUBLIC_IP}
 
# タスク1のアクセス確認
curl ${TASK1_PUBLIC_IP}
 
```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1 ID抽出
[cloudshell-user@ip-10-132-94-73 ~]$ TASK1_ID=$(echo ${TASK_LISTS} | awk '{print $1}') \
> && echo ${TASK1_ID}
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のインタフェースID取得
[cloudshell-user@ip-10-132-94-73 ~]$ NETWORK_INTERFACE1_ID=$(
>     aws ecs describe-tasks \
>         --cluster ${CLUSTER_NAME} \
>         --tasks ${TASK1_ID} \
>         --query 'tasks[].attachments[].details[?name==`networkInterfaceId`].value' \
>         --output text
> ) \
> && echo ${NETWORK_INTERFACE1_ID} 
eni-09bfdad6866cb6295
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のパブリックIP取得
[cloudshell-user@ip-10-132-94-73 ~]$ TASK1_PUBLIC_IP=$(
>     aws ec2 describe-network-interfaces \
>         --network-interface-ids ${NETWORK_INTERFACE1_ID}  \
>         --query 'NetworkInterfaces[].Association.PublicIp' \
>         --output text
> ) \
> && echo ${TASK1_PUBLIC_IP}
43.207.235.181
[cloudshell-user@ip-10-132-94-73 ~]$  
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のアクセス確認
[cloudshell-user@ip-10-132-94-73 ~]$ curl ${TASK1_PUBLIC_IP}
Hello World!
```
## タスク2のアクセス確認
```bash:コマンド
# タスク2 ID抽出
TASK2_ID=$(echo ${TASK_LISTS} | awk '{print $2}') \
&& echo ${TASK2_ID}

# タスク1のインタフェースID取得
NETWORK_INTERFACE2_ID=$(
    aws ecs describe-tasks \
        --cluster ${CLUSTER_NAME} \
        --tasks ${TASK2_ID} \
        --query 'tasks[].attachments[].details[?name==`networkInterfaceId`].value' \
        --output text
) \
&& echo ${NETWORK_INTERFACE2_ID} 

# タスク1のパブリックIP取得
TASK2_PUBLIC_IP=$(
    aws ec2 describe-network-interfaces \
        --network-interface-ids ${NETWORK_INTERFACE2_ID}  \
        --query 'NetworkInterfaces[].Association.PublicIp' \
        --output text
) \
&& echo ${TASK2_PUBLIC_IP}
 
# タスク1のアクセス確認
curl ${TASK2_PUBLIC_IP}
 
```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク2 ID抽出
[cloudshell-user@ip-10-132-94-73 ~]$ TASK2_ID=$(echo ${TASK_LISTS} | awk '{print $2}') \
> && echo ${TASK2_ID}
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のインタフェースID取得
[cloudshell-user@ip-10-132-94-73 ~]$ NETWORK_INTERFACE2_ID=$(
>     aws ecs describe-tasks \
>         --cluster ${CLUSTER_NAME} \
>         --tasks ${TASK2_ID} \
>         --query 'tasks[].attachments[].details[?name==`networkInterfaceId`].value' \
>         --output text
> ) \
> && echo ${NETWORK_INTERFACE2_ID} 
eni-0e2aec3c63efa1abf
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のパブリックIP取得
[cloudshell-user@ip-10-132-94-73 ~]$ TASK2_PUBLIC_IP=$(
>     aws ec2 describe-network-interfaces \
>         --network-interface-ids ${NETWORK_INTERFACE2_ID}  \
>         --query 'NetworkInterfaces[].Association.PublicIp' \
>         --output text
> ) \
> && echo ${TASK2_PUBLIC_IP}
43.207.59.249
[cloudshell-user@ip-10-132-94-73 ~]$  
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のアクセス確認
[cloudshell-user@ip-10-132-94-73 ~]$ curl ${TASK2_PUBLIC_IP}
Hello World!
```
## 疑似障害
### 疎通確認 (別タブで実施)
:::note warn
- uriは適宜変更
- ステータスコードを返すようにコマンドを変更
:::
```bash:コマンド
url=h4b-ecs-alb-2111226423.ap-northeast-1.elb.amazonaws.com
while true; do echo -n "$(date) "; curl -o /dev/null -s -w "%{http_code}\n" ${url}; sleep 1s; done

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ url=h4b-ecs-alb-2111226423.ap-northeast-1.elb.amazonaws.com
[cloudshell-user@ip-10-132-94-73 ~]$ while true; do echo -n "$(date) "; curl -o /dev/null -s -w "%{http_code}\n" ${url}; sleep 1s; done
Sun Sep  1 05:01:45 AM UTC 2024 200
Sun Sep  1 05:01:46 AM UTC 2024 200
Sun Sep  1 05:01:47 AM UTC 2024 200
Sun Sep  1 05:01:48 AM UTC 2024 200
Sun Sep  1 05:01:50 AM UTC 2024 200
Sun Sep  1 05:01:51 AM UTC 2024 200
Sun Sep  1 05:01:52 AM UTC 2024 200
Sun Sep  1 05:01:53 AM UTC 2024 200
Sun Sep  1 05:01:54 AM UTC 2024 200
Sun Sep  1 05:01:55 AM UTC 2024 200
Sun Sep  1 05:01:56 AM UTC 2024 200
Sun Sep  1 05:01:57 AM UTC 2024 200
Sun Sep  1 05:01:58 AM UTC 2024 200
Sun Sep  1 05:01:59 AM UTC 2024 200
Sun Sep  1 05:02:00 AM UTC 2024 200
Sun Sep  1 05:02:01 AM UTC 2024 200
Sun Sep  1 05:02:02 AM UTC 2024 200
Sun Sep  1 05:02:03 AM UTC 2024 200
Sun Sep  1 05:02:04 AM UTC 2024 200
Sun Sep  1 05:02:05 AM UTC 2024 200
Sun Sep  1 05:02:06 AM UTC 2024 200
Sun Sep  1 05:02:07 AM UTC 2024 200
Sun Sep  1 05:02:08 AM UTC 2024 200
Sun Sep  1 05:02:09 AM UTC 2024 200
Sun Sep  1 05:02:10 AM UTC 2024 200
Sun Sep  1 05:02:11 AM UTC 2024 200
Sun Sep  1 05:02:12 AM UTC 2024 200
Sun Sep  1 05:02:13 AM UTC 2024 200
Sun Sep  1 05:02:14 AM UTC 2024 200
Sun Sep  1 05:02:15 AM UTC 2024 200
Sun Sep  1 05:02:16 AM UTC 2024 200
Sun Sep  1 05:02:17 AM UTC 2024 200
Sun Sep  1 05:02:18 AM UTC 2024 200
Sun Sep  1 05:02:19 AM UTC 2024 200
Sun Sep  1 05:02:20 AM UTC 2024 200
Sun Sep  1 05:02:21 AM UTC 2024 200
Sun Sep  1 05:02:22 AM UTC 2024 200
Sun Sep  1 05:02:23 AM UTC 2024 200
Sun Sep  1 05:02:24 AM UTC 2024 200
Sun Sep  1 05:02:25 AM UTC 2024 200
Sun Sep  1 05:02:26 AM UTC 2024 200
Sun Sep  1 05:02:27 AM UTC 2024 200
Sun Sep  1 05:02:28 AM UTC 2024 200
Sun Sep  1 05:02:29 AM UTC 2024 200
Sun Sep  1 05:02:30 AM UTC 2024 200
Sun Sep  1 05:02:31 AM UTC 2024 200
Sun Sep  1 05:02:32 AM UTC 2024 200
Sun Sep  1 05:02:34 AM UTC 2024 200
Sun Sep  1 05:02:35 AM UTC 2024 200
Sun Sep  1 05:02:36 AM UTC 2024 200
Sun Sep  1 05:02:37 AM UTC 2024 200
Sun Sep  1 05:02:38 AM UTC 2024 200
Sun Sep  1 05:02:39 AM UTC 2024 200
Sun Sep  1 05:02:40 AM UTC 2024 200
Sun Sep  1 05:02:41 AM UTC 2024 200
Sun Sep  1 05:02:42 AM UTC 2024 200
Sun Sep  1 05:02:43 AM UTC 2024 200
Sun Sep  1 05:02:44 AM UTC 2024 200
Sun Sep  1 05:02:45 AM UTC 2024 200
Sun Sep  1 05:02:46 AM UTC 2024 200
Sun Sep  1 05:02:47 AM UTC 2024 200
Sun Sep  1 05:02:48 AM UTC 2024 200
Sun Sep  1 05:02:49 AM UTC 2024 200
Sun Sep  1 05:02:50 AM UTC 2024 200
Sun Sep  1 05:02:51 AM UTC 2024 200
Sun Sep  1 05:02:52 AM UTC 2024 200
Sun Sep  1 05:02:53 AM UTC 2024 200
Sun Sep  1 05:02:54 AM UTC 2024 200
Sun Sep  1 05:02:55 AM UTC 2024 200
Sun Sep  1 05:02:56 AM UTC 2024 200
Sun Sep  1 05:02:57 AM UTC 2024 200
Sun Sep  1 05:02:58 AM UTC 2024 200
Sun Sep  1 05:02:59 AM UTC 2024 200
Sun Sep  1 05:03:00 AM UTC 2024 200
Sun Sep  1 05:03:01 AM UTC 2024 200
Sun Sep  1 05:03:02 AM UTC 2024 200
Sun Sep  1 05:03:03 AM UTC 2024 200
Sun Sep  1 05:03:04 AM UTC 2024 200
Sun Sep  1 05:03:05 AM UTC 2024 200
Sun Sep  1 05:03:06 AM UTC 2024 200
Sun Sep  1 05:03:07 AM UTC 2024 200
Sun Sep  1 05:03:08 AM UTC 2024 200
Sun Sep  1 05:03:09 AM UTC 2024 200
Sun Sep  1 05:03:11 AM UTC 2024 200
Sun Sep  1 05:03:12 AM UTC 2024 200
Sun Sep  1 05:03:13 AM UTC 2024 200
Sun Sep  1 05:03:14 AM UTC 2024 200
Sun Sep  1 05:03:15 AM UTC 2024 200
Sun Sep  1 05:03:16 AM UTC 2024 200
Sun Sep  1 05:03:17 AM UTC 2024 200
Sun Sep  1 05:03:18 AM UTC 2024 200
Sun Sep  1 05:03:19 AM UTC 2024 200
Sun Sep  1 05:03:20 AM UTC 2024 200
Sun Sep  1 05:03:21 AM UTC 2024 200
Sun Sep  1 05:03:22 AM UTC 2024 200
Sun Sep  1 05:03:23 AM UTC 2024 200
Sun Sep  1 05:03:24 AM UTC 2024 200
Sun Sep  1 05:03:25 AM UTC 2024 200
Sun Sep  1 05:03:26 AM UTC 2024 200
Sun Sep  1 05:03:27 AM UTC 2024 200
Sun Sep  1 05:03:28 AM UTC 2024 200
Sun Sep  1 05:03:29 AM UTC 2024 200
Sun Sep  1 05:03:30 AM UTC 2024 200
Sun Sep  1 05:03:31 AM UTC 2024 200
Sun Sep  1 05:03:32 AM UTC 2024 200
Sun Sep  1 05:03:33 AM UTC 2024 200
Sun Sep  1 05:03:34 AM UTC 2024 200
Sun Sep  1 05:03:35 AM UTC 2024 200
Sun Sep  1 05:03:36 AM UTC 2024 200
Sun Sep  1 05:03:37 AM UTC 2024 200
Sun Sep  1 05:03:38 AM UTC 2024 200
Sun Sep  1 05:03:39 AM UTC 2024 200
Sun Sep  1 05:03:40 AM UTC 2024 200
Sun Sep  1 05:03:41 AM UTC 2024 200
Sun Sep  1 05:03:42 AM UTC 2024 200
Sun Sep  1 05:03:43 AM UTC 2024 200
Sun Sep  1 05:03:44 AM UTC 2024 200
Sun Sep  1 05:03:45 AM UTC 2024 200
Sun Sep  1 05:03:46 AM UTC 2024 200
Sun Sep  1 05:03:47 AM UTC 2024 200
Sun Sep  1 05:03:48 AM UTC 2024 200
Sun Sep  1 05:03:49 AM UTC 2024 200
Sun Sep  1 05:03:50 AM UTC 2024 200
Sun Sep  1 05:03:52 AM UTC 2024 200
Sun Sep  1 05:03:53 AM UTC 2024 200
Sun Sep  1 05:03:54 AM UTC 2024 200
Sun Sep  1 05:03:55 AM UTC 2024 200
Sun Sep  1 05:03:56 AM UTC 2024 200
Sun Sep  1 05:03:57 AM UTC 2024 200
Sun Sep  1 05:03:58 AM UTC 2024 200
Sun Sep  1 05:03:59 AM UTC 2024 200
Sun Sep  1 05:04:00 AM UTC 2024 200
Sun Sep  1 05:04:01 AM UTC 2024 200
Sun Sep  1 05:04:02 AM UTC 2024 200
Sun Sep  1 05:04:03 AM UTC 2024 200
Sun Sep  1 05:04:04 AM UTC 2024 200
Sun Sep  1 05:04:05 AM UTC 2024 200
Sun Sep  1 05:04:06 AM UTC 2024 200
Sun Sep  1 05:04:07 AM UTC 2024 200
Sun Sep  1 05:04:08 AM UTC 2024 200
Sun Sep  1 05:04:09 AM UTC 2024 200
Sun Sep  1 05:04:10 AM UTC 2024 200
^C
```
### タスク停止
```bash:コマンド
aws ecs stop-task \
    --cluster ${CLUSTER_NAME} \
    --task ${TASK1_ID} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs stop-task \
>     --cluster ${CLUSTER_NAME} \
>     --task ${TASK1_ID} \
>     --no-cli-pager
{
    "task": {
        "attachments": [
            {
                "id": "08b1ce55-2d34-4baa-91fe-80214bcd5c10",
                "type": "ElasticNetworkInterface",
                "status": "ATTACHED",
                "details": [
                    {
                        "name": "subnetId",
                        "value": "subnet-00212e581b04af6ee"
                    },
                    {
                        "name": "networkInterfaceId",
                        "value": "eni-09bfdad6866cb6295"
                    },
                    {
                        "name": "macAddress",
                        "value": "06:43:c7:bc:69:b7"
                    },
                    {
                        "name": "privateIPv4Address",
                        "value": "10.0.13.115"
                    }
                ]
            }
        ],
        "attributes": [
            {
                "name": "ecs.cpu-architecture",
                "value": "x86_64"
            }
        ],
        "availabilityZone": "ap-northeast-1a",
        "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
        "connectivity": "CONNECTED",
        "connectivityAt": "2024-09-01T04:12:43.823000+00:00",
        "containers": [
            {
                "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c/4797e8e3-6b3a-402a-ae40-b3b9a0c1e980",
                "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
                "name": "apache-helloworld",
                "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld@sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                "runtimeId": "37dd830477fc4f5b8e11bbdfac88ae8c-860549998",
                "lastStatus": "RUNNING",
                "networkBindings": [],
                "networkInterfaces": [
                    {
                        "attachmentId": "08b1ce55-2d34-4baa-91fe-80214bcd5c10",
                        "privateIpv4Address": "10.0.13.115"
                    }
                ],
                "cpu": "0"
            }
        ],
        "cpu": "1024",
        "createdAt": "2024-09-01T04:12:39.953000+00:00",
        "desiredStatus": "STOPPED",
        "enableExecuteCommand": false,
        "group": "service:h4b-ecs-service",
        "lastStatus": "DEACTIVATING",
        "launchType": "FARGATE",
        "memory": "3072",
        "overrides": {
            "containerOverrides": [
                {
                    "name": "apache-helloworld"
                }
            ],
            "inferenceAcceleratorOverrides": []
        },
        "platformVersion": "1.4.0",
        "platformFamily": "Linux",
        "pullStartedAt": "2024-09-01T04:12:50.738000+00:00",
        "pullStoppedAt": "2024-09-01T04:12:59.740000+00:00",
        "startedAt": "2024-09-01T04:13:11.382000+00:00",
        "startedBy": "ecs-svc/2975423510966026190",
        "stopCode": "UserInitiated",
        "stoppedReason": "Task stopped by user",
        "stoppingAt": "2024-09-01T05:01:55.964000+00:00",
        "tags": [],
        "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
        "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "version": 5,
        "ephemeralStorage": {
            "sizeInGiB": 20
        },
        "fargateEphemeralStorage": {
            "sizeInGiB": 20
        }
    }
}
```
### サービスイベント確認
```bash:コマンド
aws ecs describe-services \
    --cluster ${CLUSTER_NAME} \
    --services ${SERVICE_NAME} \
    --query 'services[0].events[*].[id, createdAt, message]' \
    --output table

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-services \
>     --cluster ${CLUSTER_NAME} \
>     --services ${SERVICE_NAME} \
>     --query 'services[0].events[*].[id, createdAt, message]' \
>     --output table
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                                                      DescribeServices                                                                                                                      |
+--------------------------------------+-----------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  80c028aa-5078-4ebe-88af-e5ba135d7db8|  2024-09-01T05:02:58.648000+00:00 |  (service h4b-ecs-service) has reached a steady state.                                                                                                                          |
|  8e9176e5-575e-48b0-ba0a-40fc14c2514b|  2024-09-01T05:02:39.799000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  d77b77f4-2699-4deb-a612-e56176cb63f9|  2024-09-01T05:02:11.809000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task ff8e2c9646954b76ac57c5d04f6a6c7b).                                                                                        |
|  05097688-0581-4af3-ad2a-85ec1c0e24f1|  2024-09-01T05:02:10.659000+00:00 |  (service h4b-ecs-service, taskSet ecs-svc/2975423510966026190) has begun draining connections on 1 tasks.                                                                      |
|  b32998eb-cc08-4d18-b0d0-8ba77c37515b|  2024-09-01T05:02:10.653000+00:00 |  (service h4b-ecs-service) deregistered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)   |
|  b1d2cf97-622c-4dc1-9bf7-30b2be8ebcec|  2024-09-01T04:13:26.555000+00:00 |  (service h4b-ecs-service) has reached a steady state.                                                                                                                          |
|  68fc1a52-add2-4bd9-bec7-1b94f352d9bc|  2024-09-01T04:13:26.554000+00:00 |  (service h4b-ecs-service) (deployment ecs-svc/2975423510966026190) deployment completed.                                                                                       |
|  5f6758fd-977b-4811-b9c6-8033c98e85bf|  2024-09-01T04:13:07.843000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  712ea0fb-172a-41e5-aff3-3aa2c148bc31|  2024-09-01T04:12:40.035000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 37dd830477fc4f5b8e11bbdfac88ae8c).                                                                                        |
|  e18f719e-c9b0-40ae-a618-49f6b3b0c277|  2024-09-01T04:12:20.525000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  c9a01a56-f61c-4a48-8b0b-871a6400cad4|  2024-09-01T04:11:41.475000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c).                                                                                        |
+--------------------------------------+-----------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
```
### アクセス確認
```bash:コマンド
# タスク1のアクセス確認
curl ${TASK1_PUBLIC_IP}

# タスク2のアクセス確認
curl ${TASK2_PUBLIC_IP}
```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のアクセス確認
[cloudshell-user@ip-10-132-94-73 ~]$ curl ${TASK1_PUBLIC_IP}
^C
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク1のアクセス確認
[cloudshell-user@ip-10-132-94-73 ~]$ curl ${TASK2_PUBLIC_IP}
Hello World!
```
### サービス状態
```bash:コマンド
aws ecs describe-services \
    --cluster ${CLUSTER_NAME} \
    --services ${SERVICE_NAME} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-services \
>     --cluster ${CLUSTER_NAME} \
>     --services ${SERVICE_NAME} \
>     --no-cli-pager
{
    "services": [
        {
            "serviceArn": "arn:aws:ecs:ap-northeast-1:999999999999:service/h4b-ecs-cluster/h4b-ecs-service",
            "serviceName": "h4b-ecs-service",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "loadBalancers": [
                {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                    "containerName": "apache-helloworld",
                    "containerPort": 80
                }
            ],
            "serviceRegistries": [],
            "status": "ACTIVE",
            "desiredCount": 2,
            "runningCount": 2,
            "pendingCount": 0,
            "launchType": "FARGATE",
            "platformVersion": "LATEST",
            "platformFamily": "Linux",
            "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "deploymentConfiguration": {
                "deploymentCircuitBreaker": {
                    "enable": false,
                    "rollback": false
                },
                "maximumPercent": 200,
                "minimumHealthyPercent": 100
            },
            "deployments": [
                {
                    "id": "ecs-svc/2975423510966026190",
                    "status": "PRIMARY",
                    "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
                    "desiredCount": 2,
                    "pendingCount": 0,
                    "runningCount": 2,
                    "failedTasks": 0,
                    "createdAt": "2024-09-01T04:11:29.087000+00:00",
                    "updatedAt": "2024-09-01T05:02:58.642000+00:00",
                    "launchType": "FARGATE",
                    "platformVersion": "1.4.0",
                    "platformFamily": "Linux",
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-00212e581b04af6ee",
                                "subnet-0d47fd735f5035e47"
                            ],
                            "securityGroups": [
                                "sg-0439ac82bbca00d99"
                            ],
                            "assignPublicIp": "ENABLED"
                        }
                    },
                    "rolloutState": "COMPLETED",
                    "rolloutStateReason": "ECS deployment ecs-svc/2975423510966026190 completed."
                }
            ],
            "roleArn": "arn:aws:iam::999999999999:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
            "events": [
                {
                    "id": "80c028aa-5078-4ebe-88af-e5ba135d7db8",
                    "createdAt": "2024-09-01T05:02:58.648000+00:00",
                    "message": "(service h4b-ecs-service) has reached a steady state."
                },
                {
                    "id": "8e9176e5-575e-48b0-ba0a-40fc14c2514b",
                    "createdAt": "2024-09-01T05:02:39.799000+00:00",
                    "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
                },
                {
                    "id": "d77b77f4-2699-4deb-a612-e56176cb63f9",
                    "createdAt": "2024-09-01T05:02:11.809000+00:00",
                    "message": "(service h4b-ecs-service) has started 1 tasks: (task ff8e2c9646954b76ac57c5d04f6a6c7b)."
                },
                {
                    "id": "05097688-0581-4af3-ad2a-85ec1c0e24f1",
                    "createdAt": "2024-09-01T05:02:10.659000+00:00",
                    "message": "(service h4b-ecs-service, taskSet ecs-svc/2975423510966026190) has begun draining connections on 1 tasks."
                },
                {
                    "id": "b32998eb-cc08-4d18-b0d0-8ba77c37515b",
                    "createdAt": "2024-09-01T05:02:10.653000+00:00",
                    "message": "(service h4b-ecs-service) deregistered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
                },
                {
                    "id": "b1d2cf97-622c-4dc1-9bf7-30b2be8ebcec",
                    "createdAt": "2024-09-01T04:13:26.555000+00:00",
                    "message": "(service h4b-ecs-service) has reached a steady state."
                },
                {
                    "id": "68fc1a52-add2-4bd9-bec7-1b94f352d9bc",
                    "createdAt": "2024-09-01T04:13:26.554000+00:00",
                    "message": "(service h4b-ecs-service) (deployment ecs-svc/2975423510966026190) deployment completed."
                },
                {
                    "id": "5f6758fd-977b-4811-b9c6-8033c98e85bf",
                    "createdAt": "2024-09-01T04:13:07.843000+00:00",
                    "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
                },
                {
                    "id": "712ea0fb-172a-41e5-aff3-3aa2c148bc31",
                    "createdAt": "2024-09-01T04:12:40.035000+00:00",
                    "message": "(service h4b-ecs-service) has started 1 tasks: (task 37dd830477fc4f5b8e11bbdfac88ae8c)."
                },
                {
                    "id": "e18f719e-c9b0-40ae-a618-49f6b3b0c277",
                    "createdAt": "2024-09-01T04:12:20.525000+00:00",
                    "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
                },
                {
                    "id": "c9a01a56-f61c-4a48-8b0b-871a6400cad4",
                    "createdAt": "2024-09-01T04:11:41.475000+00:00",
                    "message": "(service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c)."
                }
            ],
            "createdAt": "2024-09-01T04:11:29.087000+00:00",
            "placementConstraints": [],
            "placementStrategy": [],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-00212e581b04af6ee",
                        "subnet-0d47fd735f5035e47"
                    ],
                    "securityGroups": [
                        "sg-0439ac82bbca00d99"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            },
            "healthCheckGracePeriodSeconds": 0,
            "schedulingStrategy": "REPLICA",
            "deploymentController": {
                "type": "ECS"
            },
            "createdBy": "arn:aws:iam::999999999999:user/admin",
            "enableECSManagedTags": false,
            "propagateTags": "NONE",
            "enableExecuteCommand": false
        }
    ],
    "failures": []
}
```
### タスク状態確認
```bash:コマンド
# タスク状態確認
aws ecs describe-tasks \
    --cluster ${CLUSTER_NAME} \
    --tasks ${TASK_LISTS} \
    --no-cli-pager

aws ecs describe-tasks \
    --cluster ${CLUSTER_NAME} \
    --tasks ${TASK_LISTS} \
    --query 'tasks[*].[taskArn, lastStatus]' \
    --output text

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク状態確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --tasks ${TASK_LISTS} \
>     --no-cli-pager
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "08b1ce55-2d34-4baa-91fe-80214bcd5c10",
                    "type": "ElasticNetworkInterface",
                    "status": "DELETED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-00212e581b04af6ee"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-09bfdad6866cb6295"
                        },
                        {
                            "name": "macAddress",
                            "value": "06:43:c7:bc:69:b7"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.13.115"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "ap-northeast-1a",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2024-09-01T04:12:43.823000+00:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c/4797e8e3-6b3a-402a-ae40-b3b9a0c1e980",
                    "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld@sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "runtimeId": "37dd830477fc4f5b8e11bbdfac88ae8c-860549998",
                    "lastStatus": "STOPPED",
                    "exitCode": 137,
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "08b1ce55-2d34-4baa-91fe-80214bcd5c10",
                            "privateIpv4Address": "10.0.13.115"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2024-09-01T04:12:39.953000+00:00",
            "desiredStatus": "STOPPED",
            "enableExecuteCommand": false,
            "executionStoppedAt": "2024-09-01T05:08:22.357000+00:00",
            "group": "service:h4b-ecs-service",
            "healthStatus": "UNKNOWN",
            "lastStatus": "STOPPED",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "apache-helloworld"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2024-09-01T04:12:50.738000+00:00",
            "pullStoppedAt": "2024-09-01T04:12:59.740000+00:00",
            "startedAt": "2024-09-01T04:13:11.382000+00:00",
            "startedBy": "ecs-svc/2975423510966026190",
            "stopCode": "UserInitiated",
            "stoppedAt": "2024-09-01T05:08:46.306000+00:00",
            "stoppedReason": "Task stopped by user",
            "stoppingAt": "2024-09-01T05:01:55.964000+00:00",
            "tags": [],
            "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c",
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "version": 8,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        },
        {
            "attachments": [
                {
                    "id": "3c68c53e-a087-41a4-99a7-7e290d06646a",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-0d47fd735f5035e47"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-0e2aec3c63efa1abf"
                        },
                        {
                            "name": "macAddress",
                            "value": "0a:b1:89:d3:4a:f5"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.16.55"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "ap-northeast-1c",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2024-09-01T04:11:45.072000+00:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c/79371dae-14ff-4567-9449-d093df27a8cf",
                    "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                    "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "runtimeId": "96f27181cb8e480793a548b98447e44c-860549998",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "3c68c53e-a087-41a4-99a7-7e290d06646a",
                            "privateIpv4Address": "10.0.16.55"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2024-09-01T04:11:41.378000+00:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:h4b-ecs-service",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "apache-helloworld"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2024-09-01T04:12:00.423000+00:00",
            "pullStoppedAt": "2024-09-01T04:12:06.322000+00:00",
            "startedAt": "2024-09-01T04:12:28.976000+00:00",
            "startedBy": "ecs-svc/2975423510966026190",
            "tags": [],
            "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "version": 5,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        }
    ],
    "failures": []
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --tasks ${TASK_LISTS} \
>     --query 'tasks[*].[taskArn, lastStatus]' \
>     --output text
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/37dd830477fc4f5b8e11bbdfac88ae8c   STOPPED
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c   RUNNING
```
### タスクリスト更新
```bash:コマンド
# タスクリストの確認
aws ecs list-tasks \
    --cluster ${CLUSTER_NAME} \
    --service-name ${SERVICE_NAME}

# タスクリストの取得
TASK_LISTS_AFTER=$(
    aws ecs list-tasks \
    --cluster ${CLUSTER_NAME} \
    --service-name ${SERVICE_NAME} \
    --query taskArns \
    --output text
) \
&& echo ${TASK_LISTS_AFTER}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスクリストの確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs list-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --service-name ${SERVICE_NAME}
{
    "taskArns": [
        "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
        "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/ff8e2c9646954b76ac57c5d04f6a6c7b"
    ]
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # タスクリストの取得
[cloudshell-user@ip-10-132-94-73 ~]$ TASK_LISTS_AFTER=$(
>     aws ecs list-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --service-name ${SERVICE_NAME} \
>     --query taskArns \
>     --output text
> ) \
> && echo ${TASK_LISTS_AFTER}
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/ff8e2c9646954b76ac57c5d04f6a6c7b
```
### タスク状態確認
```bash:コマンド
# タスク状態確認
aws ecs describe-tasks \
    --cluster ${CLUSTER_NAME} \
    --tasks ${TASK_LISTS_AFTER} \
    --no-cli-pager

aws ecs describe-tasks \
    --cluster ${CLUSTER_NAME} \
    --tasks ${TASK_LISTS_AFTER} \
    --query 'tasks[*].[taskArn, lastStatus]' \
    --output text

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク状態確認
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --tasks ${TASK_LISTS_AFTER} \
>     --no-cli-pager
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "3c68c53e-a087-41a4-99a7-7e290d06646a",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-0d47fd735f5035e47"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-0e2aec3c63efa1abf"
                        },
                        {
                            "name": "macAddress",
                            "value": "0a:b1:89:d3:4a:f5"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.16.55"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "ap-northeast-1c",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2024-09-01T04:11:45.072000+00:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c/79371dae-14ff-4567-9449-d093df27a8cf",
                    "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                    "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "runtimeId": "96f27181cb8e480793a548b98447e44c-860549998",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "3c68c53e-a087-41a4-99a7-7e290d06646a",
                            "privateIpv4Address": "10.0.16.55"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2024-09-01T04:11:41.378000+00:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:h4b-ecs-service",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "apache-helloworld"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2024-09-01T04:12:00.423000+00:00",
            "pullStoppedAt": "2024-09-01T04:12:06.322000+00:00",
            "startedAt": "2024-09-01T04:12:28.976000+00:00",
            "startedBy": "ecs-svc/2975423510966026190",
            "tags": [],
            "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c",
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "version": 5,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        },
        {
            "attachments": [
                {
                    "id": "0f394aa5-7e67-4443-902c-0e18c4f1bf71",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-00212e581b04af6ee"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-065df50311438e44c"
                        },
                        {
                            "name": "macAddress",
                            "value": "06:72:db:58:24:4f"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.2.231"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "ap-northeast-1a",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2024-09-01T05:02:16.114000+00:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:ap-northeast-1:999999999999:container/h4b-ecs-cluster/ff8e2c9646954b76ac57c5d04f6a6c7b/9da3e2b5-ab18-4664-8dc1-9815f699fbe4",
                    "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/ff8e2c9646954b76ac57c5d04f6a6c7b",
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld@sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "imageDigest": "sha256:0cdafbfa1b5674149472ef708caec511a42e929e83c2ae980908311a92f02cb7",
                    "runtimeId": "ff8e2c9646954b76ac57c5d04f6a6c7b-860549998",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "0f394aa5-7e67-4443-902c-0e18c4f1bf71",
                            "privateIpv4Address": "10.0.2.231"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2024-09-01T05:02:11.703000+00:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:h4b-ecs-service",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "apache-helloworld"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2024-09-01T05:02:25.144000+00:00",
            "pullStoppedAt": "2024-09-01T05:02:32.607000+00:00",
            "startedAt": "2024-09-01T05:02:42.275000+00:00",
            "startedBy": "ecs-svc/2975423510966026190",
            "tags": [],
            "taskArn": "arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/ff8e2c9646954b76ac57c5d04f6a6c7b",
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "version": 4,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        }
    ],
    "failures": []
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-tasks \
>     --cluster ${CLUSTER_NAME} \
>     --tasks ${TASK_LISTS_AFTER} \
>     --query 'tasks[*].[taskArn, lastStatus]' \
>     --output text
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/96f27181cb8e480793a548b98447e44c   RUNNING
arn:aws:ecs:ap-northeast-1:999999999999:task/h4b-ecs-cluster/ff8e2c9646954b76ac57c5d04f6a6c7b   RUNNING
```
## タスク数追加
### タスク数追加
```bash:コマンド
# タスク数追加
aws ecs update-service \
    --cluster ${CLUSTER_NAME} \
    --service ${SERVICE_NAME} \
    --desired-count 3 \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク数追加
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs update-service \
>     --cluster ${CLUSTER_NAME} \
>     --service ${SERVICE_NAME} \
>     --desired-count 3
{
    "service": {
        "serviceArn": "arn:aws:ecs:ap-northeast-1:999999999999:service/h4b-ecs-cluster/h4b-ecs-service",
        "serviceName": "h4b-ecs-service",
        "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
        "loadBalancers": [
            {
                "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                "containerName": "apache-helloworld",
                "containerPort": 80
            }
        ],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 3,
        "runningCount": 2,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": false,
                "rollback": false
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "deployments": [
            {
                "id": "ecs-svc/2975423510966026190",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
                "desiredCount": 2,
                "pendingCount": 0,
                "runningCount": 2,
                "failedTasks": 0,
                "createdAt": "2024-09-01T04:11:29.087000+00:00",
                "updatedAt": "2024-09-01T05:02:58.642000+00:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-00212e581b04af6ee",
                            "subnet-0d47fd735f5035e47"
                        ],
                        "securityGroups": [
                            "sg-0439ac82bbca00d99"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/2975423510966026190 completed."
            }
        ],
        "roleArn": "arn:aws:iam::999999999999:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [
            {
                "id": "80c028aa-5078-4ebe-88af-e5ba135d7db8",
                "createdAt": "2024-09-01T05:02:58.648000+00:00",
                "message": "(service h4b-ecs-service) has reached a steady state."
            },
            {
                "id": "8e9176e5-575e-48b0-ba0a-40fc14c2514b",
                "createdAt": "2024-09-01T05:02:39.799000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "d77b77f4-2699-4deb-a612-e56176cb63f9",
                "createdAt": "2024-09-01T05:02:11.809000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task ff8e2c9646954b76ac57c5d04f6a6c7b)."
            },
            {
                "id": "05097688-0581-4af3-ad2a-85ec1c0e24f1",
                "createdAt": "2024-09-01T05:02:10.659000+00:00",
                "message": "(service h4b-ecs-service, taskSet ecs-svc/2975423510966026190) has begun draining connections on 1 tasks."
            },
            {
                "id": "b32998eb-cc08-4d18-b0d0-8ba77c37515b",
                "createdAt": "2024-09-01T05:02:10.653000+00:00",
                "message": "(service h4b-ecs-service) deregistered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "b1d2cf97-622c-4dc1-9bf7-30b2be8ebcec",
                "createdAt": "2024-09-01T04:13:26.555000+00:00",
                "message": "(service h4b-ecs-service) has reached a steady state."
            },
            {
                "id": "68fc1a52-add2-4bd9-bec7-1b94f352d9bc",
                "createdAt": "2024-09-01T04:13:26.554000+00:00",
                "message": "(service h4b-ecs-service) (deployment ecs-svc/2975423510966026190) deployment completed."
            },
            {
                "id": "5f6758fd-977b-4811-b9c6-8033c98e85bf",
                "createdAt": "2024-09-01T04:13:07.843000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "712ea0fb-172a-41e5-aff3-3aa2c148bc31",
                "createdAt": "2024-09-01T04:12:40.035000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task 37dd830477fc4f5b8e11bbdfac88ae8c)."
            },
            {
                "id": "e18f719e-c9b0-40ae-a618-49f6b3b0c277",
                "createdAt": "2024-09-01T04:12:20.525000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "c9a01a56-f61c-4a48-8b0b-871a6400cad4",
                "createdAt": "2024-09-01T04:11:41.475000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c)."
            }
        ],
        "createdAt": "2024-09-01T04:11:29.087000+00:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-00212e581b04af6ee",
                    "subnet-0d47fd735f5035e47"
                ],
                "securityGroups": [
                    "sg-0439ac82bbca00d99"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::999999999999:user/admin",
        "enableECSManagedTags": false,
        "propagateTags": "NONE",
        "enableExecuteCommand": false
    }
}
```
### イベント確認
```bash:コマンド
aws ecs describe-services \
    --cluster ${CLUSTER_NAME} \
    --services ${SERVICE_NAME} \
    --query 'services[0].events[*].[id, createdAt, message]' \
    --output table

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs describe-services \
>     --cluster ${CLUSTER_NAME} \
>     --services ${SERVICE_NAME} \
>     --query 'services[0].events[*].[id, createdAt, message]' \
>     --output table
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                                                      DescribeServices                                                                                                                      |
+--------------------------------------+-----------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  b1879450-2af9-4738-95ca-bfcae692a72e|  2024-09-01T05:41:06.768000+00:00 |  (service h4b-ecs-service) has reached a steady state.                                                                                                                          |
|  0230765e-2fd0-4b6d-a98f-e9d6b73a29a2|  2024-09-01T05:40:48.426000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  c7143c6c-01db-4292-a013-4d6b9a6d0707|  2024-09-01T05:40:19.569000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 9c9ed82835fc4982b127b4cd8d0d217d).                                                                                        |
|  80c028aa-5078-4ebe-88af-e5ba135d7db8|  2024-09-01T05:02:58.648000+00:00 |  (service h4b-ecs-service) has reached a steady state.                                                                                                                          |
|  8e9176e5-575e-48b0-ba0a-40fc14c2514b|  2024-09-01T05:02:39.799000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  d77b77f4-2699-4deb-a612-e56176cb63f9|  2024-09-01T05:02:11.809000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task ff8e2c9646954b76ac57c5d04f6a6c7b).                                                                                        |
|  05097688-0581-4af3-ad2a-85ec1c0e24f1|  2024-09-01T05:02:10.659000+00:00 |  (service h4b-ecs-service, taskSet ecs-svc/2975423510966026190) has begun draining connections on 1 tasks.                                                                      |
|  b32998eb-cc08-4d18-b0d0-8ba77c37515b|  2024-09-01T05:02:10.653000+00:00 |  (service h4b-ecs-service) deregistered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)   |
|  b1d2cf97-622c-4dc1-9bf7-30b2be8ebcec|  2024-09-01T04:13:26.555000+00:00 |  (service h4b-ecs-service) has reached a steady state.                                                                                                                          |
|  68fc1a52-add2-4bd9-bec7-1b94f352d9bc|  2024-09-01T04:13:26.554000+00:00 |  (service h4b-ecs-service) (deployment ecs-svc/2975423510966026190) deployment completed.                                                                                       |
|  5f6758fd-977b-4811-b9c6-8033c98e85bf|  2024-09-01T04:13:07.843000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  712ea0fb-172a-41e5-aff3-3aa2c148bc31|  2024-09-01T04:12:40.035000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 37dd830477fc4f5b8e11bbdfac88ae8c).                                                                                        |
|  e18f719e-c9b0-40ae-a618-49f6b3b0c277|  2024-09-01T04:12:20.525000+00:00 |  (service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)     |
|  c9a01a56-f61c-4a48-8b0b-871a6400cad4|  2024-09-01T04:11:41.475000+00:00 |  (service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c).                                                                                        |
```
# 10 リソースの削除 + まとめ + Next Action 案
## ALB削除
```bash:コマンド
# ALB削除
aws elbv2 delete-load-balancer --load-balancer-arn ${LB_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ALB削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws elbv2 delete-load-balancer --load-balancer-arn ${LB_ARN}
```
## ターゲットグループ削除
```bash:コマンド
# ターゲットグループ削除
aws elbv2 delete-target-group --target-group-arn ${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ターゲットグループ削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws elbv2 delete-target-group --target-group-arn ${TARGET_GROUP_ARN}
```
## ECS削除
### クラスター削除
```bash:コマンド
# サービス削除
aws ecs delete-service \
    --cluster ${CLUSTER_NAME} \
    --service ${SERVICE_NAME} \
    --force \
    --no-cli-pager

# クラスター削除
aws ecs delete-cluster \
    --cluster ${CLUSTER_NAME} \
    --no-cli-pager
```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # サービス削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs delete-service \
>     --cluster ${CLUSTER_NAME} \
>     --service ${SERVICE_NAME} \
>     --force \
>     --no-cli-pager
{
    "service": {
        "serviceArn": "arn:aws:ecs:ap-northeast-1:999999999999:service/h4b-ecs-cluster/h4b-ecs-service",
        "serviceName": "h4b-ecs-service",
        "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
        "loadBalancers": [
            {
                "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c",
                "containerName": "apache-helloworld",
                "containerPort": 80
            }
        ],
        "serviceRegistries": [],
        "status": "DRAINING",
        "desiredCount": 0,
        "runningCount": 2,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": false,
                "rollback": false
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "deployments": [
            {
                "id": "ecs-svc/2975423510966026190",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
                "desiredCount": 0,
                "pendingCount": 0,
                "runningCount": 2,
                "failedTasks": 0,
                "createdAt": "2024-09-01T04:11:29.087000+00:00",
                "updatedAt": "2024-09-01T05:51:05.464000+00:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-00212e581b04af6ee",
                            "subnet-0d47fd735f5035e47"
                        ],
                        "securityGroups": [
                            "sg-0439ac82bbca00d99"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/2975423510966026190 completed."
            }
        ],
        "roleArn": "arn:aws:iam::999999999999:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [
            {
                "id": "329e6443-c81d-41c9-a058-0e7935fc5433",
                "createdAt": "2024-09-01T05:51:14.783000+00:00",
                "message": "(service h4b-ecs-service, taskSet ecs-svc/2975423510966026190) has begun draining connections on 1 tasks."
            },
            {
                "id": "b841fb7f-838e-4f88-80dc-bbed50f83999",
                "createdAt": "2024-09-01T05:51:14.778000+00:00",
                "message": "(service h4b-ecs-service) failed to deregister targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c) with (error Target groups 'arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c' not found)"
            },
            {
                "id": "7f0d116d-2ef6-495b-bfb6-1ce7d315e237",
                "createdAt": "2024-09-01T05:51:05.533000+00:00",
                "message": "(service h4b-ecs-service) has stopped 1 running tasks: (task 96f27181cb8e480793a548b98447e44c)."
            },
            {
                "id": "b1879450-2af9-4738-95ca-bfcae692a72e",
                "createdAt": "2024-09-01T05:41:06.768000+00:00",
                "message": "(service h4b-ecs-service) has reached a steady state."
            },
            {
                "id": "0230765e-2fd0-4b6d-a98f-e9d6b73a29a2",
                "createdAt": "2024-09-01T05:40:48.426000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "c7143c6c-01db-4292-a013-4d6b9a6d0707",
                "createdAt": "2024-09-01T05:40:19.569000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task 9c9ed82835fc4982b127b4cd8d0d217d)."
            },
            {
                "id": "80c028aa-5078-4ebe-88af-e5ba135d7db8",
                "createdAt": "2024-09-01T05:02:58.648000+00:00",
                "message": "(service h4b-ecs-service) has reached a steady state."
            },
            {
                "id": "8e9176e5-575e-48b0-ba0a-40fc14c2514b",
                "createdAt": "2024-09-01T05:02:39.799000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "d77b77f4-2699-4deb-a612-e56176cb63f9",
                "createdAt": "2024-09-01T05:02:11.809000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task ff8e2c9646954b76ac57c5d04f6a6c7b)."
            },
            {
                "id": "05097688-0581-4af3-ad2a-85ec1c0e24f1",
                "createdAt": "2024-09-01T05:02:10.659000+00:00",
                "message": "(service h4b-ecs-service, taskSet ecs-svc/2975423510966026190) has begun draining connections on 1 tasks."
            },
            {
                "id": "b32998eb-cc08-4d18-b0d0-8ba77c37515b",
                "createdAt": "2024-09-01T05:02:10.653000+00:00",
                "message": "(service h4b-ecs-service) deregistered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "b1d2cf97-622c-4dc1-9bf7-30b2be8ebcec",
                "createdAt": "2024-09-01T04:13:26.555000+00:00",
                "message": "(service h4b-ecs-service) has reached a steady state."
            },
            {
                "id": "68fc1a52-add2-4bd9-bec7-1b94f352d9bc",
                "createdAt": "2024-09-01T04:13:26.554000+00:00",
                "message": "(service h4b-ecs-service) (deployment ecs-svc/2975423510966026190) deployment completed."
            },
            {
                "id": "5f6758fd-977b-4811-b9c6-8033c98e85bf",
                "createdAt": "2024-09-01T04:13:07.843000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "712ea0fb-172a-41e5-aff3-3aa2c148bc31",
                "createdAt": "2024-09-01T04:12:40.035000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task 37dd830477fc4f5b8e11bbdfac88ae8c)."
            },
            {
                "id": "e18f719e-c9b0-40ae-a618-49f6b3b0c277",
                "createdAt": "2024-09-01T04:12:20.525000+00:00",
                "message": "(service h4b-ecs-service) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/h4b-ecs-targetgroup/e9af50f66620267c)"
            },
            {
                "id": "c9a01a56-f61c-4a48-8b0b-871a6400cad4",
                "createdAt": "2024-09-01T04:11:41.475000+00:00",
                "message": "(service h4b-ecs-service) has started 1 tasks: (task 96f27181cb8e480793a548b98447e44c)."
            }
        ],
        "createdAt": "2024-09-01T04:11:29.087000+00:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-00212e581b04af6ee",
                    "subnet-0d47fd735f5035e47"
                ],
                "securityGroups": [
                    "sg-0439ac82bbca00d99"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::999999999999:user/admin",
        "enableECSManagedTags": false,
        "propagateTags": "NONE",
        "enableExecuteCommand": false
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # クラスター削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs delete-cluster \
>     --cluster ${CLUSTER_NAME} \
>     --no-cli-pager
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:ap-northeast-1:999999999999:cluster/h4b-ecs-cluster",
        "clusterName": "h4b-ecs-cluster",
        "status": "INACTIVE",
        "registeredContainerInstancesCount": 0,
        "runningTasksCount": 0,
        "pendingTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "disabled"
            }
        ],
        "capacityProviders": [],
        "defaultCapacityProviderStrategy": []
    }
}
[cloudshell-user@ip-10-132-94-73 ~]$ 
```
### タスク定義無効化
```bash:コマンド
# タスク定義無効化
aws ecs deregister-task-definition \
    --task-definition ${TASK_REGISTER_FAMILY}:${TASKDEFINITION_REVISION_NO} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # タスク定義無効化
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs deregister-task-definition \
>     --task-definition ${TASK_REGISTER_FAMILY}:${TASKDEFINITION_REVISION_NO} \
>     --no-cli-pager
{
    "taskDefinition": {
        "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
        "containerDefinitions": [
            {
                "name": "apache-helloworld",
                "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                "cpu": 0,
                "portMappings": [
                    {
                        "containerPort": 80,
                        "hostPort": 80,
                        "protocol": "tcp",
                        "name": "apache-helloworld-80-tcp",
                        "appProtocol": "http"
                    }
                ],
                "essential": true,
                "environment": [],
                "environmentFiles": [],
                "mountPoints": [],
                "volumesFrom": [],
                "ulimits": [],
                "logConfiguration": {
                    "logDriver": "awslogs",
                    "options": {
                        "awslogs-group": "/ecs/h4b-ecs-task-definition",
                        "mode": "non-blocking",
                        "max-buffer-size": "25m",
                        "awslogs-create-group": "true",
                        "awslogs-region": "ap-northeast-1",
                        "awslogs-stream-prefix": "ecs"
                    },
                    "secretOptions": []
                },
                "systemControls": []
            }
        ],
        "family": "h4b-ecs-task-definition",
        "executionRoleArn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole",
        "networkMode": "awsvpc",
        "revision": 11,
        "volumes": [],
        "status": "INACTIVE",
        "requiresAttributes": [
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
            },
            {
                "name": "ecs.capability.execution-role-awslogs"
            },
            {
                "name": "com.amazonaws.ecs.capability.ecr-auth"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28"
            },
            {
                "name": "ecs.capability.execution-role-ecr-pull"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
            },
            {
                "name": "ecs.capability.task-eni"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
            }
        ],
        "placementConstraints": [],
        "compatibilities": [
            "EC2",
            "FARGATE"
        ],
        "runtimePlatform": {
            "cpuArchitecture": "X86_64",
            "operatingSystemFamily": "LINUX"
        },
        "requiresCompatibilities": [
            "FARGATE"
        ],
        "cpu": "1024",
        "memory": "3072",
        "registeredAt": "2024-09-01T04:08:23.830000+00:00",
        "deregisteredAt": "2024-09-01T06:04:03.462000+00:00",
        "registeredBy": "arn:aws:iam::999999999999:user/admin"
    }
}
```
### 非アクティブなタスク定義を取得
```bash:コマンド
# 非アクティブなタスク定義を取得
aws ecs list-task-definitions \
    --family-prefix ${TASK_REGISTER_FAMILY}  \
    --status INACTIVE \
    --output text

for revision in $(
    aws ecs list-task-definitions \
        --family-prefix ${TASK_REGISTER_FAMILY} \
        --status INACTIVE \
        --query "taskDefinitionArns[]" \
        --output text
);
do
  aws ecs delete-task-definitions \
    --task-definition $revision \
    --no-cli-pager
done

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # 非アクティブなタスク定義を取得
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecs list-task-definitions \
>     --family-prefix ${TASK_REGISTER_FAMILY}  \
>     --status INACTIVE \
>     --output text
TASKDEFINITIONARNS      arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ for revision in $(
>     aws ecs list-task-definitions \
>         --family-prefix ${TASK_REGISTER_FAMILY} \
>         --status INACTIVE \
>         --query "taskDefinitionArns[]" \
>         --output text
> );
> do
>   aws ecs delete-task-definitions \
>     --task-definition $revision \
>     --no-cli-pager
> done
{
    "taskDefinitions": [
        {
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:999999999999:task-definition/h4b-ecs-task-definition:11",
            "containerDefinitions": [
                {
                    "name": "apache-helloworld",
                    "image": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld:0.0.1",
                    "cpu": 0,
                    "portMappings": [
                        {
                            "containerPort": 80,
                            "hostPort": 80,
                            "protocol": "tcp",
                            "name": "apache-helloworld-80-tcp",
                            "appProtocol": "http"
                        }
                    ],
                    "essential": true,
                    "environment": [],
                    "environmentFiles": [],
                    "mountPoints": [],
                    "volumesFrom": [],
                    "ulimits": [],
                    "logConfiguration": {
                        "logDriver": "awslogs",
                        "options": {
                            "awslogs-group": "/ecs/h4b-ecs-task-definition",
                            "mode": "non-blocking",
                            "awslogs-create-group": "true",
                            "max-buffer-size": "25m",
                            "awslogs-region": "ap-northeast-1",
                            "awslogs-stream-prefix": "ecs"
                        },
                        "secretOptions": []
                    },
                    "systemControls": []
                }
            ],
            "family": "h4b-ecs-task-definition",
            "executionRoleArn": "arn:aws:iam::999999999999:role/ecsTaskExecutionRole",
            "networkMode": "awsvpc",
            "revision": 11,
            "volumes": [],
            "status": "DELETE_IN_PROGRESS",
            "requiresAttributes": [
                {
                    "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
                },
                {
                    "name": "ecs.capability.execution-role-awslogs"
                },
                {
                    "name": "com.amazonaws.ecs.capability.ecr-auth"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28"
                },
                {
                    "name": "ecs.capability.execution-role-ecr-pull"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
                },
                {
                    "name": "ecs.capability.task-eni"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
                }
            ],
            "placementConstraints": [],
            "compatibilities": [
                "EC2",
                "FARGATE"
            ],
            "runtimePlatform": {
                "cpuArchitecture": "X86_64",
                "operatingSystemFamily": "LINUX"
            },
            "requiresCompatibilities": [
                "FARGATE"
            ],
            "cpu": "1024",
            "memory": "3072",
            "registeredAt": "2024-09-01T04:08:23.830000+00:00",
            "deregisteredAt": "2024-09-01T06:04:03.462000+00:00",
            "registeredBy": "arn:aws:iam::999999999999:user/admin"
        }
    ],
    "failures": []
}
```
## VPC削除
```bash:コマンド
# インターネットゲートウェイ デタッチ
aws ec2 detach-internet-gateway \
    --internet-gateway-id ${IGW_ID}\
    --vpc-id ${VPC_ID}

# インターネットゲートウェイ削除
aws ec2 delete-internet-gateway --internet-gateway-id ${IGW_ID}

# Subnet 削除
aws ec2 delete-subnet --subnet-id ${AZ1_PUB_ID}
aws ec2 delete-subnet --subnet-id ${AZ2_PUB_ID}

# ルートテーブル削除
aws ec2 delete-route-table --route-table-id ${PUB_RT_ID}

# VPC削除
aws ec2 delete-vpc --vpc-id ${VPC_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # インターネットゲートウェイ デタッチ
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 detach-internet-gateway \
>     --internet-gateway-id ${IGW_ID}\
>     --vpc-id ${VPC_ID}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # インターネットゲートウェイ削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 delete-internet-gateway --internet-gateway-id ${IGW_ID}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # Subnet 削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 delete-subnet --subnet-id ${AZ1_PUB_ID}
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 delete-subnet --subnet-id ${AZ2_PUB_ID}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # ルートテーブル削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 delete-route-table --route-table-id ${PUB_RT_ID}
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # VPC削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws ec2 delete-vpc --vpc-id ${VPC_ID}
```
## ECR削除
```bash:コマンド
aws ecr delete-repository \
    --repository-name ${REPOSITORY_NAME} \
    --force

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws ecr delete-repository \
>     --repository-name ${REPOSITORY_NAME} \
>     --force
{
    "repository": {
        "repositoryArn": "arn:aws:ecr:ap-northeast-1:999999999999:repository/h4b-ecs-helloworld",
        "registryId": "999999999999",
        "repositoryName": "h4b-ecs-helloworld",
        "repositoryUri": "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/h4b-ecs-helloworld",
        "createdAt": "2024-09-01T04:01:14.519000+00:00",
        "imageTagMutability": "MUTABLE"
    }
}
```
## IAMロールの削除
```bash:コマンド
# ロールにアタッチされているポリシーをリスト
POLICIES=$(
    aws iam list-attached-role-policies \
        --role-name ${ROLE_NAME} \
        --query 'AttachedPolicies[*].PolicyArn' \
        --output text
) \
&& echo ${POLICIES}

# リスト内のポリシーをデタッチする
for POLICY in ${POLICIES}; do
    aws iam detach-role-policy \
        --role-name ${ROLE_NAME} \
        --policy-arn ${POLICY}
done

# IAMロールの削除
aws iam delete-role \
    --role-name ${ROLE_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ # ロールにアタッチされているポリシーをリスト
[cloudshell-user@ip-10-132-94-73 ~]$ POLICIES=$(
>     aws iam list-attached-role-policies \
>         --role-name ${ROLE_NAME} \
>         --query 'AttachedPolicies[*].PolicyArn' \
>         --output text
> ) \
> && echo ${POLICIES}
arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # リスト内のポリシーをデタッチする
[cloudshell-user@ip-10-132-94-73 ~]$ for POLICY in ${POLICIES}; do
>     aws iam detach-role-policy \
>         --role-name ${ROLE_NAME} \
>         --policy-arn ${POLICY}
> done
[cloudshell-user@ip-10-132-94-73 ~]$ 
[cloudshell-user@ip-10-132-94-73 ~]$ # IAMロールの削除
[cloudshell-user@ip-10-132-94-73 ~]$ aws iam delete-role \
>     --role-name ${ROLE_NAME}
```
## Cloud9削除
```bash:コマンド
aws cloud9 delete-environment \
    --environment-id ${CLOUD9_ENVIRONMENT_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-94-73 ~]$ aws cloud9 delete-environment \
>     --environment-id ${CLOUD9_ENVIRONMENT_ID}
```