0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FargateにSSMでログイン ~停止したコンテナをマネージドインスタンスから一括削除~

Last updated at Posted at 2020-08-28

概要

AWS ECS の Fargateコンテナに対してSSM使用したログインを行うことができる。その際にコンテナを生成するごとにマネージドインスタンスに登録されるが、コンテナが終了しても自動では削除されないため、手動で削除行う必要があった

AWSコンソール画面からマネージドインスタンスを一括で削除できないため、CLIを通して一括削除するコマンドを作成してみた

SSMを使ったコンテナへのログイン方法等については下記を参照

マネージドインスタンス一覧取得コマンド

$ aws ssm describe-instance-information

下記のようにJSONでレスポンスが返ってくる。 --filterにKeyを指定することで一覧取得時の条件を指定することが可能

{
    "InstanceInformationList": [
        {
            "InstanceId": "<instanceId>",
            "PingStatus": "ConnectionLost",
            "LastPingDateTime": "2020-04-20T15:38:33.983000+09:00",
            "AgentVersion": "2.3.978.0",
            "IsLatestVersion": false,
            "PlatformType": "Linux",
            "PlatformName": "Debian GNU/Linux",
            "PlatformVersion": "8",
            "ActivationId": "<ActivationId>",
            "IamRole": "service-role/AmazonEC2RunCommandRoleForManagedInstances",
            "RegistrationDate": "2020-04-20T15:38:32.732000+09:00",
            "ResourceType": "ManagedInstance",
            "IPAddress": "<IPAddress>",
            "ComputerName": "<ComputerName>",
            "AssociationStatus": "Failed",
            "LastAssociationExecutionDate": "2020-04-20T16:48:59.672000+09:00",
            "AssociationOverview": {
                "DetailedStatus": "Failed",
                "InstanceAssociationStatusAggregatedCount": {
                    "Failed": 1,
                    "Pending": 1
                }
            }
        }
    ]
}

削除コマンド

--instance-id に取得した InstanceId を 指定することで一つずつ削除が可能

$ aws ssm deregister-managed-instance --instance-id <InstanceId>

一括削除コマンド

一覧取得ときにConnectionLostおよび、ManagedInstanceを対象とし、接続が切れたマネージドインスタンスを削除するコマンドを作成した。ActivationIdを --filter で指定することはできなかった。実行する際は誤った物を削除しないように注意すること

$ aws ssm describe-instance-information \
    --filters \
       "Key=PingStatus,Values=ConnectionLost" \
       "Key=ResourceType,Values=ManagedInstance" \
    | grep 'InstanceId' \
    | awk '{print $2}' \
    | sed -e 's/,//g' \
    | xargs -L 1 -I arg aws ssm deregister-managed-instance --instance-id arg
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?