0
0

Amazon ECS・ECRのCLIメモ

Last updated at Posted at 2024-07-31

背景・目的

最近、ECSやコンテナに触れる機会があります。
ECSやECRをCLIで作ったのでで忘れないようにメモします。

コマンド間でリソースや、状態の整合性は取れていないのでご注意ください。

まとめ

随時、追加していきます。

下記に、目的別にコマンドをまとめます。

分類 目的 コマンド
ECR レジストリを確認する aws ecr describe-registry
ECRリポジトリを作成する aws ecr create-repository
ECRリポジトリを確認する aws ecr describe-repositories
イメージリストを確認する aws ecr list-images
ECSクラスタ ECSクラスタを作成する aws ecs create-cluster
ECSクラスタを確認する aws ecs describe-clusters
タスク定義 タスク定義を登録する aws ecs register-task-definition
タスク定義を確認する aws ecs describe-task-definition
サービス サービスを起動する aws ecs create-service
サービスを更新する aws ecs update-service
サービスを削除する aws ecs delete-service

実践

前提

下記の環境で実行しています。

  • MacOS
  • AWS CLI
  • 東京リージョン

ECSは、Fargateタイプで実装しています

以降のコマンド実行前に、環境変数にプロファイルを指定しています。

export AWS_PROFILE=プロファイル名

ECR

describe-registry / レジストリを確認する

$ aws ecr describe-registry

{
    "registryId": "XXXXX",
    "replicationConfiguration": {
        "rules": []
    }
}
$ 

create-repository / ECRリポジトリを作成する

  1. 下記のコマンドで作成します
    $ aws ecr create-repository --repository-name test
    {
        "repository": {
            "repositoryArn": "arn:aws:ecr:ap-northeast-1:XXXXX:repository/test",
            "registryId": "XXXXX",
            "repositoryName": "test",
            "repositoryUri": "XXXXX.dkr.ecr.ap-northeast-1.amazonaws.com/test",
            "createdAt": "2024-07-31T10:25:55.680000+09:00",
            "imageTagMutability": "MUTABLE",
            "imageScanningConfiguration": {
                "scanOnPush": false
            },
            "encryptionConfiguration": {
                "encryptionType": "AES256"
            }
        }
    }
    $
    
  2. できました
    image.png

describe-repositories / ECRリポジトリを確認する

  1. 下記のコマンドで確認します
    $ aws ecr describe-repositories --repository-names test
    {
        "repositories": [
            {
                "repositoryArn": "arn:aws:ecr:ap-northeast-1:XXXXX:repository/test",
                "registryId": "XXXXX",
                "repositoryName": "test",
                "repositoryUri": "XXXXX.dkr.ecr.ap-northeast-1.amazonaws.com/test",
                "createdAt": "2024-07-31T10:25:55.680000+09:00",
                "imageTagMutability": "MUTABLE",
                "imageScanningConfiguration": {
                    "scanOnPush": false
                },
                "encryptionConfiguration": {
                    "encryptionType": "AES256"
                }
            }
        ]
    }
    $
    

list-images / イメージリストを確認する

  1. 登録されているイメージを確認します
    $ aws ecr list-images --repository-name example-java-backend
    {
        "imageIds": [
            {
                "imageDigest": "sha256:XXXXXXXXXXX",
                "imageTag": "XXXXXX"
            }
        ]
    }
    $
    

ECSクラスタ

create-cluster / ECSクラスタを作成する

  1. 下記のコマンドで作成します。なお、cluster-nameを指定しない場合はdefaultという名前で作成されます
    $ aws ecs create-cluster --cluster-name test
    {
        "cluster": {
            "clusterArn": "arn:aws:ecs:ap-northeast-1:XXXXX:cluster/test",
            "clusterName": "test",
            "status": "ACTIVE",
            "registeredContainerInstancesCount": 0,
            "runningTasksCount": 0,
            "pendingTasksCount": 0,
            "activeServicesCount": 0,
            "statistics": [],
            "tags": [],
            "settings": [
                {
                    "name": "containerInsights",
                    "value": "disabled"
                }
            ],
            "capacityProviders": [],
            "defaultCapacityProviderStrategy": []
        }
    }
    $
    
  2. 作成されました
    image.png

describe-clusters / ECSクラスタを確認する

  1. 下記のコマンドで確認します
    $ aws ecs describe-clusters --clusters test
    {
        "clusters": [
            {
                "clusterArn": "arn:aws:ecs:ap-northeast-1:XXXXX:cluster/test",
                "clusterName": "test",
                "status": "ACTIVE",
                "registeredContainerInstancesCount": 0,
                "runningTasksCount": 0,
                "pendingTasksCount": 0,
                "activeServicesCount": 0,
                "statistics": [],
                "tags": [],
                "settings": [],
                "capacityProviders": [],
                "defaultCapacityProviderStrategy": []
            }
        ],
        "failures": []
    }
    

タスク定義

register-task-definition / タスク定義を登録する

  1. 事前にタスク定義のJSONを用意します

    {
        "family": "Example-ecs-service-JavaBackEndApp",
        "networkMode": "awsvpc",
        "containerDefinitions": [
            {
                "name": "Example-java-backend",
                "image": "XXXXX.dkr.ecr.ap-northeast-1.amazonaws.com/example-java-backend:XXXXXX",
                "essential": true,
                "portMappings": [
                    {
                        "containerPort": 80,
                        "hostPort": 80
                    }
                ],
                "logConfiguration": {
                    "logDriver": "awslogs",
                    "options": {
                        "awslogs-group": "/ecs/Example-ecs-service-JavaBackEndApp",
                        "awslogs-region": "ap-northeast-1",
                        "awslogs-stream-prefix": "ecs"
                    }
                }
            }
        ],
        "requiresCompatibilities": [
            "FARGATE"
        ],
        "cpu": "256",
        "memory": "512",
        "executionRoleArn": "arn:aws:iam::XXXXX:role/XXXXX-iam-role-EcsTaskExecution",
        "taskRoleArn": "arn:aws:iam::XXXXX:role/XXXXX-iam-role-EcsTask"
    }
    
  2. 下記のコマンドで登録します

    $ aws ecs create-service --cluster Example-ecs-cluster-JavaBackEndApp --service-name Example-ecs-service-JavaBackEndApp2 --task-definition arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:73 --desired-count 1 --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[subnet-XXXXX,subnet-XXXXX],securityGroups=[sg-XXXXX],assignPublicIp=ENABLED}" --load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:XXXXX:targetgroup/Example-elb2-TargetGroup/XXXXX,containerName=Example-java-backend,containerPort=80"
    {
        "service": {
            "serviceArn": "arn:aws:ecs:ap-northeast-1:XXXXX:service/Example-ecs-cluster-JavaBackEndApp/Example-ecs-service-JavaBackEndApp2",
            "serviceName": "Example-ecs-service-JavaBackEndApp2",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:XXXXX:cluster/Example-ecs-cluster-JavaBackEndApp",
            "loadBalancers": [
                {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:XXXXX:targetgroup/Example-elb2-TargetGroup/XXXXX",
                    "containerName": "Example-java-backend",
                    "containerPort": 80
                }
            ],
            "serviceRegistries": [],
            "status": "ACTIVE",
            "desiredCount": 1,
            "runningCount": 0,
            "pendingCount": 0,
            "launchType": "FARGATE",
            "platformVersion": "LATEST",
            "platformFamily": "Linux",
            "taskDefinition": "arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:73",
            "deploymentConfiguration": {
                "deploymentCircuitBreaker": {
                    "enable": false,
                    "rollback": false
                },
                "maximumPercent": 200,
                "minimumHealthyPercent": 100
            },
            "deployments": [
                {
                    "id": "ecs-svc/XXXXX",
                    "status": "PRIMARY",
                    "taskDefinition": "arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:73",
                    "desiredCount": 0,
                    "pendingCount": 0,
                    "runningCount": 0,
                    "failedTasks": 0,
                    "createdAt": "2024-07-31T13:22:36.356000+09:00",
                    "updatedAt": "2024-07-31T13:22:36.356000+09:00",
                    "launchType": "FARGATE",
                    "platformVersion": "1.4.0",
                    "platformFamily": "Linux",
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-XXXXX",
                                "subnet-XXXXX"
                            ],
                            "securityGroups": [
                                "sg-XXXXX"
                            ],
                            "assignPublicIp": "ENABLED"
                        }
                    },
                    "rolloutState": "IN_PROGRESS",
                    "rolloutStateReason": "ECS deployment ecs-svc/XXXXX in progress."
                }
            ],
            "roleArn": "arn:aws:iam::XXXXX:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
            "events": [],
            "createdAt": "2024-07-31T13:22:36.356000+09:00",
            "placementConstraints": [],
            "placementStrategy": [],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-XXXXX",
                        "subnet-XXXXX"
                    ],
                    "securityGroups": [
                        "sg-XXXXX"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            },
            "healthCheckGracePeriodSeconds": 0,
            "schedulingStrategy": "REPLICA",
            "deploymentController": {
                "type": "ECS"
            },
            "createdBy": "arn:aws:iam::XXXXX:role/aws-reserved/sso.amazonaws.com/ap-northeast-1/XXXXX",
            "enableECSManagedTags": false,
            "propagateTags": "NONE",
            "enableExecuteCommand": false
        }
    }
    

describe-task-definition / タスク定義を確認する

  1. 下記のコマンドで確認します
    $ aws ecs describe-task-definition --task-definition Example-ecs-service-JavaBackEndApp
    {
        "taskDefinition": {
            "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:72",
            "containerDefinitions": [
                {
                    "name": "Example-java-backend",
                    "image": "XXXXX/example-java-backend:XXXXX",
                    "cpu": 0,
                    "portMappings": [
                        {
                            "containerPort": 80,
                            "hostPort": 80,
                            "protocol": "tcp"
                        }
                    ],
                    "essential": true,
                    "environment": [],
                    "mountPoints": [],
                    "volumesFrom": [],
                    "logConfiguration": {
                        "logDriver": "awslogs",
                        "options": {
                            "awslogs-group": "/ecs/Example-ecs-service-JavaBackEndApp",
                            "awslogs-region": "ap-northeast-1",
                            "awslogs-stream-prefix": "ecs"
                        }
                    },
                    "systemControls": []
                }
            ],
            "family": "Example-ecs-service-JavaBackEndApp",
            "taskRoleArn": "arn:aws:iam::XXXXX:role/Example-iam-role-EcsTask",
            "executionRoleArn": "arn:aws:iam::XXXXX:role/Example-iam-role-EcsTaskExecution",
            "networkMode": "awsvpc",
            "revision": 72,
            "volumes": [],
            "status": "ACTIVE",
            "requiresAttributes": [
                {
                    "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
                },
                {
                    "name": "ecs.capability.execution-role-awslogs"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
                },
                {
                    "name": "com.amazonaws.ecs.capability.task-iam-role"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
                },
                {
                    "name": "ecs.capability.task-eni"
                }
            ],
            "placementConstraints": [],
            "compatibilities": [
                "EC2",
                "FARGATE"
            ],
            "requiresCompatibilities": [
                "FARGATE"
            ],
            "cpu": "256",
            "memory": "512",
            "registeredAt": "2024-07-31T11:17:28.266000+09:00",
            "registeredBy": "arn:aws:sts::XXXXX:assumed-role/XXXXX/XXXXX"
        },
        "tags": []
    }
    $
    

サービス

create-service / サービスを起動する

  1. 下記のコマンドでサービスを起動します
    $ aws ecs create-service --cluster Example-ecs-cluster-JavaBackEndApp --service-name Example-ecs-service-JavaBackEndApp2 --task-definition arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:72 --desired-count 1 --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[subnet-XXXXX,subnet-XXXXX],securityGroups=[sg-XXXXX],assignPublicIp=ENABLED}" --load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:XXXXX:targetgroup/Example-elb2-TargetGroup/XXXXX,containerName=Example-java-backend,containerPort=80" 
    {
        "service": {
            "serviceArn": "arn:aws:ecs:ap-northeast-1:XXXXX:service/Example-ecs-cluster-JavaBackEndApp/Example-ecs-service-JavaBackEndApp2",
            "serviceName": "Example-ecs-service-JavaBackEndApp2",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:XXXXX:cluster/Example-ecs-cluster-JavaBackEndApp",
            "loadBalancers": [
                {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:XXXXX:targetgroup/Example-elb2-TargetGroup/XXXXX",
                    "containerName": "Example-java-backend",
                    "containerPort": 80
                }
            ],
            "serviceRegistries": [],
            "status": "ACTIVE",
            "desiredCount": 1,
            "runningCount": 0,
            "pendingCount": 0,
            "launchType": "FARGATE",
            "platformVersion": "LATEST",
            "platformFamily": "Linux",
            "taskDefinition": "arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:72",
            "deploymentConfiguration": {
                "deploymentCircuitBreaker": {
                    "enable": false,
                    "rollback": false
                },
                "maximumPercent": 200,
                "minimumHealthyPercent": 100
            },
            "deployments": [
                {
                    "id": "ecs-svc/XXXXX",
                    "status": "PRIMARY",
                    "taskDefinition": "arn:aws:ecs:ap-northeast-1:XXXXX:task-definition/Example-ecs-service-JavaBackEndApp:72",
                    "desiredCount": 0,
                    "pendingCount": 0,
                    "runningCount": 0,
                    "failedTasks": 0,
                    "createdAt": "2024-07-31T13:14:00.320000+09:00",
                    "updatedAt": "2024-07-31T13:14:00.320000+09:00",
                    "launchType": "FARGATE",
                    "platformVersion": "1.4.0",
                    "platformFamily": "Linux",
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-XXXXX",
                                "subnet-XXXXX"
                            ],
                            "securityGroups": [
                                "sg-XXXXX"
                            ],
                            "assignPublicIp": "ENABLED"
                        }
                    },
                    "rolloutState": "IN_PROGRESS",
                    "rolloutStateReason": "ECS deployment ecs-svc/XXXXX in progress."
                }
            ],
            "roleArn": "arn:aws:iam::XXXXX:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
            "events": [],
            "createdAt": "2024-07-31T13:14:00.320000+09:00",
            "placementConstraints": [],
            "placementStrategy": [],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-XXXXX",
                        "subnet-XXXXX"
                    ],
                    "securityGroups": [
                        "sg-XXXXX"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            },
            "healthCheckGracePeriodSeconds": 0,
            "schedulingStrategy": "REPLICA",
            "deploymentController": {
                "type": "ECS"
            },
            "createdBy": "arn:aws:iam::XXXXX:role/aws-reserved/sso.amazonaws.com/ap-northeast-1/XXXXX",
            "enableECSManagedTags": false,
            "propagateTags": "NONE",
            "enableExecuteCommand": false
        }
    }
    
  2. アクティブになりました
    image.png

update-service / サービスを更新する

  1. 下記のコマンドでサービスを更新します
    $ aws ecs update-service --cluster Example-ecs-cluster-JavaBackEndApp --service Example-ecs-service-JavaBackEndApp3 --desired-count 0       
    {
        "service": {
            "serviceArn": "arn:aws:ecs:ap-northeast-1:XXXX:service/Example-ecs-cluster-JavaBackEndApp/Example-ecs-service-JavaBackEndApp3",
            "serviceName": "Example-ecs-service-JavaBackEndApp3",
            "clusterArn": "arn:aws:ecs:ap-northeast-1:XXXX:cluster/Example-ecs-cluster-JavaBackEndApp",
            "loadBalancers": [
                {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:XXXX:targetgroup/Example-elb2-TargetGroup/XXXX",
                    "containerName": "Example-java-backend",
                    "containerPort": 80
                }
            ],
            "serviceRegistries": [],
            "status": "ACTIVE",
            "desiredCount": 0,
            "runningCount": 0,
            "pendingCount": 0,
            "launchType": "FARGATE",
            "platformVersion": "LATEST",
            "platformFamily": "Linux",
            "taskDefinition": "arn:aws:ecs:ap-northeast-1:XXXX:task-definition/Example-ecs-service-JavaBackEndApp:75",
            "deploymentConfiguration": {
                "deploymentCircuitBreaker": {
                    "enable": false,
                    "rollback": false
                },
                "maximumPercent": 200,
                "minimumHealthyPercent": 100
            },
            "deployments": [
                {
                    "id": "ecs-svc/XXXX",
                    "status": "PRIMARY",
                    "taskDefinition": "arn:aws:ecs:ap-northeast-1:XXXX:task-definition/Example-ecs-service-JavaBackEndApp:75",
                    "desiredCount": 1,
                    "pendingCount": 0,
                    "runningCount": 0,
                    "failedTasks": 0,
                    "createdAt": "2024-07-31T14:21:25.262000+09:00",
                    "updatedAt": "2024-07-31T15:44:02.785000+09:00",
                    "launchType": "FARGATE",
                    "platformVersion": "1.4.0",
                    "platformFamily": "Linux",
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-XXXX",
                                "subnet-XXXX"
                            ],
                            "securityGroups": [
                                "sg-XXXX"
                            ],
                            "assignPublicIp": "ENABLED"
                        }
                    },
                    "rolloutState": "COMPLETED",
                    "rolloutStateReason": "ECS deployment ecs-svc/XXXX completed."
                }
            ],
            "roleArn": "arn:aws:iam::XXXX:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
            "events": [
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T15:45:17.896000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) failed to launch a task with (error Error retrieving security group information for [sg-0265648a717b7c21b]: The security group 'sg-XXXX' does not exist (ErrorCode: InvalidGro
    up.NotFound))."
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T15:44:11.633000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3, taskSet ecs-svc/XXXX) has begun draining connections on 1 tasks."
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T15:44:11.627000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) failed to deregister targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:XXXX:targetgroup/Example-elb2-TargetGroup/XXXX) with (error Target groups 'ar
    n:aws:elasticloadbalancing:ap-northeast-1:XXXXX:targetgroup/Example-elb2-TargetGroup/XXXX' not found)"
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T15:44:02.912000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) has stopped 1 running tasks: (task 6b2e1c03c7a241d4b4c38896fc494386)."
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T14:23:09.852000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) has reached a steady state."
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T14:23:09.851000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) (deployment ecs-svc/6405515881307664181) deployment completed."
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T14:22:21.271000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:XXXXX:targetgroup/Example-elb2-TargetGroup/7e177518df3981d9)"
                },
                {
                    "id": "XXXX",
                    "createdAt": "2024-07-31T14:21:41.310000+09:00",
                    "message": "(service Example-ecs-service-JavaBackEndApp3) has started 1 tasks: (task XXXX)."
                }
            ],
            "createdAt": "2024-07-31T14:21:25.262000+09:00",
            "placementConstraints": [],
            "placementStrategy": [],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-XXXX",
                        "subnet-XXXX"
                    ],
                    "securityGroups": [
                        "sg-XXXX"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            },
            "healthCheckGracePeriodSeconds": 0,
            "schedulingStrategy": "REPLICA",
            "deploymentController": {
                "type": "ECS"
            },
            "createdBy": "arn:aws:iam::XXXX:role/GitHubActions-for-java-backend",
            "enableECSManagedTags": false,
            "propagateTags": "NONE",
            "enableExecuteCommand": false
        }
    }
    $
    

delete-service / サービスを削除する

  1. 下記のコマンドで削除します
    aws ecs delete-service --cluster Example-ecs-cluster-JavaBackEndApp --service Example-ecs-service-JavaBackEndApp3 
    
  2. 消えました
    image.png

考察

今回、ECSやECRについて、AWS CLIから操作するコマンドを記載しました。今後もアップデートしていく予定です。

参考

0
0
0

Register as a new user and use Qiita more conveniently

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