Первоначально опубликовано в pbhadani.com Добро пожаловать в мой пост и с Новым годом!
Давайте создадим наш первый ресурс GCP, используя Terraform в этом посте.
Создайте ведро Google Cloud Storage (GCS), используя Terraform.
Этот пост предполагает следующее:
- У нас уже есть проект GCP и созданное ведро GCS (мы будем использовать его для хранения файла состояния Terraform).
- Google Cloud SDK (
gcloud
) иTerraform
настроен на вашей рабочей станции. Если у вас нет, то обратитесь к моим предыдущим блогам — Начало работы с Terraform и Начало работы с Google Cloud SDK Анкет
Шаг 1: Создайте каталог UNIX для проекта Terraform.
mkdir ~/terraform-gcs-example cd ~/terraform-gcs-example
Шаг 2: Создайте файл конфигурации Terraform, который определяет ведро GCS и поставщик.
vi bucket.tf
Этот файл имеет следующее содержимое
# Specify the GCP Provider provider "google" { project = var.project_id region = var.region } # Create a GCS Bucket resource "google_storage_bucket" "my_bucket" { name = var.bucket_name location = var.region }
Шаг 3: Определите переменные терраформ.
vi variables.tf
Этот файл выглядит так:
variable "project_id" { description = "Google Project ID." type = string } variable "bucket_name" { description = "GCS Bucket name. Value should be unique ." type = string } variable "region" { description = "Google Cloud region" type = string default = "europe-west2" }
**Note:** We are defining a `default` value for `region`. This means if a value is not supplied for this variable, Terraform will use `europe-west2` as its value.
Шаг 4: Создать tfvars
файл.
vi terraform.tfvars
project_id = "" # Put your GCP Project ID. bucket_name = "my-bucket-48693" # Put the desired GCS Bucket name.
Шаг 5: Установите удаленное состояние.
vi backend.tf
terraform { backend "gcs" { bucket = "my-tfstate-bucket" # GCS bucket name to store terraform tfstate prefix = "first-app" # Update to desired prefix name. Prefix name should be unique for each Terraform project having same remote state bucket. } }
Шаг 6: Структура файла выглядит ниже
cntekio:~ terraform-gcs-example$ tree . ├── backend.tf ├── bucket.tf ├── terraform.tfvars └── variables.tf 0 directories, 4 files
Шаг 7: Теперь инициализируйте проект Terraform.
terraform init
Выход
Initializing the backend... Successfully configured the backend "gcs"! Terraform will automatically use this backend unless the backend configuration changes. Initializing provider plugins... - Checking for available provider plugins... - Downloading plugin for provider "google" (hashicorp/google) 3.3.0... The following providers do not have any version constraints in configuration, so the latest version was installed. To prevent automatic upgrades to new major versions that may contain breaking changes, it is recommended to add version = "..." constraints to the corresponding provider blocks in configuration, with the constraint strings suggested below. * provider.google: version = "~> 3.3" 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 Init
Загружает все необходимые поставщики и плагины.
Шаг 8: Давайте посмотрим на план исполнения.
terraform plan --out 1.plan
Выход
Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. ------------------------------------------------------------------------ An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # google_storage_bucket.my_bucket will be created + resource "google_storage_bucket" "my_bucket" { + bucket_policy_only = (known after apply) + force_destroy = false + id = (known after apply) + location = "EUROPE-WEST2" + name = "my-bucket-48693" + project = (known after apply) + self_link = (known after apply) + storage_class = "STANDARD" + url = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ This plan was saved to: 1.plan To perform exactly these actions, run the following command to apply: terraform apply "1.plan"
Примечание: План терраформ
Вывод показывает, что этот код создаст одно ведро GCS. --В-ПЛАНА
Флаг говорит Terraform, чтобы сохранить план в файле.
Шаг 9: План выполнения выглядит хорошо, поэтому давайте продвинутесь вперед и применим этот план.
terraform apply 1.plan
Выход
google_storage_bucket.my_bucket: Creating... google_storage_bucket.my_bucket: Creation complete after 3s [id=my-bucket-48693] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Шаг 10: Как только нам больше не нужна эта инфраструктура, мы сможем очистить, чтобы снизить затраты.
terraform destroy
Выход
google_storage_bucket.my_bucket: Refreshing state... [id=my-bucket-48693] An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: - destroy Terraform will perform the following actions: # google_storage_bucket.my_bucket will be destroyed - resource "google_storage_bucket" "my_bucket" { - bucket_policy_only = false -> null - force_destroy = false -> null - id = "my-bucket-48693" -> null - labels = {} -> null - location = "EUROPE-WEST2" -> null - name = "my-bucket-48693" -> null - project = "my-project-id" -> null - requester_pays = false -> null - self_link = "https://www.googleapis.com/storage/v1/b/my-bucket-48693" -> null - storage_class = "STANDARD" -> null - url = "gs://my-bucket-48693" -> null } Plan: 0 to add, 0 to change, 1 to destroy. Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value: yes google_storage_bucket.my_bucket: Destroying... [id=my-bucket-48693] google_storage_bucket.my_bucket: Destruction complete after 6s Destroy complete! Resources: 1 destroyed.
Надеюсь, этот блог поможет вам начать с создания ресурсов GCP с помощью Terraform
Если у вас есть отзывы или вопросы, пожалуйста, обратитесь ко мне в LinkedIn или Твиттер
Оригинал: «https://dev.to/pradeepbhadani/create-first-gcp-resource-with-terraform-2gj5»