로컬 머신에서 Terraform과 Yandex Cloud를 설정하여 클라우드에 연결하세요.

Terraform

요약: Linux에서는 일반적으로 Terraform, **Yandex Cloud CLI (yc)**를 설치하고, 초기화를 거친 후 Terraform에 인증 정보(IAM 토큰 또는 서비스 계정 키)를 설정합니다.

1. Terraform

공식 바이너리로 설치 (일반적 방법):

# amd64 예시; 필요에 따라 버전과 아키텍처를 변경하세요
TERRAFORM_VERSION=1.9.8
wget "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
unzip "terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
sudo mv terraform /usr/local/bin/
terraform version

또는 패키지 매니저를 이용 (Ubuntu/Debian 사용자이고 HashiCorp 저장소가 설정되어 있다면 — 문서에서 설명한 배포판 설정과 동일하게).

2. Yandex Cloud CLI (yc)

curl -sSL https://storage.yandexcloud.net/yandexcloud-yc/install.sh | bash
exec -l $SHELL   # 또는 새 터미널을 열어주세요
yc version

3. 클라우드에 대한 프로필 및 접근 설정

처음 사용 시에는 인터랙티브 모드가 편리합니다:

yc init

다음 정보가 필요합니다:

  • 프로필 이름 (기본값(default)을 선택하거나 새 프로필을 생성)
  • OAuth 토큰 (링크를 제공하여 어떻게 얻을 수 있는지 안내)
  • 클라우드 이름 (요금 청구 대상 클라우드를 결정하는 데 사용됨)
  • 폴더 이름 (선택 제안)
  • 기본 컴퓨팅 존 (예: ru-central1-a...k 중에서 선택)

이후 yc는 프로필을 저장합니다. 확인 방법:

yc config list
yc resource-manager cloud list
yc resource-manager folder list

4. Terraform 변수 설정 (Yandex 프로바이더)

프로바이더는 표준 환경 변수를 읽습니다. 최소한 식별자인증 방법 중 하나가 필요합니다.

방법 A — 사용자 계정 (Yandex CLI에서 얻은 IAM 토큰):

export YC_TOKEN=$(yc iam create-token)
export YC_CLOUD_ID="<your-cloud-id>"
export YC_FOLDER_ID="<your-folder-id>"

IAM 토큰은 임시입니다. 장기 사용을 위해 서비스 계정이 더 편리합니다.

방법 B — 서비스 계정 (JSON 키 파일):

export YC_SERVICE_ACCOUNT_KEY_FILE="/absolute/path/to/key.json"
export YC_CLOUD_ID="<cloud-id>"
```YC_FOLDER_ID="<folder-id>"

(프로바이더에서 파일 키 변수 이름은 이와 같은 형태입니다. Yandex 프로바이더 문서를 참조하세요.)

5. Terraform 구성 폴더 내에서

cd /path/to/your/terraform/project
terraform init
terraform plan

실용 팁:

  • YC_TOKEN=$(yc iam create-token)은 주기적으로 갱신해야 합니다.
  • CI 및 “항상 작동” 시나리오에서는 서비스 계정을 생성하고, 해당 계정에 필요한 역할을 부여한 후 정적 키를 JSON 형태로 생성하는 것이 일반적입니다.
  • cloud_idfolder_idyc resource-manager cloud list / folder list 명령어의 출력 또는 Yandex Cloud 콘솔에서 확인할 수 있습니다.

버킷

기존 버킷(https://console.yandex.cloud/folders/b1g/storage/buckets/bucket)에 대한 access_keysecret_key는 어떻게 얻을 수 있나요?

Yandex Object Storage에서 버킷은 자체적으로 access_key / secret_key를 제공하지 않습니다. 이러한 키는 서비스 계정(또는 이미 생성된 키를 사용)에 부여됩니다. 버킷은 IAM 권한을 통해 버킷 자체 또는 폴더 수준에서 접근 권한을 부여받습니다.

콘솔을 통한 방법

  1. b1g 폴더 → Object Storagebucket 버킷으로 이동합니다.
  2. 해당 버킷에 접근 권한이 필요한 서비스 계정이 있는지 확인하거나 새로 생성합니다.
  3. 버킷에서 접근 권한 → 해당 서비스 계정에 storage.editor 같은 역할(또는 이미 설정된 Object Storage 접근 역할)을 부여합니다.
  4. 서비스 계정필요한 계정정적 접근 키 또는 접근 키 탭 → 새로운 키 생성.
  5. 생성된 키 ID비밀번호를 저장합니다. 비밀번호는 한 번만 표시됩니다.

키 ID = S3 클라이언트에서 일반적으로 access_key 또는 AWS_ACCESS_KEY_ID로 사용됨, 비밀번호 = secret_key 또는 AWS_SECRET_ACCESS_KEY.

CLI (yc)를 통한 방법

폴더 내 서비스 계정 목록:

yc iam service-account list --folder-id b1g

필요한 서비스 계정 ID를 입력하여 정적 키 생성:

yc iam access-key create --service-account-id <SERVICE_ACCOUNT_ID>

응답에는 key_idsecret이 포함됩니다. 이 두 값이 S3 API를 위한 키 쌍입니다.

버킷에 대한 권한은 미리 부여하는 것이 좋습니다(버킷 또는 폴더 수준의 역할). 예: storage.editor 역할을 버킷에 부여하거나, 조직 내에서 일반적으로 폴더 수준 역할을 사용하는 경우가 많습니다.

주의사항

  • 이미 생성된 비밀번호는 다시 볼 수 없습니다. 필요 시 새로운 키를 생성하고, 필요에 따라 기존 키를 취소해야 합니다.
  • Terraform state를 S3에 저장할 때는 동일한 키를 사용하며, endpoint는 https://storage.yandexcloud.net이고, 지역은 ru-central1 (또는 사용자의 지역)입니다.

Yandex Cloud 공식 문서에서 정적 접근 키 및 Object Storage S3 API 접근 방식에 대한 설명이 제공됩니다.


로컬 저장소

저장소 폴더로 이동하여, 서비스 계정 키를 사용해 Terraform 저장소를 초기화합니다:

terraform init \
  -backend-config="access_key=<key_id>" \
  -backend-config="secret_key=<secret>"

이렇게 하면 클라우드 폴더와 로컬 저장소를 연결합니다.


Hashicorp 제약 사항

만약 다음 메시지를 받는다면:terraform init -backend-config=“access_key=YCA” -backend-config=“secret_key=YCN”
후크백 초기화 중…

“aws” 백엔드 구성이 성공적으로 완료되었습니다! 백엔드 설정이 변경되지 않는 한 Terraform은 자동으로 이 백엔드를 사용합니다.
프로바이더 플러그인 초기화 중…

  • yandex-cloud/yandex 최신 버전 찾기…
  • hashicorp/null “~> 3.2” 버전 찾기…
  • hashicorp/local 최신 버전 찾기…
  • yandex-cloud/yandex v0.200.0 설치 중…
  • yandex-cloud/yandex v0.200.0 설치 완료 (자체 서명, 키 ID: E40F590B50BB8E40)
    파트너 및 커뮤니티 프로바이더는 개발자들이 서명합니다.
    프로바이더 서명에 대해 더 알고 싶으시면 여기를 참조하세요:
    Plugin signatures | Terraform | HashiCorp Developer

    │ 오류: 사용 가능한 프로바이더 패키지 조회 실패

    │ hashicorp/null 프로바이더의 사용 가능한 버전 목록을 가져오지 못했습니다: 프로바이더
    │ 레지스트리 registry.terraform.io에 hashicorp/null이라는 이름의 프로바이더가 없습니다.

    │ 모든 모듈은 외부 사용자가 모듈을 사용할 때 정확한 프로바이더를 받도록 required_providers를 명시해야 합니다. 현재 hashicorp/null에 의존하는 모듈을 확인하려면 다음 명령어를 실행하세요:
    │ terraform providers


    │ 오류: 사용 가능한 프로바이더 패키지 조회 실패

    │ hashicorp/local 프로바이더의 사용 가능한 버전 목록을 가져오지 못했습니다: 프로바이더
    │ 레지스트리 registry.terraform.io에 hashicorp/local이라는 이름의 프로바이더가 없습니다.

    │ 모든 모듈은 외부 사용자가 모듈을 사용할 때 정확한 프로바이더를 받도록 required_providers를 명시해야 합니다. 현재 hashicorp/local에 의존하는 모듈을 확인하려면 다음 명령어를 실행하세요:
    │ terraform providers
아래 단계를 수행하세요.

### 무엇이 일어났는가

`yandex-cloud/yandex`는 정상적으로 설치되었지만, **`hashicorp/null`** 및 **`hashicorp/local`**은 설치되지 않았습니다. 이는 **`registry.terraform.io`가 접근 불가능**할 때(네트워크, DNS, 정책 문제 등) 또는 잘못된 응답을 보내는 경우에 발생합니다.

### 당신이 해야 할 일

1. **Yandex Cloud 미러 설정** — 홈 디렉토리에 Terraform 설정 파일을 복사합니다. (저장소에서 복사한 `terraform.rc.example` 파일을 사용):

   ```bash
   cp ~/terraform.rc.example ~/.terraformrc

이 설정 파일에서는 registry.terraform.io/*/*에 대해 https://terraform-mirror.yandexcloud.net/를 지정합니다. (Yandex Cloud 문서 참조: Верификация)

  1. 다시 실행:

    cd ~/yc-cloud
    terraform init
    
  2. 코드에서 provider.tflocal 프로바이더를 명시적으로 추가했습니다 (이전에는 null만 존재했음). 이로 인해 버전이 한 곳에서 고정됩니다.

직접 접근이 필요한 경우: VPN/프록시 설정을 확인하고 curl -sI https://registry.terraform.io 명령어가 정상적으로 실행되는지 확인하세요.```bash
$ terraform init -backend-config=“access_key=YCA” -backend-config=“secret_key=YCN”
Initializing the backend…
Initializing provider plugins…

  • Finding hashicorp/null versions matching “~> 3.2”…
  • Finding hashicorp/local versions matching “~> 2.5”…
  • Finding latest version of yandex-cloud/yandex…
  • Installing yandex-cloud/yandex v0.200.0…
  • Installed yandex-cloud/yandex v0.200.0 (unauthenticated)
  • Installing hashicorp/null v3.2.4…
  • Installed hashicorp/null v3.2.4 (unauthenticated)
  • Installing hashicorp/local v2.8.0…
  • Installed hashicorp/local v2.8.0 (unauthenticated)
    Terraform has created a lock file .terraform.lock.hcl to record the provider
    selections it made above. Include this file in your version control repository
    so that Terraform can guarantee to make the same selections by default when
    you run “terraform init” in the future.


│ Warning: Incomplete lock file information for providers

│ Due to your customized provider installation methods, Terraform was forced to calculate
│ lock file checksums locally for the following providers:
│ - hashicorp/local
│ - hashicorp/null
│ - yandex-cloud/yandex

│ The current .terraform.lock.hcl file only includes checksums for linux_amd64, so Terraform
│ running on another platform will fail to install these providers.

│ To calculate additional checksums for another platform, run:
│ terraform providers lock -platform=linux_amd64
│ (where linux_amd64 is the platform to generate)

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running “terraform plan” to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.


# Terraform plan / apply

```bash
terraform plan -input=false -var-file=count_vars.vars -out=tfplan
terraform apply -auto-approve tfplan
terraform destroy -auto-approve -var-file="count_vars.vars"