

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# sam remote invoke를 사용하여 클라우드에서 테스트 소개
<a name="using-sam-cli-remote-invoke"></a>

 AWS Serverless Application Model 명령줄 인터페이스(AWS SAM CLI) `sam remote invoke` 명령을 사용하여에서 지원되는 AWS 리소스와 상호 작용합니다 AWS 클라우드. 다음 리소스를 간접 호출하기 위해 `sam remote invoke`를 사용할 수 있습니다.
+ **Amazon Kinesis Data Streams** - 데이터 레코드를 Kinesis Data Streams 애플리케이션으로 전송합니다.
+ **AWS Lambda** - 이벤트를 간접 호출하고 Lambda 함수로 전달합니다.
+ **Amazon Simple Queue Service (Amazon SQS)** – 메시지를 Amazon Simple Queue Service(Amazon SQS) 대기열에 전송합니다.
+ **AWS Step Functions** – Step Functions 상태 머신을 간접 호출하여 실행을 시작합니다.

에 대한 소개는 단원을 AWS SAM CLI참조하십시오. [란 무엇입니까 AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli) 

일반적인 개발 워크플로 중 `sam remote invoke`를 사용하는 예는 [5단계:에서 함수와 상호 작용 AWS 클라우드](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-remote-invoke) 섹션을 참조하세요.

**Topics**
+ [sam remote invoke 명령 사용](#using-sam-cli-remote-invoke-use)
+ [sam remote invoke 명령 옵션 사용](#using-sam-cli-remote-invoke-options)
+ [프로젝트 구성 파일을 구성합니다.](#using-sam-cli-remote-invoke-configure)
+ [예제](#using-sam-cli-remote-invoke-examples)
+ [관련 링크](#using-sam-cli-remote-invoke-links)

## 사전 조건
<a name="using-sam-cli-remote-invoke-prerequisites"></a>

`sam remote invoke`를 사용하려면 다음을 완료하여 AWS SAM CLI를 설치합니다.
+ [AWS SAM 사전 조건](prerequisites.md).
+ [AWS SAM CLI 설치](install-sam-cli.md).

또한 최신 버전의 로 업그레이드하는 것이 좋습니다 AWS SAM CLI. 자세한 내용은 [AWS SAMCLI업그레이드](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade) 섹션을 참조하세요.

`sam remote invoke`를 사용하기 전에 다음 사항에 대한 기본적인 이해를 하는 것이 좋습니다.
+ [AWS SAM CLI 구성](using-sam-cli-configure.md).
+ [에서 애플리케이션 생성 AWS SAM](using-sam-cli-init.md).
+ [를 사용한 빌드 소개 AWS SAM](using-sam-cli-build.md).
+ [를 사용한 배포 소개 AWS SAM](using-sam-cli-deploy.md).
+ [를 사용하여 sam sync에 동기화 소개 AWS 클라우드](using-sam-cli-sync.md).

## sam remote invoke 명령 사용
<a name="using-sam-cli-remote-invoke-use"></a>

이 명령을 사용하기 전에 리소스를 AWS 클라우드에 배포해야 합니다.

다음 명령 구조를 사용하고 프로젝트의 루트 디렉터리에서 실행합니다.

```
$ sam remote invoke <arguments> <options>
```

**참고**  
이 페이지에는 명령 프롬프트에서 제공되는 옵션이 표시됩니다. 명령 프롬프트에서 옵션을 전달하는 대신 프로젝트의 구성 파일에서 옵션을 구성할 수도 있습니다. 자세한 내용은 [프로젝트 설정 구성](using-sam-cli-configure.md#using-sam-cli-configure-project) 섹션을 참조하세요.

`sam remote invoke` 인수 및 옵션에 대한 설명은 [sam remote invoke](sam-cli-command-reference-remote-invoke.md) 섹션을 참조하세요.

### Kinesis Data Streams 사용
<a name="using-sam-cli-remote-invoke-use-kinesis"></a>

Kinesis Data Streams 애플리케이션에 데이터 레코드를 보낼 수 있습니다. AWS SAM CLI는 데이터 레코드를 전송하고 샤드 ID와 시퀀스 번호를 반환합니다. 다음은 예제입니다.

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event hello-world
	
	Putting record to Kinesis data stream KinesisStream                                                             
	Auto converting value 'hello-world' into JSON '"hello-world"'. If you don't want auto-conversion, please provide
	a JSON string as event                                                                                          
	{
	  "ShardId": "shardId-000000000000",
	  "SequenceNumber": "49646251411914806775980850790050483811301135051202232322"
	}%
```

**데이터 기록을 보내려면**

1. 리소스 ID 값을 Kinesis Data Streams 애플리케이션의 인수로 제공합니다. 자세한 내용은 [리소스 ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id)를 참조하세요.

1. 데이터 레코드를 이벤트로 제공하여 Kinesis Data Streams 애플리케이션에 전송합니다. `--event` 옵션을 사용하여 명령줄에서 이벤트를 제공하거나 `--event-file`을 사용하는 파일에서 이벤트를 제공할 수 있습니다. 이벤트를 제공하지 않으면가 AWS SAM CLI 빈 이벤트를 보냅니다.

### Lambda 함수와 함께 사용
<a name="using-sam-cli-remote-invoke-use-lambda"></a>

클라우드에서 Lambda 함수를 간접 호출하고 빈 이벤트를 전달하거나 명령줄 또는 파일에서 이벤트를 제공할 수 있습니다. 는 AWS SAM CLI Lambda 함수를 호출하고 응답을 반환합니다. 다음은 예제입니다.

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app

Invoking Lambda Function HelloWorldFunction                                       
START RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Version: $LATEST
END RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9
REPORT RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9  Duration: 6.62 ms       Billed Duration: 7 ms     Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 164.06 ms
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
```

**Lambda 함수를 간접 호출하기 위해**

1. 리소스 ID 값을 Lambda 함수에 대한 인수로 제공합니다. 자세한 내용은 [리소스 ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id)를 참조하세요.

1. Lambda 함수에 전송할 이벤트를 제공합니다. `--event` 옵션을 사용하여 명령줄에서 이벤트를 제공하거나 `--event-file`을 사용하는 파일에서 이벤트를 제공할 수 있습니다. 이벤트를 제공하지 않으면가 AWS SAM CLI 빈 이벤트를 보냅니다.

#### 응답 스트리밍으로 구성된 Lambda 함수
<a name="using-sam-cli-remote-invoke-invoke-stream"></a>

이 `sam remote invoke` 명령은 응답을 스트리밍하도록 구성된 Lambda 함수를 지원합니다. AWS SAM 템플릿의 `FunctionUrlConfig` 속성을 사용하여 응답을 스트리밍하도록 Lambda 함수를 구성할 수 있습니다. `sam remote invoke`를 사용하면 AWS SAMCLI가 Lambda 구성을 자동으로 감지하고 응답 스트리밍을 통해 간접 호출합니다.

예시는 [응답을 스트리밍하도록 Lambda 함수 구성](#using-sam-cli-remote-invoke-examples-lambda-stream) 섹션을 참조하세요.

#### 공유 가능한 테스트 이벤트를 클라우드의 Lambda 함수에 전달
<a name="using-sam-cli-remote-invoke-shareable"></a>

공유 가능한 테스트 이벤트는 동일한 AWS 계정계정의 다른 사용자와 공유할 수 있는 테스트 이벤트입니다. 자세히 알아보려면 *AWS Lambda 개발자 안내서*의 [공유 가능한 테스트 이벤트](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html#creating-shareable-events) 섹션을 참조하세요.

##### 공유 가능한 테스트 이벤트 액세스 및 관리
<a name="using-sam-cli-remote-invoke-shareable-access"></a>

`sam remote test-event` 명령을 사용하여 AWS SAM CLI 공유 가능한 테스트 이벤트에 액세스하고 관리할 수 있습니다. 예를 들면, 다음을 수행하기 위해 `sam remote test-event`를 사용할 수 있습니다.
+ Amazon EventBridge 스키마 레지스트리에서 공유 가능한 테스트 이벤트를 검색합니다.
+ 공유 가능한 테스트 이벤트를 로컬에서 수정하고 EventBridge 스키마 레지스트리에 업로드합니다.
+ EventBridge 스키마 레지스트리에서 공유 가능한 테스트 이벤트를 삭제합니다.

자세한 내용은 [sam remote test-event를 사용한 클라우드 테스트 소개](using-sam-cli-remote-test-event.md)를 참조하세요.

##### 공유 가능한 테스트 이벤트를 클라우드의 Lambda 함수에 전달
<a name="using-sam-cli-remote-invoke-shareable-pass"></a>

EventBridge 스키마 레지스트리에서 클라우드의 Lambda 함수로 공유 가능한 테스트 이벤트를 전달하려면 `--test-event-name` 옵션을 사용하고 공유 가능한 테스트 이벤트의 이름을 제공합니다. 다음은 예제입니다.

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --test-event-name demo-event
```

공유 가능한 테스트 이벤트를 로컬에 저장하는 경우 `--event-file` 옵션을 사용하여 로컬 테스트 이벤트의 파일 경로와 이름을 제공할 수 있습니다. 다음은 예제입니다.

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --event-file demo-event.json
```

### Amazon SQS에서 사용
<a name="using-sam-cli-remote-invoke-use-sqs"></a>

메시지를 Amazon SQS 대기열로 전송할 수 있습니다. 는 AWS SAM CLI 다음을 반환합니다.
+ 메시지 ID
+ 메시지 본문의 MD5
+ 응답 메타데이터

 다음은 예제입니다.

```
$ sam remote invoke MySqsQueue --stack-name sqs-example -event hello

Sending message to SQS queue MySqsQueue                                                                         
{
  "MD5OfMessageBody": "5d41402abc4b2a76b9719d911017c592",
  "MessageId": "05c7af65-9ae8-4014-ae28-809d6d8ec652"
}%
```

**메시지 전송**

1. Amazon SQS 대기열의 인수로 리소스 ID 값을 제공합니다. 자세한 내용은 [리소스 ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id)를 참조하세요.

1. Amazon SQS 대기열로 전송할 이벤트를 제공합니다. `--event` 옵션을 사용하여 명령줄에서 이벤트를 제공하거나 `--event-file`을 사용하는 파일에서 이벤트를 제공할 수 있습니다. 이벤트를 제공하지 않으면가 AWS SAM CLI 빈 이벤트를 보냅니다.

### Step Functions와 함께 사용
<a name="using-sam-cli-remote-invoke-use-sf"></a>

 Step Functions 상태 시스템 실행을 시작합니다. AWS SAM CLI는 상태 시스템 워크플로가 완료되고 실행의 마지막 단계의 출력이 반환될 때까지 기다립니다. 다음은 예제입니다.

```
$ sam remote invoke HelloWorldStateMachine --stack-name state-machine-example --event '{"is_developer": true}'

Invoking Step Function HelloWorldStateMachine                                                                   
"Hello Developer World"%
```

**상태 머신을 실행하려면**

1. Step Functions 상태 시스템의 인수로 리소스 ID 값을 제공합니다. 자세한 내용은 [리소스 ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id)를 참조하세요.

1. 상태 시스템에 전송할 이벤트를 제공합니다. `--event` 옵션을 사용하여 명령줄에서 이벤트를 제공하거나 `--event-file`을 사용하는 파일에서 이벤트를 제공할 수 있습니다. 이벤트를 제공하지 않으면가 AWS SAM CLI 빈 이벤트를 보냅니다.

## sam remote invoke 명령 옵션 사용
<a name="using-sam-cli-remote-invoke-options"></a>

이 섹션에서는 `sam remote invoke` 명령과 함께 사용할 수 있는 몇 가지 주요 옵션을 다룹니다. 옵션의 전체 목록은 [sam remote invoke](sam-cli-command-reference-remote-invoke.md) 섹션을 참조하세요.

### 리소스에 이벤트 전달
<a name="using-sam-cli-remote-invoke-options-event"></a>

다음 옵션을 사용하여 클라우드의 리소스에 이벤트를 전달할 수 있습니다.
+ `--event` - 명령줄에서 이벤트를 전달합니다.
+ `--event-file` - 파일에서 이벤트를 전달합니다.

#### Lambda 예제
<a name="using-sam-cli-remote-invoke-options-event-lambda-examples"></a>

**`--event`를 사용하여 명령줄에서 이벤트를 문자열 값으로 전달합니다.**

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --event '{"message": "hello!"}'

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: b992292d-1fac-4aa2-922a-c9dc5c6fceab Version: $LATEST
END RequestId: b992292d-1fac-4aa2-922a-c9dc5c6fceab
REPORT RequestId: b992292d-1fac-4aa2-922a-c9dc5c6fceab  Duration: 16.41 ms      Billed Duration: 17 ms  Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 185.96 ms
{"statusCode":200,"body":"{\"message\":\"hello!\"}"}%
```

**`--event-file`를 사용하여 파일에서 이벤트를 전달하고 파일 경로를 제공합니다.**

```
$ cat event.json
			
{"message": "hello from file"}%    
			
$ sam remote invoke HelloWorldFunction --stack-name sam-app --event-file event.json       

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: 3bc71f7d-153a-4b1e-8c9a-901d91b1bec9 Version: $LATEST
END RequestId: 3bc71f7d-153a-4b1e-8c9a-901d91b1bec9
REPORT RequestId: 3bc71f7d-153a-4b1e-8c9a-901d91b1bec9  Duration: 21.15 ms      Billed Duration: 22 ms  Memory Size: 128 MB     Max Memory Used: 67 MB
{"statusCode":200,"body":"{\"message\":\"hello from file\"}"}%
```

**`stdin`를 사용하여 이벤트를 전달합니다.**

```
$ cat event.json
			
{"message": "hello from file"}%    
                                                                       
$ cat event.json | sam remote invoke HelloWorldFunction --stack-name sam-app --event-file -

Reading event from stdin (you can also pass it from file with --event-file)                               
Invoking Lambda Function HelloWorldFunction                                                               
START RequestId: 85ecc902-8ad0-4a2b-a8c8-9bb4f65f5a7a Version: $LATEST
END RequestId: 85ecc902-8ad0-4a2b-a8c8-9bb4f65f5a7a
REPORT RequestId: 85ecc902-8ad0-4a2b-a8c8-9bb4f65f5a7a  Duration: 1.36 ms       Billed Duration: 2 ms   Memory Size: 128 MB       Max Memory Used: 67 MB
{"statusCode":200,"body":"{\"message\":\"hello from file\"}"}%
```

### AWS SAMCLI 응답 출력을 구성합니다.
<a name="using-sam-cli-remote-invoke-options-output"></a>

`sam remote invoke`를 사용하여 지원되는 리소스를 간접 호출하면 AWS SAMCLI는 다음을 포함하는 응답을 반환합니다.
+ **요청 메타데이터** - 요청과 관련된 메타데이터입니다. 여기에는 요청 ID 및 요청 시작 시간이 포함됩니다.
+ **리소스 응답** - 클라우드에서 간접 호출된 후 리소스가 보내는 응답입니다.

`--output` 옵션을 사용하여 출력 응답을 구성할 수 있습니다 AWS SAM CLI. 다음과 같은 값을 사용할 수 있습니다.
+ `json` - 메타데이터 및 리소스 응답이 JSON 구조로 반환됩니다. 응답에는 전체 SDK 출력이 포함됩니다.
+ `text` - 메타데이터가 텍스트 구조로 반환됩니다. 리소스 응답은 리소스의 출력 형식으로 반환됩니다.

다음은 `json` 출력의 예제입니다.

```
$ sam remote invoke --stack-name sam-app --output json

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
{
  "ResponseMetadata": {
    "RequestId": "3bdf9a30-776d-4a90-94a6-4cccc0fc7b41",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "date": "Mon, 19 Jun 2023 17:15:46 GMT",
      "content-type": "application/json",
      "content-length": "57",
      "connection": "keep-alive",
      "x-amzn-requestid": "3bdf9a30-776d-4a90-94a6-4cccc0fc7b41",
      "x-amzn-remapped-content-length": "0",
      "x-amz-executed-version": "$LATEST",
      "x-amz-log-result": "U1RBUlQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEKUkVQT1JUIFJlcXVlc3RJZDogM2JkZjlhMzAtNzc2ZC00YTkwLTk0YTYtNGNjY2MwZmM3YjQxCUR1cmF0aW9uOiA4LjIzIG1zCUJpbGxlZCBEdXJhdGlvbjogOSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjggTUIJCg==",
      "x-amzn-trace-id": "root=1-64908d42-17dab270273fcc6b527dd6b8;sampled=0;lineage=2301f8dc:0"
    },
    "RetryAttempts": 0
  },
  "StatusCode": 200,
  "LogResult": "U1RBUlQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEKUkVQT1JUIFJlcXVlc3RJZDogM2JkZjlhMzAtNzc2ZC00YTkwLTk0YTYtNGNjY2MwZmM3YjQxCUR1cmF0aW9uOiA4LjIzIG1zCUJpbGxlZCBEdXJhdGlvbjogOSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjggTUIJCg==",
  "ExecutedVersion": "$LATEST",
  "Payload": "{\"statusCode\":200,\"body\":\"{\\\"message\\\":\\\"hello world\\\"}\"}"
}%
```

`json` 출력을 지정하면 전체 응답이 `stdout`에 반환됩니다. 다음은 예제입니다.

```
$ sam remote invoke --stack-name sam-app --output json 1> stdout.log

Invoking Lambda Function HelloWorldFunction           
                                                                                                                                                                                                          
$ cat stdout.log
			
{
  "ResponseMetadata": {
    "RequestId": "d30d280f-8188-4372-bc94-ce0f1603b6bb",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "date": "Mon, 19 Jun 2023 17:35:56 GMT",
      "content-type": "application/json",
      "content-length": "57",
      "connection": "keep-alive",
      "x-amzn-requestid": "d30d280f-8188-4372-bc94-ce0f1603b6bb",
      "x-amzn-remapped-content-length": "0",
      "x-amz-executed-version": "$LATEST",
      "x-amz-log-result": "U1RBUlQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIKUkVQT1JUIFJlcXVlc3RJZDogZDMwZDI4MGYtODE4OC00MzcyLWJjOTQtY2UwZjE2MDNiNmJiCUR1cmF0aW9uOiA0LjE2IG1zCUJpbGxlZCBEdXJhdGlvbjogNSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjcgTUIJSW5pdCBEdXJhdGlvbjogMTU4LjM5IG1zCQo=",
      "x-amzn-trace-id": "root=1-649091fc-771473c7778689627a6122b7;sampled=0;lineage=2301f8dc:0"
    },
    "RetryAttempts": 0
  },
  "StatusCode": 200,
  "LogResult": "U1RBUlQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIKUkVQT1JUIFJlcXVlc3RJZDogZDMwZDI4MGYtODE4OC00MzcyLWJjOTQtY2UwZjE2MDNiNmJiCUR1cmF0aW9uOiA0LjE2IG1zCUJpbGxlZCBEdXJhdGlvbjogNSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjcgTUIJSW5pdCBEdXJhdGlvbjogMTU4LjM5IG1zCQo=",
  "ExecutedVersion": "$LATEST",
  "Payload": "{\"statusCode\":200,\"body\":\"{\\\"message\\\":\\\"hello world\\\"}\"}"
}%
```

다음은 `text` 출력의 예제입니다.

```
$ sam remote invoke --stack-name sam-app --output text

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: 4dbacc43-1ec6-47c2-982b-9dc4620144d6 Version: $LATEST
END RequestId: 4dbacc43-1ec6-47c2-982b-9dc4620144d6
REPORT RequestId: 4dbacc43-1ec6-47c2-982b-9dc4620144d6  Duration: 9.13 ms       Billed Duration: 10 ms  Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 165.50 ms
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
```

`text` 출력을 지정하면 Lambda 함수 런타임 출력(예: 로그)이 `stderr`로 반환됩니다. Lambda 함수 페이로드가 `stdout`로 반환됩니다. 다음은 예제입니다.

```
$ sam remote invoke --stack-name sam-app --output text 2> stderr.log

{"statusCode":200,"body":"{\"message\":\"hello world\"}"}% 
                                                                                                                                                                                                     
$ cat stderr.log

Invoking Lambda Function HelloWorldFunction
START RequestId: 82273c3b-aa3a-4d16-8f1c-1d2ad3ace891 Version: $LATEST
END RequestId: 82273c3b-aa3a-4d16-8f1c-1d2ad3ace891
REPORT RequestId: 82273c3b-aa3a-4d16-8f1c-1d2ad3ace891  Duration: 40.62 ms      Billed Duration: 41 ms  Memory Size: 128 MB     Max Memory Used: 68 MB

$ sam remote invoke --stack-name sam-app --output text 1> stdout.log
 
Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: 74acaa9f-5b80-4a5c-b3b8-ffaccb84cbbd Version: $LATEST
END RequestId: 74acaa9f-5b80-4a5c-b3b8-ffaccb84cbbd
REPORT RequestId: 74acaa9f-5b80-4a5c-b3b8-ffaccb84cbbd  Duration: 2.31 ms       Billed Duration: 3 ms   Memory Size: 128 MB     Max Memory Used: 67 MB

$ cat stdout.log

{"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
```

### Boto3 파라미터를 사용자 지정합니다.
<a name="using-sam-cli-remote-invoke-options-boto3"></a>

의 AWS SAM CLI 경우 `sam remote invoke`는 Python용 AWS SDK(Boto3)를 활용하여 클라우드의 리소스와 상호 작용합니다. `--parameter` 옵션을 사용하여 Boto3 파라미터를 사용자 지정할 수 있습니다. 사용자 지정할 수 있는 지원되는 파라미터 목록은 `--parameter` 섹션을 참조하세요.

#### 예제
<a name="using-sam-cli-remote-invoke-options-boto3-examples"></a>

**Lambda 함수를 간접 호출하여 파라미터 값을 검증하고 권한을 확인합니다.**

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --parameter InvocationType="DryRun"
```

**단일 명령으로 `--parameter` 옵션을 여러 번 사용하여 여러 파라미터를 제공합니다.**

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --parameter InvocationType="Event" --parameter LogType="None"
```

### 기타 옵션
<a name="using-sam-cli-remote-invoke-options-other"></a>

`sam remote invoke` 옵션의 전체 목록은 [sam remote invoke](sam-cli-command-reference-remote-invoke.md) 섹션을 참조하세요.

## 프로젝트 구성 파일을 구성합니다.
<a name="using-sam-cli-remote-invoke-configure"></a>

구성 파일에서 `sam remote invoke`를 구성하려면 테이블에서 `remote_invoke`를 사용합니다. 다음은 `sam remote invoke` 명령의 기본값을 구성하는 `samconfig.toml` 파일의 예입니다.

```
...
version =0.1

[default]
...
[default.remote_invoke.parameters]
stack_name = "cloud-app"
event = '{"message": "Hello!"}'
```

## 예제
<a name="using-sam-cli-remote-invoke-examples"></a>

사용의 기본 예제는 *AWS 컴퓨팅 블로그*의 [AWS SAM 원격을 사용하여 함수 테스트를 AWS Lambda](https://aws.amazon.com/blogs/compute/testing-aws-lambda-functions-with-aws-sam-remote-invoke/) `sam remote invoke`참조하세요.

### Kinesis Data Streams 예제
<a name="using-sam-cli-remote-invoke-examples-kinesis"></a>

#### 기본 예제
<a name="using-sam-cli-remote-invoke-examples-kinesis-basic"></a>

**파일에서 Kinesis Data Streams 애플리케이션으로 데이터 레코드를 전송합니다. 리소스 ID에 대한 ARN을 제공하여 Kinesis Data Streams 애플리케이션을 식별할 수 있습니다.**

```
$ sam remote invoke arn:aws:kinesis:us-west-2:01234567890:stream/kinesis-example-KinesisStream-BgnLcAey4xUQ --event-file event.json
```

**명령줄에 제공된 이벤트를 Kinesis Data Streams 애플리케이션으로 전송합니다.**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event hello-world

Putting record to Kinesis data stream KinesisStream                                                             
Auto converting value 'hello-world' into JSON '"hello-world"'. If you don't want auto-conversion, please provide
a JSON string as event                                                                                          
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980903986194508740483329854174920706"
}%
```

**Kinesis Data Streams 애플리케이션의 물리적 ID를 가져옵니다. 그런 다음 명령줄에서 이벤트를 제공합니다.**

```
$ sam list resources --stack-name kinesis-example --output json

[
  {
    "LogicalResourceId": "KinesisStream",
    "PhysicalResourceId": "kinesis-example-KinesisStream-ZgnLcQey4xUQ"
  }
]

$ sam remote invoke kinesis-example-KinesisStream-ZgnLcQey4xUQ --event hello

Putting record to Kinesis data stream KinesisStream                                                             
Auto converting value 'hello' into JSON '"hello"'. If you don't want auto-conversion, please provide a JSON     
string as event                                                                                                 
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980904340716841045751814812900261890"
}%
```

**명령줄에 JSON 문자열을 이벤트로 제공합니다.**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event '{"method": "GET", "body": ""}'                      

Putting record to Kinesis data stream KinesisStream                                                             
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980904492868617924990209230536441858"
}%
```

**Kinesis Data Streams 애플리케이션에 빈 이벤트를 전송합니다.**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example

Putting record to Kinesis data stream KinesisStream                                                             
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980904866469008589597168190416224258"
}%
```

**응답을 JSON 형식으로 반환합니다 AWS SAM CLI.**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event '{"hello": "world"}' --output json

Putting record to Kinesis data stream KinesisStream                                                             
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980905078409420803696667195489648642",
  "ResponseMetadata": {
    "RequestId": "ebbbd307-3e9f-4431-b67c-f0715e9e353e",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "ebbbd307-3e9f-4431-b67c-f0715e9e353e",
      "x-amz-id-2": "Q3yBcgTwtPaQTV26IKclbECmZikUYOzKY+CzcxA84ZHgCkc5T2N/ITWg6RPOQcWw8Gn0tNPcEJBEHyVVqboJAPgCritqsvCu",
      "date": "Thu, 09 Nov 2023 18:13:10 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "110"
    },
    "RetryAttempts": 0
  }
}%
```

**JSON 출력을 stdout으로 반환합니다.**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event '{"hello": "world"}' --output json 1> stdout.log

Putting record to Kinesis data stream KinesisStream                                                             

$ cat stdout.log
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980906397777867595039988349006774274",
  "ResponseMetadata": {
    "RequestId": "f4290006-d84b-b1cd-a9ee-28306eeb2939",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "f4290006-d84b-b1cd-a9ee-28306eeb2939",
      "x-amz-id-2": "npCqz+IBKpoL4sQ1ClbUmxuJlbeA24Fx1UgpIrS6mm2NoIeV2qdZSN5AhNurdssykXajBrXaC9anMhj2eG/h7Hnbf+bPuotU",
      "date": "Thu, 09 Nov 2023 18:33:26 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "110"
    },
    "RetryAttempts": 0
  }
}%
```

### Lambda 예제
<a name="using-sam-cli-remote-invoke-examples-lambda"></a>

#### 기본 예제
<a name="using-sam-cli-remote-invoke-examples-lambda-basic"></a>

**ARN을 리소스 ID로 제공하여 Lambda 함수를 간접 호출합니다.**

```
$ sam remote invoke arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-ohRFEn2RuAvp
```

**논리적 ID를 리소스 ID로 제공하여 Lambda 함수를 간접 호출합니다.**

또한 `--stack-name` 옵션을 사용하여 CloudFormation 스택 이름을 제공해야 합니다. 다음은 예제입니다.

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app
```

애플리케이션에 단일 Lambda 함수가 포함된 경우 해당 함수의 논리적 ID를 지정하지 않아도 됩니다. `--stack-name` 옵션만 제공할 수 있습니다. 다음은 예제입니다.

```
$ sam remote invoke --stack-name sam-app
```

**물리적 ID를 리소스 ID로 제공하여 Lambda 함수를 간접 호출합니다.**

를 사용하여 배포할 때 물리적 ID가 생성됩니다 CloudFormation.

```
$ sam remote invoke sam-app-HelloWorldFunction-TZvxQRFNv0k4
```

**하위 스택의 Lambda 함수를 간접 호출합니다.**

이 예제에서 애플리케이션에는 다음과 같은 디렉터리 구조를 포함합니다.

```
lambda-example
├── childstack
│   ├── function
│   │   ├── __init__.py
│   │   ├── app.py
│   │   └── requirements.txt
│   └── template.yaml
├── events
│   └── event.json
├── samconfig.toml
└── template.yaml
```

`childstack`에 대한 Lambda 함수를 간접 호출하기 위해 다음을 실행합니다.

```
$ sam remote invoke ChildStack/HelloWorldFunction --stack-name lambda-example

Invoking Lambda Function HelloWorldFunction                                                                     
START RequestId: 207a864b-e67c-4307-8478-365b004d4bcd Version: $LATEST
END RequestId: 207a864b-e67c-4307-8478-365b004d4bcd
REPORT RequestId: 207a864b-e67c-4307-8478-365b004d4bcd  Duration: 1.27 ms       Billed Duration: 2 ms   Memory Size: 128 MB     Max Memory Used: 36 MB  Init Duration: 111.07 ms
{"statusCode": 200, "body": "{\"message\": \"Hello\", \"received_event\": {}}"}%
```

#### 응답을 스트리밍하도록 Lambda 함수 구성
<a name="using-sam-cli-remote-invoke-examples-lambda-stream"></a>

이 예제에서는 AWS SAMCLI를 사용하여 응답을 스트리밍하도록 구성된 Lambda 함수를 포함하는 새로운 서버리스 애플리케이션을 초기화합니다. 애플리케이션을에 배포 AWS 클라우드 하고 `sam remote invoke`를 사용하여 클라우드에서 함수와 상호 작용합니다.

먼저 `sam init` 명령을 실행하여 새 서버리스 애플리케이션을 생성합니다. **Lambda 응답 스트리밍** 빠른 시작 템플릿을 선택하고 애플리케이션 이름을 **lambda-streaming-nodejs-app**으로 지정합니다.

```
$ sam init
	
	You can preselect a particular runtime or package type when using the `sam init` experience.
	Call `sam init --help` to learn more.
	
	Which template source would you like to use?
	        1 - AWS Quick Start Templates
	        2 - Custom Template Location
	Choice: 1
	
	Choose an AWS Quick Start application template
	        1 - Hello World Example
	        ...
	        9 - Lambda Response Streaming
	        ...
	        15 - Machine Learning
	Template: 9
	
	Which runtime would you like to use?
	        1 - go (provided.al2)
	        2 - nodejs18.x
	        3 - nodejs16.x
	Runtime: 2
	
	Based on your selections, the only Package type available is Zip.
	We will proceed to selecting the Package type as Zip.
	
	Based on your selections, the only dependency manager available is npm.
	We will proceed copying the template using npm.
	
	Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER
	
	Would you like to enable monitoring using CloudWatch Application Insights?
	For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER
	
	Project name [sam-app]: lambda-streaming-nodejs-app
	
	    -----------------------
	    Generating application:
	    -----------------------
	    Name: lambda-streaming-nodejs-app
	    Runtime: nodejs18.x
	    Architectures: x86_64
	    Dependency Manager: npm
	    Application Template: response-streaming
	    Output Directory: .
	    Configuration file: lambda-streaming-nodejs-app/samconfig.toml
	    
	    Next steps can be found in the README file at lambda-streaming-nodejs-app/README.md
	        
	
	Commands you can use next
	=========================
	[*] Create pipeline: cd lambda-streaming-nodejs-app && sam pipeline init --bootstrap
	[*] Validate SAM template: cd lambda-streaming-nodejs-app && sam validate
	[*] Test Function in the Cloud: cd lambda-streaming-nodejs-app && sam sync --stack-name {stack-name} --watch
```

는 AWS SAM CLI 다음 구조로 프로젝트를 생성합니다.

```
lambda-streaming-nodejs-app
	├── README.md
	├── __tests__
	│   └── unit
	│       └── index.test.js
	├── package.json
	├── samconfig.toml
	├── src
	│   └── index.js
	└── template.yaml
```

다음은 Lambda 함수 코드의 예제입니다.

```
exports.handler = awslambda.streamifyResponse(
	  async (event, responseStream, context) => {
	    const httpResponseMetadata = {
	      statusCode: 200,
	      headers: {
	        "Content-Type": "text/html",
	        "X-Custom-Header": "Example-Custom-Header"
	      }
	    };
	
	    responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata);
	    // It's recommended to use a `pipeline` over the `write` method for more complex use cases.
	    // Learn more: https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html
	    responseStream.write("<html>");
	    responseStream.write("<p>First write!</p>");
	
	    responseStream.write("<h1>Streaming h1</h1>");
	    await new Promise(r => setTimeout(r, 1000));
	    responseStream.write("<h2>Streaming h2</h2>");
	    await new Promise(r => setTimeout(r, 1000));
	    responseStream.write("<h3>Streaming h3</h3>");
	    await new Promise(r => setTimeout(r, 1000));
	
	    // Long strings will be streamed
	    const loremIpsum1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae mi tincidunt tellus ultricies dignissim id et diam. Morbi pharetra eu nisi et finibus. Vivamus diam nulla, vulputate et nisl cursus, pellentesque vehicula libero. Cras imperdiet lorem ante, non posuere dolor sollicitudin a. Vestibulum ipsum lacus, blandit nec augue id, lobortis dictum urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi auctor orci eget tellus aliquam, non maximus massa porta. In diam ante, pulvinar aliquam nisl non, elementum hendrerit sapien. Vestibulum massa nunc, mattis non congue vitae, placerat in quam. Nam vulputate lectus metus, et dignissim erat varius a.";
	    responseStream.write(`<p>${loremIpsum1}</p>`);
	    await new Promise(r => setTimeout(r, 1000));
	
	    responseStream.write("<p>DONE!</p>");
	    responseStream.write("</html>");
	    responseStream.end();
	  }
	);
```

다음은 `template.yaml` 파일의 예제입니다. Lambda 함수의 응답 스트리밍은 `FunctionUrlConfig` 속성을 사용하여 구성됩니다.

```
AWSTemplateFormatVersion: '2010-09-09'
	Transform: AWS::Serverless-2016-10-31
	
	Description: >
	  Sample SAM Template for lambda-streaming-nodejs-app
	  
	Resources:
	  StreamingFunction:
	    Type: AWS::Serverless::Function
	    Properties:
	      CodeUri: src/
	      Handler: index.handler
	      Runtime: nodejs18.x
	      Architectures:
	        - x86_64
	      Timeout: 10
	      FunctionUrlConfig:
	        AuthType: AWS_IAM
	        InvokeMode: RESPONSE_STREAM
	
	Outputs:
	  StreamingFunction:
	    Description: "Streaming Lambda Function ARN"
	    Value: !GetAtt StreamingFunction.Arn
	  StreamingFunctionURL:
	    Description: "Streaming Lambda Function URL"
	    Value: !GetAtt StreamingFunctionUrl.FunctionUrl
```

일반적으로 `sam build` 및 `sam deploy --guided`를 사용하여 프로덕션 애플리케이션을 빌드하고 배포할 수 있습니다. 이 예제에서는 개발 환경을 가정하고 `sam sync` 명령을 사용하여 애플리케이션을 빌드하고 배포해 보겠습니다.

**참고**  
이 `sam sync` 명령은 개발 환경에 권장됩니다. 자세한 내용은 [를 사용하여 sam sync에 동기화 소개 AWS 클라우드](using-sam-cli-sync.md)를 참조하세요.

`sam sync`를 실행하기 전에 `samconfig.toml` 파일에 프로젝트가 올바르게 구성되어 있는지 확인합니다. 가장 중요한 것은 `stack_name` 및 `watch`의 값을 검증하는 것입니다. 구성 파일에 이러한 값을 지정하면 명령줄에서 값을 제공할 필요가 없습니다.

```
version = 0.1
	
	[default]
	[default.global.parameters]
	stack_name = "lambda-streaming-nodejs-app"
	
	[default.build.parameters]
	cached = true
	parallel = true
	
	[default.validate.parameters]
	lint = true
	
	[default.deploy.parameters]
	capabilities = "CAPABILITY_IAM"
	confirm_changeset = true
	resolve_s3 = true
	s3_prefix = "lambda-streaming-nodejs-app"
	region = "us-west-2"
	image_repositories = []
	
	[default.package.parameters]
	resolve_s3 = true
	
	[default.sync.parameters]
	watch = true
	
	[default.local_start_api.parameters]
	warm_containers = "EAGER"
	
	[default.local_start_lambda.parameters]
	warm_containers = "EAGER"
```

다음으로 `sam sync`를 실행하여 애플리케이션을 빌드하고 배포합니다. `--watch` 옵션이 구성 파일에 구성되어 있으므로 AWS SAMCLI는 애플리케이션을 빌드하고, 애플리케이션을 배포하고, 변경 사항을 확인합니다.

```
$ sam sync
	
	The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code   
	without                                                                                                   
	performing a CloudFormation deployment. This will cause drift in your CloudFormation stack.               
	**The sync command should only be used against a development stack**.                                     
	                                                                                                          
	Queued infra sync. Waiting for in progress code syncs to complete...                                      
	Starting infra sync.                                                                                      
	Building codeuri:                                                                                         
	/Users/.../lambda-streaming-nodejs-app/src runtime: nodejs18.x metadata: {} architecture: x86_64 functions: StreamingFunction  
	package.json file not found. Continuing the build without dependencies.                                   
	Running NodejsNpmBuilder:CopySource                                                                       
	
	Build Succeeded
	
	Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpavrzdhgp.
	Execute the following command to deploy the packaged template
	sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpavrzdhgp --stack-name <YOUR STACK NAME>
	
	
	        Deploying with following values
	        ===============================
	        Stack name                   : lambda-streaming-nodejs-app
	        Region                       : us-west-2
	        Disable rollback             : False
	        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
	        Capabilities                 : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
	        Parameter overrides          : {}
	        Signing Profiles             : null
	
	Initiating deployment
	=====================
	
	
	2023-06-20 12:11:16 - Waiting for stack create/update to complete
	
	CloudFormation events from stack operations (refresh every 0.5 seconds)
	-----------------------------------------------------------------------------------------------------
	ResourceStatus            ResourceType              LogicalResourceId         ResourceStatusReason    
	-----------------------------------------------------------------------------------------------------
	CREATE_IN_PROGRESS        AWS::CloudFormation::St   lambda-streaming-         Transformation          
	                          ack                       nodejs-app                succeeded               
	CREATE_IN_PROGRESS        AWS::IAM::Role            StreamingFunctionRole     -                       
	CREATE_IN_PROGRESS        AWS::CloudFormation::St   AwsSamAutoDependencyLay   -                       
	                          ack                       erNestedStack                                     
	CREATE_IN_PROGRESS        AWS::IAM::Role            StreamingFunctionRole     Resource creation       
	                                                                              Initiated               
	CREATE_IN_PROGRESS        AWS::CloudFormation::St   AwsSamAutoDependencyLay   Resource creation       
	                          ack                       erNestedStack             Initiated               
	CREATE_COMPLETE           AWS::IAM::Role            StreamingFunctionRole     -                       
	CREATE_COMPLETE           AWS::CloudFormation::St   AwsSamAutoDependencyLay   -                       
	                          ack                       erNestedStack                                     
	CREATE_IN_PROGRESS        AWS::Lambda::Function     StreamingFunction         -                       
	CREATE_IN_PROGRESS        AWS::Lambda::Function     StreamingFunction         Resource creation       
	                                                                              Initiated               
	CREATE_COMPLETE           AWS::Lambda::Function     StreamingFunction         -                       
	CREATE_IN_PROGRESS        AWS::Lambda::Url          StreamingFunctionUrl      -                       
	CREATE_IN_PROGRESS        AWS::Lambda::Url          StreamingFunctionUrl      Resource creation       
	                                                                              Initiated               
	CREATE_COMPLETE           AWS::Lambda::Url          StreamingFunctionUrl      -                       
	CREATE_COMPLETE           AWS::CloudFormation::St   lambda-streaming-         -                       
	                          ack                       nodejs-app                                        
	-----------------------------------------------------------------------------------------------------
	
	CloudFormation outputs from deployed stack
	-------------------------------------------------------------------------------------------------------
	Outputs                                                                                               
	-------------------------------------------------------------------------------------------------------
	Key                 StreamingFunction                                                                 
	Description         Streaming Lambda Function ARN                                                     
	Value               arn:aws:lambda:us-west-2:012345678910:function:lambda-streaming-nodejs-app-       
	StreamingFunction-gUmhO833A0vZ                                                                        
	
	Key                 StreamingFunctionURL                                                              
	Description         Streaming Lambda Function URL                                                     
	Value               https://wxgkcc2dyntgtrwhf2dgdcvylu0rnnof.lambda-url.us-west-2.on.aws/             
	-------------------------------------------------------------------------------------------------------
	
	                                                                                                          
	Stack creation succeeded. Sync infra completed.                                                           
	                                                                                                          
	Infra sync completed.
```

이제 함수가 클라우드에 배포되었으므로 `sam remote invoke`를 사용하여 함수와 상호 작용할 수 있습니다. AWS SAMCLI는 함수가 응답 스트리밍을 위해 구성되었음을 자동으로 감지하고 즉시 함수의 스트리밍된 응답을 실시간으로 출력하기 시작합니다.

```
$ sam remote invoke StreamingFunction
	
	Invoking Lambda Function StreamingFunction                                              
	{"statusCode":200,"headers":{"Content-Type":"text/html","X-Custom-Header":"Example-Custom-Header"}}<html><p>First write!</p><h1>Streaming h1</h1><h2>Streaming h2</h2><h3>Streaming h3</h3><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae mi tincidunt tellus ultricies dignissim id et diam. Morbi pharetra eu nisi et finibus. Vivamus diam nulla, vulputate et nisl cursus, pellentesque vehicula libero. Cras imperdiet lorem ante, non posuere dolor sollicitudin a. Vestibulum ipsum lacus, blandit nec augue id, lobortis dictum urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi auctor orci eget tellus aliquam, non maximus massa porta. In diam ante, pulvinar aliquam nisl non, elementum hendrerit sapien. Vestibulum massa nunc, mattis non congue vitae, placerat in quam. Nam vulputate lectus metus, et dignissim erat varius a.</p><p>DONE!</p></html>START RequestId: 1e4cdf04-60de-4769-b3a2-c1481982deb4 Version: $LATEST
	END RequestId: 1e4cdf04-60de-4769-b3a2-c1481982deb4
	REPORT RequestId: 1e4cdf04-60de-4769-b3a2-c1481982deb4  Duration: 4088.66 ms    Billed Duration: 4089 ms        Memory Size: 128 MB     Max Memory Used: 68 MB  Init Duration: 168.45 ms
```

함수 코드를 수정하면 AWS SAMCLI는 변경 사항을 즉시 감지하고 즉시 배포합니다. 다음은 함수 코드를 변경한 후의 AWS SAMCLI 출력의 예입니다.

```
Syncing Lambda Function StreamingFunction...                                             
	Building codeuri:                                                                        
	/Users/.../lambda-streaming-nodejs-app/src runtime: nodejs18.x metadata: {} architecture:    
	x86_64 functions: StreamingFunction                                                      
	package.json file not found. Continuing the build without dependencies.                  
	Running NodejsNpmBuilder:CopySource                                                      
	Finished syncing Lambda Function StreamingFunction.                                      
	Syncing Layer StreamingFunctione9cfe924DepLayer...                                       
	SyncFlow [Layer StreamingFunctione9cfe924DepLayer]: Skipping resource update as the      
	content didn't change                                                                    
	Finished syncing Layer StreamingFunctione9cfe924DepLayer.
```

이제 다시 `sam remote invoke`를 사용하여 클라우드에서 함수와 상호 작용하고 변경 사항을 테스트할 수 있습니다.

### SQS 예제
<a name="using-sam-cli-remote-invoke-examples-sqs"></a>

#### 기본 예제
<a name="using-sam-cli-remote-invoke-examples-sqs-basic"></a>

**ARN을 리소스 ID로 제공하여 Amazon SQS 대기열을 간접 호출합니다.**

```
$ sam remote invoke arn:aws:sqs:us-west-2:01234567890:sqs-example-4DonhBsjsW1b --event '{"hello": "world"}' --output json

Sending message to SQS queue MySqsQueue                                                                         
{
  "MD5OfMessageBody": "49dfdd54b01cbcd2d2ab5e9e5ee6b9b9",
  "MessageId": "4f464cdd-15ef-4b57-bd72-3ad225d80adc",
  "ResponseMetadata": {
    "RequestId": "95d39377-8323-5ef0-9223-ceb198bd09bd",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "95d39377-8323-5ef0-9223-ceb198bd09bd",
      "date": "Wed, 08 Nov 2023 23:27:26 GMT",
      "content-type": "application/x-amz-json-1.0",
      "content-length": "106",
      "connection": "keep-alive"
    },
    "RetryAttempts": 0
  }
}%
```

### Step Functions 예제
<a name="using-sam-cli-remote-invoke-examples-sf"></a>

#### 기본 예제
<a name="using-sam-cli-remote-invoke-examples-sf-basic"></a>

**물리적 ID를 리소스 ID로 제공하여 상태 시스템을 간접 호출합니다.**

먼저 `sam list resources`를 사용하여 물리적 ID를 가져옵니다.

```
$ sam list resources --stack-name state-machine-example --output json

[
  {
    "LogicalResourceId": "HelloWorldStateMachine",
    "PhysicalResourceId": "arn:aws:states:us-west-2:513423067560:stateMachine:HelloWorldStateMachine-z69tFEUx0F66"
  },
  {
    "LogicalResourceId": "HelloWorldStateMachineRole",
    "PhysicalResourceId": "simple-state-machine-HelloWorldStateMachineRole-PduA0BDGuFXw"
  }
]
```

다음으로 물리적 ID를 리소스 ID로 사용하여 상태 시스템을 간접 호출합니다. 명령줄에서 `--event` 옵션을 사용하여 이벤트를 전달합니다.

```
$ sam remote invoke arn:aws:states:us-west-2:01234567890:stateMachine:HelloWorldStateMachine-z69tFEUx0F66 --event '{"is_developer": true}'

Invoking Step Function arn:aws:states:us-west-2:01234567890:stateMachine:HelloWorldStateMachine-z69tFEUx0F66   
"Hello Developer World"%
```

**빈 이벤트를 전달하여 상태 시스템을 간접 호출합니다.**

```
$ sam remote invoke HelloWorldStateMachine --stack-name state-machine-example

Invoking Step Function HelloWorldStateMachine                                                                   
"Hello World"%
```

## 관련 링크
<a name="using-sam-cli-remote-invoke-links"></a>

`sam remote invoke` 및 사용과 관련된 설명서는 다음을 AWS SAM CLI참조하세요.
+ [sam remote invoke](sam-cli-command-reference-remote-invoke.md)
+ [AWS SAMCLI 문제 해결](sam-cli-troubleshooting.md)