

# AWS CLI에서 출력 필터링
<a name="cli-usage-filter"></a>

AWS Command Line Interface(AWS CLI)에는 개별적으로 또는 함께 사용하여 AWS CLI 출력을 필터링할 수 있는 서버 측 필터링과 클라이언트 측 필터링이 둘 다 있습니다. 서버 측 필터링이 먼저 처리되고 클라이언트 측 필터링에 대한 출력을 반환합니다.
+ 서버 측 필터링은 API에서 지원되며, 일반적으로 `--filter` 매개 변수를 사용하여 구현합니다. 이 서비스는 대량 데이터세트에 대한 HTTP 응답 시간을 단축할 수 있는 일치하는 결과만 반환합니다.
+ 클라이언트 측 필터링은 AWS CLI 매개 변수를 사용하여 `--query` 클라이언트에서 지원됩니다. 이 파라미터에는 서버 측 필터링에 없을 수 있는 기능이 있습니다.

**Topics**
+ [서버 측 필터링](#cli-usage-filter-server-side)
+ [클라이언트 측 필터링](#cli-usage-filter-client-side)
+ [서버 측 필터링과 클라이언트 측 필터링 결합](#cli-usage-filter-combining)
+ [추가 리소스](#cli-usage-filter-resources)

## 서버 측 필터링
<a name="cli-usage-filter-server-side"></a>

AWS CLI의 서버 측 필터링은 AWS 서비스 API에서 제공됩니다. AWS 서비스는 필터와 일치하는 HTTP 응답의 레코드만 반환하며, 이렇게 되면 대량 데이터세트에 대한 HTTP 응답 시간을 단축할 수 있습니다. 서버 측 필터링은 서비스 API에 의해 정의되므로, 매개 변수 이름과 함수는 서비스마다 달라집니다. 필터링에 사용되는 몇 가지 일반적인 매개 변수 이름은 다음과 같습니다.
+ `--filter`(예: [ses](https://docs.aws.amazon.com/cli/latest/reference/ses/create-receipt-filter.html) 및 [ce](https://docs.aws.amazon.com/cli/latest/reference/ce/get-cost-and-usage.html)).
+ `--filters`(예: [ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-volumes.html), [autoscaling](https://docs.aws.amazon.com/cli/latest/reference/autoscaling/describe-tags.html) 및 [rds](https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html)).
+ `filter`라는 단어로 시작하는 이름입니다(예: [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html) 명령의 경우 `--filter-expression`).

특정 명령에 서버 측 필터링과 필터링 규칙이 있는지에 대한 자세한 내용은 [AWS CLI 버전 2 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/index.html)를 참조하세요.

## 클라이언트 측 필터링
<a name="cli-usage-filter-client-side"></a>

AWS CLI은(는) `--query` 매개 변수를 사용하는 기본 제공 JSON 기반 클라이언트 측 필터링 기능을 제공합니다. `--query` 매개 변수는 출력의 내용과 스타일을 사용자 지정하는 데 사용할 수 있는 강력한 도구입니다. `--query` 매개 변수는 서버에서 다시 오는 HTTP 응답을 받아, 결과를 필터링한 후에 이를 표시합니다. 필터링하기 전에 전체 HTTP 응답이 클라이언트로 전송되므로, 클라이언트 측 필터링은 대량 데이터세트에 대한 서버 측 필터링보다 느릴 수 있습니다.

쿼리는 [JMESPath 구문](https://jmespath.org/)을 사용하여 출력을 필터링하는 표현식을 만듭니다. JMESPath 구문에 대해 알아보려면 *JMESPath 웹사이트*에서 [자습서](https://jmespath.org/tutorial.html)를 참조하세요.

**중요**  
지정한 출력 유형에 따라 `--query` 옵션 작동 방식이 변경됩니다.  
`--output text`를 지정하면 `--query` 필터를 적용하기 *전에* 해당 출력이 페이지 매김되며, AWS CLI는 해당 출력의 *각 페이지*에서 해당 쿼리를 한 번 실행합니다. 이로 인해, 쿼리에는 예상치 못한 추가 출력이 발생할 수 있는 각 페이지의 첫 번째 일치하는 요소가 포함됩니다. 출력을 추가로 필터링하려면 `head` 또는 `tail` 등 다른 명령줄 도구를 사용할 수 있습니다.
`--output json`, `--output yaml` 또는 `--output yaml-stream`을 지정하면 해당 출력을 하나의 네이티브 구조로 완전히 처리한 뒤에 `--query` 필터를 적용합니다. AWS CLI은(는) 전체 구조에 대해 한 번만 쿼리를 실행하여 필터링된 결과를 생성한 다음 출력합니다.

**Topics**
+ [시작하기 전에](#cli-usage-filter-client-side-output)
+ [식별자](#cli-usage-filter-client-side-identifiers)
+ [목록에서 선택](#cli-usage-filter-client-side-select-list)
+ [중첩된 데이터 필터링](#cli-usage-filter-client-side-nested)
+ [결과 병합](#cli-usage-filter-client-side-specific-flattening)
+ [특정 값에 대한 필터링](#cli-usage-filter-client-side-specific-values)
+ [파이핑 표현식](#cli-usage-filter-client-side-pipe)
+ [여러 식별자 값에 대한 필터링](#cli-usage-filter-client-side-miltiselect-list)
+ [식별자 값에 레이블 추가](#cli-usage-filter-client-side-multiselect-hash)
+ [함수](#cli-usage-filter-client-side-functions)
+ [고급 `--query` 예제](#cli-usage-filter-client-side-advanced)

### 시작하기 전에
<a name="cli-usage-filter-client-side-output"></a>

**참고**  
이러한 필터 표현식 예제는 기본 Linux와 유사한 쉘에 대해 작성되었습니다. 이 예제를 사용할 때는 터미널 셸에 올바른 인용 규칙을 사용해야 합니다. 터미널이 입력을 해석하는 방식은 AWS CLI로 전송되는 항목을 크게 변경할 수 있습니다. 터미널이 작은따옴표(`'`), 큰따옴표(`"`) 또는 백틱(```)을 읽는 방법은 콘텐츠 읽기 방법을 변경할 수 있습니다.  
자세한 내용은 [AWS CLI에서 문자열에 따옴표와 리터럴 사용](cli-usage-parameters-quoting-strings.md) 섹션을 참조하세요.

다음 JSON 출력은 `--query` 매개 변수가 생성할 수 있는 결과물의 예를 보여줍니다. 이 출력은 별도의 Amazon EC2 인스턴스에 연결된 세 가지 Amazon EBS 볼륨을 설명합니다.

#### 출력 예시
<a name="cli-usage-filter-client-side-output-example"></a>

```
$ aws ec2 describe-volumes
{
  "Volumes": [
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-17T00:55:03.000Z",
          "InstanceId": "i-a071c394",
          "VolumeId": "vol-e11a5288",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-e11a5288",
      "State": "in-use",
      "SnapshotId": "snap-f23ec1c8",
      "CreateTime": "2013-09-17T00:55:03.000Z",
      "Size": 30
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-18T20:26:16.000Z",
          "InstanceId": "i-4b41a37c",
          "VolumeId": "vol-2e410a47",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-2e410a47",
      "State": "in-use",
      "SnapshotId": "snap-708e8348",
      "CreateTime": "2013-09-18T20:26:15.000Z",
      "Size": 8
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2020-11-20T19:54:06.000Z",
          "InstanceId": "i-1jd73kv8",
          "VolumeId": "vol-a1b3c7nd",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-a1b3c7nd",
      "State": "in-use",
      "SnapshotId": "snap-234087fb",
      "CreateTime": "2020-11-20T19:54:05.000Z",
      "Size": 15
    }
  ]
}
```

### 식별자
<a name="cli-usage-filter-client-side-identifiers"></a>

식별자는 출력 값의 레이블입니다. 필터를 만들 때 식별자를 사용하여 쿼리 결과 범위를 좁힙니다. 다음 출력 예제에서는 `Volumes`, `AvailabilityZone`, `AttachTime` 등 모든 식별자가 강조 표시됩니다.

```
$ aws ec2 describe-volumes
{
  "Volumes": [
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-17T00:55:03.000Z",
          "InstanceId": "i-a071c394",
          "VolumeId": "vol-e11a5288",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-e11a5288",
      "State": "in-use",
      "SnapshotId": "snap-f23ec1c8",
      "CreateTime": "2013-09-17T00:55:03.000Z",
      "Size": 30
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-18T20:26:16.000Z",
          "InstanceId": "i-4b41a37c",
          "VolumeId": "vol-2e410a47",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-2e410a47",
      "State": "in-use",
      "SnapshotId": "snap-708e8348",
      "CreateTime": "2013-09-18T20:26:15.000Z",
      "Size": 8
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2020-11-20T19:54:06.000Z",
          "InstanceId": "i-1jd73kv8",
          "VolumeId": "vol-a1b3c7nd",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-a1b3c7nd",
      "State": "in-use",
      "SnapshotId": "snap-234087fb",
      "CreateTime": "2020-11-20T19:54:05.000Z",
      "Size": 15
    }
  ]
}
```

자세한 내용은 *JMESPath 웹사이트*의 [식별자](https://jmespath.org/specification.html#identifiers )를 참조하세요.

### 목록에서 선택
<a name="cli-usage-filter-client-side-select-list"></a>

목록 또는 배열은 `[`의 `Volumes` 및 `Attachments` 등 대괄호 “[시작하기 전에](#cli-usage-filter-client-side-output)” 뒤에 오는 식별자입니다.

**구문**:

```
<listName>[ ]
```

배열의 모든 출력을 필터링하려면 와일드 카드 표기법을 사용할 수 있습니다. [와일드카드](http://jmespath.org/specification.html#wildcard-expressions) 표현식은 `*` 표기법을 사용하여 요소를 반환하는 데 사용되는 표현식입니다.

다음 예제에서는 모든 `Volumes` 내용을 쿼리합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2020-11-20T19:54:06.000Z",
        "InstanceId": "i-1jd73kv8",
        "VolumeId": "vol-a1b3c7nd",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-a1b3c7nd",
    "State": "in-use",
    "SnapshotId": "snap-234087fb",
    "CreateTime": "2020-11-20T19:54:05.000Z",
    "Size": 15
  }
]
```

인덱스별로 배열의 특정 볼륨을 보려면 배열 인덱스를 호출합니다. 예를 들어, `Volumes` 배열의 첫 번째 항목은 인덱스가 0이고 `Volumes[0]` 쿼리가 생성됩니다. 배열 인덱스에 대한 자세한 내용은 *JMESPath 웹 사이트*의 [인덱스 표현식](http://jmespath.org/specification.html#index-expressions)을 참조하세요.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[0]'
{
  "AvailabilityZone": "us-west-2a",
  "Attachments": [
    {
      "AttachTime": "2013-09-17T00:55:03.000Z",
      "InstanceId": "i-a071c394",
      "VolumeId": "vol-e11a5288",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ],
  "VolumeType": "standard",
  "VolumeId": "vol-e11a5288",
  "State": "in-use",
  "SnapshotId": "snap-f23ec1c8",
  "CreateTime": "2013-09-17T00:55:03.000Z",
  "Size": 30
}
```

인덱스별로 특정 범위의 볼륨을 보려면 다음 구문과 함께 `slice`를 사용합니다. 여기서 **start**는 시작 배열 인덱스이고, **stop**은 필터가 처리를 중지하는 인덱스이고, **step**은 건너뛰기 간격입니다.

**구문**:

```
<arrayName>[<start>:<stop>:<step>]
```

다음 항목 중 하나라도 슬라이스 표현식에서 생략된 경우, 다음 기본값을 사용합니다.
+ 시작 - 목록의 첫 번째 인덱스, 0.
+ 중지 - 목록의 마지막 인덱스.
+ 단계 - 건너뛰기 단계 없음. 여기서 값은 1입니다.

처음 두 볼륨만 반환하려면 다음 예제와 같이 시작 값 0, 중지 값 2, 단계 값 1을 사용합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[0:2:1]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-18T20:26:16.000Z",
        "InstanceId": "i-4b41a37c",
        "VolumeId": "vol-2e410a47",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-2e410a47",
    "State": "in-use",
    "SnapshotId": "snap-708e8348",
    "CreateTime": "2013-09-18T20:26:15.000Z",
    "Size": 8
  }
]
```

이 예제에는 기본값이 포함되어 있으므로 슬라이스를 `Volumes[0:2:1]`에서 `Volumes[:2]`(으)로 줄일 수 있습니다.

다음 예제에서는 기본값을 생략하고 전체 배열에서 두 볼륨마다 반환합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[::2]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2020-11-20T19:54:06.000Z",
        "InstanceId": "i-1jd73kv8",
        "VolumeId": "vol-a1b3c7nd",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-a1b3c7nd",
    "State": "in-use",
    "SnapshotId": "snap-234087fb",
    "CreateTime": "2020-11-20T19:54:05.000Z",
    "Size": 15
  }
]
```

단계는 다음 예제와 같이 배열의 역순으로 필터링하는 음수를 사용할 수도 있습니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[::-2]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2020-11-20T19:54:06.000Z",
        "InstanceId": "i-1jd73kv8",
        "VolumeId": "vol-a1b3c7nd",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-a1b3c7nd",
    "State": "in-use",
    "SnapshotId": "snap-234087fb",
    "CreateTime": "2020-11-20T19:54:05.000Z",
    "Size": 15
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  }
]
```

자세한 내용은 *JMESPath 웹사이트*의 [슬라이스](https://jmespath.org/specification.html#slices)를 참조하세요.

### 중첩된 데이터 필터링
<a name="cli-usage-filter-client-side-nested"></a>

중첩된 값의 `Volumes[*]` 필터링 범위를 좁히려면 마침표 및 필터 기준을 추가하여 하위 표현식을 사용합니다.

**구문**:

```
<expression>.<expression>
```

다음 예제에서는 모든 볼륨에 대한 모든 `Attachments` 정보를 보여줍니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments'
[
  [
    {
      "AttachTime": "2013-09-17T00:55:03.000Z",
      "InstanceId": "i-a071c394",
      "VolumeId": "vol-e11a5288",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ],
  [
    {
      "AttachTime": "2013-09-18T20:26:16.000Z",
      "InstanceId": "i-4b41a37c",
      "VolumeId": "vol-2e410a47",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ],
  [
    {
      "AttachTime": "2020-11-20T19:54:06.000Z",
      "InstanceId": "i-1jd73kv8",
      "VolumeId": "vol-a1b3c7nd",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ]
]
```

중첩된 값으로 추가로 필터링하려면 중첩된 각 식별자에 대한 표현식을 추가합니다. 다음 예제에서는 모든 `State`에 대한 `Volumes`이(가) 나와 있습니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[*].State'
[
  [
    "attached"
  ],
  [
    "attached"
  ],
  [
    "attached"
  ]
]
```

### 결과 병합
<a name="cli-usage-filter-client-side-specific-flattening"></a>

자세한 내용은 *JMESPath 웹 사이트*의 [하위 표현식](https://jmespath.org/specification.html#subexpressions)을 참조하세요.

와일드카드 표기법을 제거함으로써 `Volumes[*].Attachments[*].State`에 대한 결과를 병합하여 `Volumes[*].Attachments[].State` 쿼리를 생성할 수 있습니다. 병합은 흔히 결과의 가독성을 높이는 데 유용합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[].State'
[
  "attached",
  "attached",
  "attached"
]
```

자세한 내용은 *JMESPath 웹사이트*의 [병합](https://jmespath.org/specification.html#flatten)을 참조하세요.

### 특정 값에 대한 필터링
<a name="cli-usage-filter-client-side-specific-values"></a>

목록의 특정 값을 필터링하려면 다음 구문과 같이 필터 표현식을 사용합니다.

**구문**:

```
? <expression> <comparator> <expression>]
```

표현식 비교기에는 `==`, `!=`, `<`, `<=`, `>`, `>=`이(가) 포함됩니다. 다음 예제에서는 `VolumeIds``Volumes`의 모든 `Attached`에 대해 `State`을(를) 필터링합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[?State==`attached`].VolumeId'
[
  [
    "vol-e11a5288"
  ],
  [
    "vol-2e410a47"
  ],
  [
    "vol-a1b3c7nd"
  ]
]
```

그런 다음 이를 병합하여 다음 예제처럼 되게 할 수 있습니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[?State==`attached`].VolumeId[]'
[
  "vol-e11a5288",
  "vol-2e410a47",
  "vol-a1b3c7nd"
]
```

다음 예제에서는 크기가 20보다 작은 모든 `VolumeIds`의 `Volumes`을(를) 필터링합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[?Size < `20`].VolumeId'
[
  "vol-2e410a47",
  "vol-a1b3c7nd"
]
```

자세한 내용은 *JMESPath 웹 사이트*의 [필터 표현식](https://jmespath.org/specification.html#filterexpressions)을 참조하세요.

### 파이핑 표현식
<a name="cli-usage-filter-client-side-pipe"></a>

필터 결과를 새 목록으로 파이핑한 후, 다음 구문을 사용하여 다른 표현식으로 결과를 필터링할 수 있습니다.

**구문**:

```
<expression> | <expression>] 
```

다음 예제에서는 `Volumes[*].Attachments[].InstanceId` 표현식의 필터 결과를 가져와 배열의 첫 번째 결과를 출력합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[].InstanceId | [0]'
"i-a071c394"
```

이 예제는 먼저 다음 표현식에서 배열을 생작성하여 이 작업을 수행합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[].InstanceId'
"i-a071c394",
  "i-4b41a37c",
  "i-1jd73kv8"
```

그런 다음 해당 배열의 첫 번째 요소를 반환합니다.

```
"i-a071c394"
```

자세한 내용은 *JMESPath 웹 사이트*의 [파이프 표현식](https://jmespath.org/specification.html#pipe-expressions)을 참조하세요.

### 여러 식별자 값에 대한 필터링
<a name="cli-usage-filter-client-side-miltiselect-list"></a>

여러 식별자를 필터링하려면 다음 구문을 사용하여 다중 선택 목록을 사용합니다.

**구문**:

```
<listName>[].[<expression>, <expression>]
```

다음 예제에서는 `VolumeId` 및 `VolumeType`이(가) `Volumes` 목록에서 필터링되어 다음 표현식이 생성됩니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].[VolumeId, VolumeType]'
[
  [
    "vol-e11a5288",
    "standard"
  ],
  [
    "vol-2e410a47",
    "standard"
  ],
  [
    "vol-a1b3c7nd",
    "standard"
  ]
]
```

중첩된 데이터를 목록에 추가하려면 다른 다중 선택 목록을 추가합니다. 다음 예제에서는 중첩 `InstanceId` 목록에서 `State` 및 `Attachments`도 필터링하여 이전 예제를 확장합니다. 그러면 다음과 같은 표현식이 생성됩니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].[VolumeId, VolumeType, Attachments[].[InstanceId, State]]'
[
  [
    "vol-e11a5288",
    "standard",
    [
      [
        "i-a071c394",
        "attached"
      ]
    ]
  ],
  [
    "vol-2e410a47",
    "standard",
    [
      [
        "i-4b41a37c",
        "attached"
      ]
    ]
  ],
  [
    "vol-a1b3c7nd",
    "standard",
    [
      [
        "i-1jd73kv8",
        "attached"
      ]
    ]
  ]
]
```

더 읽기 쉽게 하려면 다음 예제와 같이 표현식을 병합합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].[VolumeId, VolumeType, Attachments[].[InstanceId, State][]][]'
[
  "vol-e11a5288",
  "standard",
  [
    "i-a071c394",
    "attached"
  ],
  "vol-2e410a47",
  "standard",
  [
    "i-4b41a37c",
    "attached"
  ],
  "vol-a1b3c7nd",
  "standard",
  [
    "i-1jd73kv8",
    "attached"
  ]
]
```

자세한 내용은 *JMESPath 웹 사이트*의 [다중 선택 목록](https://jmespath.org/specification.html#multiselectlist)을 참조하세요.

### 식별자 값에 레이블 추가
<a name="cli-usage-filter-client-side-multiselect-hash"></a>

이 출력을 더 읽기 쉽게 하려면 다음 구문을 사용하여 다중 선택 해시를 사용합니다.

**구문**:

```
<listName>[].{<label>: <expression>, <label>: <expression>}
```

식별자 레이블이 식별자 이름과 같을 필요는 없습니다. 다음 예제에서는 `VolumeType` 값에 `VolumeType` 레이블을 사용합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].{VolumeType: VolumeType}'
[
  {
    "VolumeType": "standard",
  },
  {
    "VolumeType": "standard",
  },
  {
    "VolumeType": "standard",
  }
]
```

간단히, 다음 예제에서는 각 레이블의 식별자 이름을 유지하고 모든 볼륨에 대해 `VolumeId`, `VolumeType`, `InstanceId` 및 `State`을(를) 표시합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].{VolumeId: VolumeId, VolumeType: VolumeType, InstanceId: Attachments[0].InstanceId, State: Attachments[0].State}'
[
  {
    "VolumeId": "vol-e11a5288",
    "VolumeType": "standard",
    "InstanceId": "i-a071c394",
    "State": "attached"
  },
  {
    "VolumeId": "vol-2e410a47",
    "VolumeType": "standard",
    "InstanceId": "i-4b41a37c",
    "State": "attached"
  },
  {
    "VolumeId": "vol-a1b3c7nd",
    "VolumeType": "standard",
    "InstanceId": "i-1jd73kv8",
    "State": "attached"
  }
]
```

자세한 내용은 *JMESPath 웹 사이트*의 [다중 선택 해시](https://jmespath.org/specification.html#multiselecthash)를 참조하세요.

### 함수
<a name="cli-usage-filter-client-side-functions"></a>

JMESPath 구문에는 쿼리에 사용할 수 있는 많은 함수가 포함되어 있습니다. JMESPath 함수에 대한 자세한 내용은 *JMESPath 웹 사이트*의 [기본 제공 함수](https://jmespath.org/specification.html#built-in-functions)를 참조하세요.

함수를 쿼리에 통합하는 방법을 보여주기 위해 다음 예제에서는 `sort_by` 함수를 사용합니다. `sort_by` 함수는 다음 구문을 사용하여 표현식을 정렬 키로 사용해 배열을 정렬합니다.

**구문**:

```
sort_by(<listName>, <sort expression>)[].<expression>
```

다음 예제에서는 이전의 [다중 선택 해시 예제](#cli-usage-filter-client-side-multiselect-hash)를 사용하고 `VolumeId`(으)로 출력을 정렬합니다.

```
$ aws ec2 describe-volumes \
    --query 'sort_by(Volumes, &VolumeId)[].{VolumeId: VolumeId, VolumeType: VolumeType, InstanceId: Attachments[0].InstanceId, State: Attachments[0].State}'
[
  {
    "VolumeId": "vol-2e410a47",
    "VolumeType": "standard",
    "InstanceId": "i-4b41a37c",
    "State": "attached"
  },
  {
    "VolumeId": "vol-a1b3c7nd",
    "VolumeType": "standard",
    "InstanceId": "i-1jd73kv8",
    "State": "attached"
  },
  {
    "VolumeId": "vol-e11a5288",
    "VolumeType": "standard",
    "InstanceId": "i-a071c394",
    "State": "attached"
  }
]
```

자세한 내용은 *JMESPath 웹 사이트*의 [sort\$1by](https://jmespath.org/specification.html#sort-by)를 참조하세요.

### 고급 `--query` 예제
<a name="cli-usage-filter-client-side-advanced"></a>

**특정 항목에서 정보를 추출하는 방법**

다음 예제에서는 목록에서 특정 항목을 찾은 다음 해당 항목에서 정보를 추출하는 데 `--query` 파라미터를 사용합니다. 이 예제에서는 지정된 서비스 엔드포인트에 연결된 모든 `AvailabilityZones`을(를) 나열합니다. 지정된 `ServiceDetails`을 가진 `ServiceName` 목록에서 해당 항목을 추출한 다음, 선택한 항목에서 `AvailabilityZones` 필드를 출력합니다.

```
$ aws --region us-east-1 ec2 describe-vpc-endpoint-services \
    --query 'ServiceDetails[?ServiceName==`com.amazonaws.us-east-1.ecs`].AvailabilityZones'
[
    [
        "us-east-1a",
        "us-east-1b",
        "us-east-1c",
        "us-east-1d",
        "us-east-1e",
        "us-east-1f"
    ]
]
```

**지정된 생성 날짜 이후 스냅샷을 표시하는 방법**

다음 예제에서는 출력에 사용 가능한 필드를 몇 개만 포함하여 지정된 날짜 이후에 생성된 모든 스냅샷을 나열하는 방법을 보여줍니다.

```
$ aws ec2 describe-snapshots --owner self \
    --output json \
    --query 'Snapshots[?StartTime>=`2018-02-07`].{Id:SnapshotId,VId:VolumeId,Size:VolumeSize}'
[
    {
        "id": "snap-0effb42b7a1b2c3d4",
        "vid": "vol-0be9bb0bf12345678",
        "Size": 8
    }
]
```

**최신 AMI를 표시하는 방법**

다음 예제에서는 가장 최근에 생성된 5개의 Amazon Machine Image(AMI)를 가장 최근부터 가장 오래된 순으로 정렬하여 나열합니다.

```
$ aws ec2 describe-images \
    --owners self \
    --query 'reverse(sort_by(Images,&CreationDate))[:5].{id:ImageId,date:CreationDate}'
[
    {
        "id": "ami-0a1b2c3d4e5f60001",
        "date": "2018-11-28T17:16:38.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60002",
        "date": "2018-09-15T13:51:22.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60003",
        "date": "2018-08-19T10:22:45.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60004",
        "date": "2018-05-03T12:04:02.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60005",
        "date": "2017-12-13T17:16:38.000Z"
    }
]
```

**비정상 Auto Scaling 인스턴스를 표시하려면**

다음 예제에서는 지정된 AutoScaling 그룹의 비정상 인스턴스에 대한 `InstanceId`만 보여줍니다.

```
$ aws autoscaling describe-auto-scaling-groups \
    --auto-scaling-group-name My-AutoScaling-Group-Name \
    --output text \
    --query 'AutoScalingGroups[*].Instances[?HealthStatus==`Unhealthy`].InstanceId'
```

**지정된 태그가 있는 볼륨을 포함하는 방법**

다음 예제에서는 `test` 태그가 있는 모든 인스턴스에 대해 설명합니다. 볼륨에 연결된 `test` 옆에 또 다른 태그가 있으면, 볼륨은 여전히 결과에 반환됩니다.

아래 표현식은 `test` 태그가 있는 모든 태그를 배열에 반환합니다. `test` 태그가 아닌 모든 태그에는 `null` 값이 포함됩니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Tags[?Value == `test`]'
```

**지정된 태그가 있는 볼륨을 제외하는 방법**

다음 예제에서는 `test` 태그가 없는 모든 인스턴스에 대해 설명합니다. 볼륨에 여러 태그가 있을 수 있으므로 단순 `?Value != `test`` 표현식을 사용하면 볼륨을 제외하지 않습니다. 볼륨에 연결된 `test` 옆에 또 다른 태그가 있으면, 볼륨은 여전히 결과에 반환됩니다.

`test` 태그가 있는 모든 볼륨을 제외하려면 아래 표현식으로 시작하여 `test` 태그가 있는 모든 태그를 배열에 반환합니다. `test` 태그가 아닌 모든 태그에는 `null` 값이 포함됩니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Tags[?Value == `test`]'
```

그런 다음 `test` 함수를 사용하여 모든 양의 `not_null` 결과를 필터링합니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[?!not_null(Tags[?Value == `test`].Value)]'
```

결과를 파이핑하여 결과를 병합하면 다음 쿼리가 생성됩니다.

```
$ aws ec2 describe-volumes \
    --query 'Volumes[?!not_null(Tags[?Value == `test`].Value)] | []'
```

## 서버 측 필터링과 클라이언트 측 필터링 결합
<a name="cli-usage-filter-combining"></a>

서버 측 필터링과 클라이언트 측 필터링을 함께 사용할 수 있습니다. 서버 측 필터링이 먼저 완료되어, `--query` 매개 변수가 필터링하는 데이터를 클라이언트로 보냅니다. 대량 데이터세트를 사용하는 경우, 먼저 서버 측 필터링을 사용하면 클라이언트 측 필터링이 제공하는 강력한 사용자 지정을 유지하면서 각 AWS CLI 호출에 대해 클라이언트로 전송되는 데이터 양을 줄일 수 있습니다.

다음 예제에서는 서버 측 필터링과 클라이언트 측 필터링을 둘 다 사용하는 Amazon EC2 볼륨을 나열합니다. 이 서비스는 `us-west-2a` 가용 영역에서 연결된 모든 볼륨의 목록을 필터링합니다. `--query` 파라미터는 또한 출력을 50보다 큰 `Size` 값을 가진 볼륨으로만 제한하며 사용자 정의 이름으로 지정된 필드만 표시합니다.

```
$ aws ec2 describe-volumes \
    --filters "Name=availability-zone,Values=us-west-2a" "Name=status,Values=attached" \
    --query 'Volumes[?Size > `50`].{Id:VolumeId,Size:Size,Type:VolumeType}'
[
    {
        "Id": "vol-0be9bb0bf12345678",
        "Size": 80,
        "VolumeType": "gp2"
    }
]
```

다음 예제에서는 여러 기준을 충족하는 이미지의 목록을 가져옵니다. 그런 다음 `--query` 파라미터를 사용하여 `CreationDate`를 기준으로 출력을 정렬하고 가장 최근 항목만 선택합니다. 마지막으로 해당 이미지의 `ImageId`를 표시합니다.

```
$ aws ec2 describe-images \
    --owners amazon \
    --filters "Name=name,Values=amzn*gp2" "Name=virtualization-type,Values=hvm" "Name=root-device-type,Values=ebs" \
    --query "sort_by(Images, &CreationDate)[-1].ImageId" \
    --output text
ami-00ced3122871a4921
```

다음 예제에서는 `length`로 목록의 항목 수를 계산하여 1000 IOPS 이상인 사용 가능한 볼륨 수를 표시합니다.

```
$ aws ec2 describe-volumes \
    --filters "Name=status,Values=available" \
    --query 'length(Volumes[?Iops > `1000`])'
3
```

다음 예시에서는 CloudFormation 스택을 사용하는 지정된 AWS 리전에서 시작 구성을 사용하는 Auto Scaling 그룹의 이름을 검색합니다.

```
$ aws autoscaling describe-auto-scaling-groups --region us-west-2 \
  --filters Name=tag-key,Values=aws:cloudformation:stack-name \
  --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`].AutoScalingGroupName'
[
    "group-1",
    "group-2",
    "group-3"
]
```

## 추가 리소스
<a name="cli-usage-filter-resources"></a>

**AWS CLI 자동 프롬프트**  
필터 표현식 사용을 시작할 때 AWS CLI 버전 2에서 자동 프롬프트 기능을 사용할 수 있습니다. 자동 프롬프트 기능은 **F5** 키를 누를 때 미리 보기를 제공합니다. 자세한 내용은 [AWS CLI에서 명령 프롬프트 활성화 및 사용](cli-usage-parameters-prompting.md) 섹션을 참조하세요.

**JMESPath Terminal**  
JMESPath Terminal은 클라이언트 측 필터링에 사용되는 JMESPath 표현식을 실험하는 대화형 터미널 명령입니다. `jpterm` 명령을 사용하면 사용자가 입력할 때 터미널에 즉시 쿼리 결과가 표시됩니다. AWS CLI 출력을 터미널에 직접 파이핑하여 고급 쿼리 실험을 할 수 있습니다.  
다음 예제에서는 `aws ec2 describe-volumes` 출력을 JMESPath Terminal에 직접 파이핑합니다.  

```
$ aws ec2 describe-volumes | jpterm
```
JMESPath Terminal 및 설치 지침에 대한 자세한 내용은 *GitHub*의 [JMESPath Terminal](https://github.com/jmespath/jmespath.terminal)을 참조하세요.

**jq 유틸리티**  
`jq` 유틸리티는 클라이언트 측의 출력을 사용자가 원하는 출력 형식으로 변환하는 방법을 제공합니다. `jq` 및 설치 지침에 대한 자세한 내용은 *GitHub*의 [jq](https://stedolan.github.io/jq/)를 참조하세요.