LoginSignup
1
1

More than 3 years have passed since last update.

AWS CLIでフィルターをかける方法(filtersオプション)

Last updated at Posted at 2020-02-01

はじめに

Elasticacheのチュートリアルをやっている時に、コマンドの引数で「デフォルトのセキュリティグループのIDを指定する」という部分があったので、コマンドで楽に拾う方法がないかと思い、CLIを少し調べました。

差し当たり、--queryの方は敷居が高そうだったので--filtersの方を調べました。

環境情報

OS : Windows10
CLI : aws-cli/1.17.9 Python/3.7.4 Windows/10 botocore/1.14.9

構文

今回は「デフォルトのセキュリティグループのID」が欲しかったので、グループ名が「default」のものを検索しました。

aws ec2 describe-security-groups --filters "Name=group-name,Values=default"
  • 書式 : --filters "Name=(name),Values=(value)"

※注意点
① 大文字と小文字は区別される("name="のように書くと構文エラーになる)
② Name=で指定する名前はコマンド出力結果と異なる

例えば、下記情報をfiltersで取得したい場合。

{
    "SecurityGroups": [
        {
            "Description": "default VPC security group",
            "GroupName": "default",
            "IpPermissions": [
                {

この場合で、グループ名で検索したいからといって「Name=GroupName」と書いてもエラーになります。
これはコマンドの出力される時の名前と内部で管理している名前が異なるためです。

> aws ec2 describe-security-groups --filters "Name=GroupName,Values=default"

An error occurred (InvalidParameterValue) when calling the DescribeSecurityGroups operation: The filter 'GroupName' is invalid

--filtersでどのリソース名を指定すれば良いかは、コマンドに「help」を付けると確認することができます。

> aws ec2 describe-security-groups help

(省略)
Options
*******

(省略)
"--filters" (list)

   The filters. If using multiple filters for rules, the results
   include security groups for which any combination of rules - not
   necessarily a single rule - match all filters.
(省略)

   * "group-name" - The name of the security group.

(以下省略)

補足

--filtersでAND検索をする場合は、"Name~Values~"のセットを空白区切りでもう一つ追加します。
(その際、条件セット毎に""で括ってあげないとうまく拾えないので注意)

aws ec2 describe-security-groups --filters "Name=group-name,Values=default" "Name=vpc-id,Values=vpc-a43d6fc3"

OR検索をする場合は、キー(Values)の部分にカンマ(,)で追加します。

aws ec2 describe-security-groups --filters "Name=group-name,Values=default,launch-wizard-9"

尚、別々のキーをOR検索したい場合はそのままではできないので、複数回コマンドを実行した上で結果をマージする、という作業が必要になるそうです。

参考URL

1
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
1
1