dullwhaleのメモ帳

何度も同じことを調べなくてよいように...

ECS関連をAWS CLIで列挙したり、一括操作したり

複数のリソース

クラスタ名とサービス名をタブ区切りで列挙

出力の1列目にクラスタ名、2列目にサービス名が表示される。

aws ecs list-clusters --output text | cut -f2 | xargs -L 1 -P 16 -I {} aws ecs list-services --cluster {} --output text | sed -E 's|.+:service/(.+)/(.+)|\1\t\2|' | sort

最後のsortはお好みで

出力例

cluster-name-1    service-name-1
cluster-name-1  service-name-2
cluster-name-2  service-name-1
cluster-name-2  service-name-2

リソースからfooタグを一括削除する

ECSタスク、ECSサービスで使えることを確認済

cat target-list xargs -P 16 -I ARN aws ecs untag-resource --resource-arn ARN --tag-keys "foo"

ここで、target-listファイルはリソースのARNが1行毎に書かれていることを想定している。

サービス

サービスをARNで列挙

aws ecs list-clusters --output text | cut -f2 | xargs -L 1 -P 16 -I {} aws ecs list-services --cluster {} --output text | cut -f2

出力例

arn:aws:ecs:ap-northeast-1:123456789012:service/cluster-name-1/service-name-1
arn:aws:ecs:ap-northeast-1:123456789012:service/cluster-name-1/service-name-2
arn:aws:ecs:ap-northeast-1:123456789012:service/cluster-name-2/service-name-1
arn:aws:ecs:ap-northeast-1:123456789012:service/cluster-name-2/service-name-2

サービスについているfooタグの値をARNと共に列挙

aws ecs list-clusters --output text | cut -f2 | xargs -L 1 -P 16 -I {} aws ecs list-services --cluster {} --output text | cut -f2 | xargs -I ARN /bin/sh -c 'echo -en "ARN\t"; aws ecs list-tags-for-resource --resource-arn ARN --query "tags[?key=='foo'].value | [0]" --output text | tr -d "\r"'

出力例 タブ区切り

arn:aws:ecs:ap-northeast-1:123456789012:service/cluster-name-1/service-name-1 bar1
arn:aws:ecs:ap-northeast-1:123456789012:service/cluster-name-2/service-name-1   bar2

タスク

タスクをARNで列挙

aws ecs list-clusters --output text | cut -f2 | xargs -L 1 -P 16 -I {} aws ecs list-tasks --cluster {} --output text | cut -f2

出力例

arn:aws:ecs:ap-northeast-1:123456789012:task/cluster-name-1/0123456789abcdef0123456789abcdef
arn:aws:ecs:ap-northeast-1:123456789012:task/cluster-name-1/0123456789abcdef0123456789abcdf0
arn:aws:ecs:ap-northeast-1:123456789012:task/cluster-name-2/0123456789abcdef0123456789abcdf1
arn:aws:ecs:ap-northeast-1:123456789012:task/cluster-name-2/0123456789abcdef0123456789abcdf2

タスクについているfooタグの値をARNと共に列挙

aws ecs list-clusters --output text | cut -f2 | xargs -L 1 -P 16 -I {} aws ecs list-tasks --cluster {} --output text | cut -f2 | xargs -I ARN /bin/sh -c 'echo -en "ARN\t"; aws ecs list-tags-for-resource --resource-arn ARN --query "tags[?key=='foo'].value | [0]" --output text | tr -d "\r"'

出力例 タブ区切り

arn:aws:ecs:ap-northeast-1:123456789012:task/cluster-name-1/0123456789abcdef0123456789abcdef  bar1
arn:aws:ecs:ap-northeast-1:123456789012:task/cluster-name-2/0123456789abcdef0123456789abcdf1    bar2