{Terraform}RDS/GCP

 

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/sql_database_instance

 

-- 1. macにTerraformインストール

brew tap hashicorp/tap
brew install hashicorp/tap/terraform
brew update
brew upgrade hashicorp/tap/terraform
terraform -help
terraform -version


-- 2. GCPプロジェクト作成

gcloud init
gcloud auth list

gcloud --version

gcloud projects create project01-9999999 \
--name="project01"

gcloud config list
gcloud config set project project01-9999999
gcloud config set compute/region asia-northeast1 --quiet
gcloud config set compute/zone asia-northeast1-a --quiet

 

gcloud beta billing accounts list
gcloud beta billing projects link project01-9999999 --billing-account=111111-111111-111111

gcloud services enable compute.googleapis.com --project project01-9999999

 

-- 3. tfファイル作成

vim main.tf

provider "google" {
  project = "project01-9999999"
  region = "asia-northeast1"
}


resource "google_sql_database_instance" "postgres01" {
  region           = "asia-northeast1"
  database_version = "POSTGRES_15"
  name             = "postgres01"
  root_password    = "password"
  deletion_protection = false
  
  settings {
    tier = "db-f1-micro"
    availability_type = "ZONAL"
    deletion_protection_enabled = false
    disk_autoresize = false
    disk_size = 10
    disk_type = "PD_HDD"

    backup_configuration {
      enabled = true
      point_in_time_recovery_enabled = true
      transaction_log_retention_days = 1
      backup_retention_settings {
        retained_backups = 1
        retention_unit = "COUNT"
      }
    }

    ip_configuration {
      ipv4_enabled = true
    }
    
  }
}

 


-- 4. terraform 実行


gcloud auth application-default login
terraform init

terraform plan
terraform apply

17分かかった


gcloud sql instances list
gcloud sql instances describe postgres01

承認済みアドレスの設定

gcloud sql instances patch postgres01 \
--authorized-networks=192.0.2.1/32


インスタンス接続
gcloud sql databases list --instance=postgres01

gcloud sql connect postgres01 --user=postgres --database=postgres


-- 5. GCPクリーンアップ

terraform destroy


gcloud projects list

gcloud projects delete project01-9999999 \
--quiet