Programming/IaC
[IaC] Terraform Syntax-GCP
Hayley Shim
2023. 10. 28. 17:45
안녕하세요. [IaC] Terraform Syntax-AWS 내용을 참고하여 GCP Provider 버전으로 작성했습니다.
사전환경
- GCP IAM User 생성
- CSP IAM 비교 : 참고
- IAM feature comparisons: Each of the three providers implements some variant of a Role-Based Access Control (RBAC) system. Users assume “roles,” which are typically pre-defined groupings of access and authorization policies that define what resources they do and do not have access to.

Logical organization
- GCP CLI 설치 및 IAM User 자격 증명 설정 : 참고

2. GCP VPC 확인
- 각 region에 기본 VPC가 있는 AWS와 달리 GCP는 하나의 VPC 내에 region이 있습니다.

# View networks
$ gcloud cmopute networks list
NAME SUBNET_MODE BGP_ROUTING_MODE IPV4_RANGE GATEWAY_IPV4
default AUTO REGIONAL# List subnets
$ gcloud compute networks subnets list
NAME REGION NETWORK RANGE STACK_TYPE IPV6_ACCESS_TYPE INTERNAL_IPV6_PREFIX EXTERNAL_IPV6_PREFIX
default us-central1 default 10.128.0.0/20 IPV4_ONLY
default europe-west1 default 10.132.0.0/20 IPV4_ONLY
...
3. 테라폼 설치
- 설치 링크 : 개인 OS 환경에 맞게 설치해줍니다.
# 자동 완성
$ terraform -install-autocomplete
$ cat ~/.zshrc
autoload -U +X bashcompinit && bashcompinit
complete -o nospace -C /opt/homebrew/bin/terraform terraform
단일 서버 배포
- text editor : visual studio code
- 빈폴더(study-terraform) -> main.tf 파일 생성
- gcp 를 공급자로 사용하여 asia-northeast3 리전에 인프라를 배포한다는 것을 의미
- provider : gcp와 같은 공급자 이름
- type : instance와 같이 해당 공급자에서 생성할 리소스 유형
- name : 테라폼에서 이 리소스를 참조하기 위해 사용할 수 있는 my_instance와 같은 식별자
- CONFIG : 특정 리소스에 대한 하나 이상의 인수(argument)로 구성
GCP compute_instance 배포
- boot_disk 내 auto_delete = false 옵션을 통해 인스턴스 종료 시 디스크 볼륨 삭제되는 것 방지
# 코드 스캔, 공급자 확인, 필요한 코드를 다운로드(.terraform)
$ terraform init# 실제 변경 전 테라폼이 수행할 작업 확인(유닉스, 리눅스, 깃 등의 diff 명령 결과값과 유사, +항목:추가, - 항목:삭제, ~항목:수정)# 실제 인스턴스 생성
$ terraform plan# terraform resource 적용
$ terraform apply# terraform resource 삭제
$ terraform destroy
버전 관리
- 테라폼 코드가 동작하면 버전 관리 도구에 저장하는 것을 권장
- 다른 팀 구성원과 코드 공유 가능 및 모든 인프라의 변경 내용을 추적하거나 커밋 로그 사용하여 디버깅 가능
$ git init
$ git add main.tf
$ git commit -m "Initial commit"
GCP 보안 설정
- AWS의 instance 보안 설정인 Security Group과 유사하게 GCP는 instance에 firewall rule을 적용할 수 있습니다.
- 실습 코드 : Github repo
참고
blog migration project
written in 2022.10.21
https://medium.com/techblog-hayleyshim/iac-terraform-syntax-gcp-6459d26f0dc4