

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

# Cassandra Go 클라이언트 드라이버를 사용하여 프로그래밍 방식으로 Amazon Keyspaces에 액세스
<a name="using_go_driver"></a>

이 섹션에서는 Go Cassandra 클라이언트 드라이버를 사용하여 Amazon Keyspaces에 접속하는 방법을 소개합니다. Amazon Keyspaces 리소스에 프로그래밍 방식으로 액세스할 수 있는 자격 증명을 사용자와 애플리케이션에 제공하려면 다음 중 하나를 수행할 수 있습니다.
+ 특정 AWS Identity and Access Management (IAM) 사용자와 연결된 서비스별 자격 증명을 생성합니다.
+ 보안을 강화하려면 모든 AWS 서비스에서 사용되는 IAM 보안 주체에 대한 IAM 액세스 키를 생성하는 것이 좋습니다. Cassandra 클라이언트 드라이버용 Amazon Keyspaces SigV4 인증 플러그인을 사용하면 사용자 이름 및 암호 대신 IAM 액세스 키를 사용하여 Amazon Keyspaces에 대한 호출을 인증할 수 있습니다. 자세한 내용은 [Amazon Keyspaces에 대한 AWS 자격 증명 생성 및 구성](access.credentials.md) 단원을 참조하십시오.

**Topics**
+ [시작하기 전 준비 사항](#using_go_driver.BeforeYouBegin)
+ [Apache Cassandra용 Gocql 드라이버와 서비스별 자격 증명을 사용하여 Amazon Keyspaces에 접속합니다.](#go_ssc)
+ [Apache Cassandra용 Go 드라이버와 SigV4 인증 플러그인을 사용하여 Amazon Keyspaces에 접속](#go_SigV4)

## 시작하기 전 준비 사항
<a name="using_go_driver.BeforeYouBegin"></a>

시작하기 전에 다음 작업을 수행해야 합니다.

Amazon Keyspaces에서는 클라이언트와의 연결을 보호하는 데 도움이 되는 전송 계층 보안(TLS)을 사용해야 합니다. TLS를 사용하여 Amazon Keyspace에 접속하려면 Amazon 디지털 인증서를 다운로드하고 TLS를 사용하도록 Go 드라이버를 구성해야 합니다.

 다음 디지털 인증서를 다운로드하고 파일을 로컬 또는 홈 디렉터리에 저장합니다.

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield 클래스 2 루트(선택 사항 - 이전 버전과의 호환성을 위해)

인증서를 다운로드하려면 다음 명령을 사용할 수 있습니다.

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**참고**  
Amazon Keyspaces는 이전에 Starfield Class 2 CA에 고정된 TLS 인증서를 사용했습니다. AWS 는 Amazon Trust Services(Amazon Root CA 1\$14)에 따라 발급된 인증서 AWS 리전 로 모두 마이그레이션하고 있습니다. CAs 이 전환 중에 Amazon Root CAs1\$14와 Starfield 루트를 모두 신뢰하도록 클라이언트를 구성하여 모든 리전에서 호환성을 보장합니다.

예제에서 다운로드한 모든 인증서를 *keyspaces-bundle.pem*이라는 이름과 함께 단일 `pem` 파일로 결합합니다. 다음 명령을 실행하여 이 작업을 수행할 수 있습니다. 파일의 경로를 기록해 둡니다. 나중에 필요합니다.

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## Apache Cassandra용 Gocql 드라이버와 서비스별 자격 증명을 사용하여 Amazon Keyspaces에 접속합니다.
<a name="go_ssc"></a>

1. 애플리케이션용 디렉터리를 생성합니다.

   ```
   mkdir ./gocqlexample
   ```

1. 새 디렉터리로 이동합니다.

   ```
   cd gocqlexample
   ```

1. 애플리케이션에 대한 파일을 생성합니다.

   ```
   touch cqlapp.go
   ```

1. Go 드라이버를 다운로드합니다.

   ```
   go get github.com/gocql/gocql
   ```

1. 다음 샘플 코드를 cqlapp.go 파일에 추가합니다.

   ```
   package main
   
   import (
   	    "fmt"
   	    "github.com/gocql/gocql"
   	    "log"
   )
   
   func main() {
   
       // add the Amazon Keyspaces service endpoint 
       cluster := gocql.NewCluster("cassandra.us-east-2.amazonaws.com")
       cluster.Port=9142
       // add your service specific credentials
       cluster.Authenticator = gocql.PasswordAuthenticator{
               Username: "ServiceUserName",
               Password: "ServicePassword"}
   
       // provide the path to the keyspaces-bundle.pem
       cluster.SslOpts = &gocql.SslOptions{
               CaPath: "path_to_file/keyspaces-bundle.pem",
               EnableHostVerification: false,            
        }
   
        // Override default Consistency to LocalQuorum
        cluster.Consistency = gocql.LocalQuorum
        cluster.DisableInitialHostLookup = false
   
        session, err := cluster.CreateSession()
        if err != nil {
               fmt.Println("err>", err)
        }
        defer session.Close()
   
        // run a sample query from the system keyspace
        var text string
        iter := session.Query("SELECT keyspace_name FROM system_schema.tables;").Iter()
        for iter.Scan(&text) {
               fmt.Println("keyspace_name:", text)
        }
        if err := iter.Close(); err != nil {
               log.Fatal(err)
        }
        session.Close()
   }
   ```

   사용 노트:

   1. 를 첫 번째 단계에서 저장된 결합된 인증서 파일의 경로`"path_to_file/keyspaces-bundle.pem"`로 바꿉니다.

   1. *ServiceUserName*과 *ServicePassword*는 [Amazon Keyspaces에 프로그래밍 방식으로 액세스하기 위한 서비스별 자격 증명 만들기](programmatic.credentials.ssc.md)에 대한 단계에 따라 서비스별 자격 증명을 생성할 때 얻은 사용자 이름 및 암호와 일치해야 합니다.

   1. 사용 가능한 엔드포인트 목록은 [Amazon Keyspaces의 서비스 엔드포인트](programmatic.endpoints.md) 섹션을 참조하세요.

1. 프로그램을 빌드합니다.

   ```
   go build cqlapp.go
   ```

1. 프로그램을 실행합니다.

   ```
   ./cqlapp
   ```

## Apache Cassandra용 Go 드라이버와 SigV4 인증 플러그인을 사용하여 Amazon Keyspaces에 접속
<a name="go_SigV4"></a>

다음 코드 샘플에서는 오픈 소스 Go 드라이버를 위한 SigV4 인증 플러그인을 사용하여 Amazon Keyspaces(Apache Cassandra용) 에 액세스하는 방법을 설명합니다.

아직 수행하지 않은 경우 [Amazon Keyspaces에 대한 AWS 자격 증명 생성 및 구성](access.credentials.md)의 단계에 따라 IAM 위탁자의 자격 증명을 생성합니다. 애플리케이션이 Lambda 또는 Amazon EC2 인스턴스에서 실행 중인 경우 애플리케이션은 인스턴스의 자격 증명을 자동으로 사용합니다. 이 자습서를 로컬에서 실행하려면 자격 증명을 로컬 환경 변수로 저장할 수 있습니다.

[GitHub 리포지토리](https://github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin)에서 Go SigV4 인증 플러그인을 애플리케이션에 추가합니다. 플러그인은 Cassandra용 오픈 소스 Go 드라이버 버전 1.2.x를 지원하며 AWS SDK for Go에 따라 다릅니다.

```
$ go mod init
$ go get github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin
```

이 코드 예제에서 Amazon Keyspaces 엔드포인트는 `Cluster` 클래스로 표현됩니다. 클러스터의 인증 속성에 대한 `AwsAuthenticator`을 통해 자격 증명이 생성됩니다.

```
package main

import (
        "fmt"
        "github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin/sigv4"
        "github.com/gocql/gocql"
        "log"
)

func main() {
    // configuring the cluster options
    cluster := gocql.NewCluster("cassandra.us-west-2.amazonaws.com")
    cluster.Port=9142
    
    // the authenticator uses the default credential chain to find AWS credentials
    cluster.Authenticator = sigv4.NewAwsAuthenticator()

    cluster.SslOpts = &gocql.SslOptions{

            CaPath: "path_to_file/keyspaces-bundle.pem",
            EnableHostVerification: false,
    }
    cluster.Consistency = gocql.LocalQuorum
    cluster.DisableInitialHostLookup = false
   
    session, err := cluster.CreateSession()
    if err != nil {
	    fmt.Println("err>", err)
	    return
    }
    defer session.Close()

    // doing the query
    var text string
    iter := session.Query("SELECT keyspace_name FROM system_schema.tables;").Iter()
    for iter.Scan(&text) {
	    fmt.Println("keyspace_name:", text)
    }
    if err := iter.Close(); err != nil {
	    log.Fatal(err)
    }
}
```

사용 노트:

1. 를 첫 번째 단계에서 저장된 인증서 파일의 경로`"path_to_file/keyspaces-bundle.pem"`로 바꿉니다.

1. 이 예제를 로컬에서 실행하려면 다음 변수를 환경 변수로 정의해야 합니다.
   + `AWS_ACCESS_KEY_ID`
   + `AWS_SECRET_ACCESS_KEY`
   + `AWS_DEFAULT_REGION`

1. 액세스 키를 코드 외부에 저장하는 경우의 모범 사례는 [프로그래밍 방식 액세스를 위한 액세스 키 저장](aws.credentials.manage.md) 섹션을 참조하세요.

1. 사용 가능한 엔드포인트 목록은 [Amazon Keyspaces의 서비스 엔드포인트](programmatic.endpoints.md) 섹션을 참조하세요.