Работа с Google Cloud Platform (google bigquery) и Terraform в Unix/Linux

Работа с Google Cloud Platform (google bigquery) и Terraform в Unix/Linux

Google Cloud Platrorm — это платформа вида «инфраструктура как сервис» (IaaS), позволяющая клиентам создавать, тестировать и развертывать собственные приложения на инфраструктуре Google, в высокопроизводительных виртуальных машинах.

Google Compute Engine предоставляет виртуальные машины, работающие в инновационных центрах обработки данных Google и всемирной сети.

Google BigQuery – это инструмент, обеспечивающий высокую скорость обработки запросов в больших наборах данных.

Установка terraform в Unix/Linux

Установка крайне примитивная и я описал как это можно сделать тут:

Установка terraform в Unix/Linux

Вот еще полезные статьи по GCP + Terrafrom:

Работа с Google Cloud Platform (compute instance) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute health check) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute target pool) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute forwarding rule) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute firewall) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute disk) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute image) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute instance template) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute instance group manager) и Terraform в Unix/Linux

Работа с Google Cloud Platform (compute autoscaler) и Terraform в Unix/Linux

Работа с Google Cloud Platform (google kms) и Terraform в Unix/Linux

Работа с Google Cloud Platform (storage bucket) и Terraform в Unix/Linux

Работа с Google Cloud Platform (google pubsub) и Terraform в Unix/Linux

Работа с Google Cloud Platform (google dns) и Terraform в Unix/Linux

Работа с Google Cloud Platform (cloudbuild_trigger) и Terraform в Unix/Linux

Работа с Google Cloud Platform (redis instance) и Terraform в Unix/Linux

Работа с Google Cloud Platform (sql database instance) и Terraform в Unix/Linux

Работа с Google Cloud Platform (sourcerepo repository) и Terraform в Unix/Linux

Работа с Google Cloud Platform (dataflow job) и Terraform в Unix/Linux

Работа с Google Cloud Platform (endpoints service) и Terraform в Unix/Linux

Работа с Google Cloud Platform (spanner instance) и Terraform в Unix/Linux

Работа с Google Cloud Platform (google runtimeconfig) и Terraform в Unix/Linux

Работа с Google Cloud Platform (google bigtable) и Terraform в Unix/Linux

Генерация документации для Terraform с Python в Unix/Linux

Так же, в данной статье, я создал скрипт для автоматической установки данного ПО. Он был протестирован на CentOS 6/7, Debian 8 и на Mac OS X. Все работает должным образом!

Чтобы получить помощь по использованию команд, выполните:

$ terraform --help
Usage: terraform [--version] [--help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    push               Upload this Terraform module to Atlas to run
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management

Приступим к использованию!

Работа с Google Cloud Platform (google bigquery) и Terraform в Unix/Linux

Первое что нужно сделать — это настроить «Cloud Identity». С помощью сервиса Google Cloud Identity вы сможете предоставлять доменам, пользователям и аккаунтам в организации доступ к ресурсам Cloud, а также централизованно управлять пользователями и группами через консоль администратора Google.

Полезное чтиво:

Установка Google Cloud SDK/gcloud в Unix/Linux

У меня есть папка terraform, в ней у меня будут лежать провайдеры с которыми я буду работать. Т.к в этом примере я буду использовать google_cloud_platform, то создам данную папку и перейду в нее. Далее, в этой папке, стоит создать:

$ mkdir examples modules

В папке examples, я буду хранить так званые «плейбуки» для разварачивания различных служб, например — zabbix-server, grafana, web-серверы и так далее. В modules директории, я буду хранить все необходимые модули.

Начнем писать модуль, но для этой задачи, я создам папку:

$  mkdir modules/google_bigquery

Переходим в нее:

$ cd modules/google_bigquery

Открываем файл:

$ vim google_bigquery.tf

В данный файл, вставляем:

#---------------------------------------------------
# Create google bigquery dataset
#---------------------------------------------------
resource "random_integer" "dataset" {
    count   = "${var.enable_bigquery_dataset ? 1 : 0}" 
                    
    min     = 10
    max     = 1024
    keepers = {
        dataset_id = "${var.dataset_id}"
    }
}

resource "google_bigquery_dataset" "bigquery_dataset" {
    count                       = "${var.enable_bigquery_dataset ? 1 : 0}"
    
    dataset_id                  = "${length(var.dataset_id) >0 ? var.dataset_id : "${random_integer.dataset.result}" }"
    friendly_name               = "${length(var.friendly_name) >0 ? var.friendly_name : "${lower(var.name)}-bq-dataset-${lower(var.environment)}" }"
    description                 = "${var.description}"
    project                     = "${var.project}"
    location                    = "${var.location}"
    default_table_expiration_ms = "${var.default_table_expiration_ms}"
    
    labels {
        name            = "${lower(var.name)}-bq-dataset-${lower(var.environment)}"
        dataset_id      = "${length(var.dataset_id) >0 ? var.dataset_id : "${random_integer.dataset.result}" }"
        environment     = "${lower(var.environment)}"
        orchestration   = "${lower(var.orchestration)}"
    }

    lifecycle {
        ignore_changes = ["dataset_id"]
        create_before_destroy = true
    }

    depends_on  = ["random_integer.dataset"] 
}

#---------------------------------------------------
# Create google bigquery table
#---------------------------------------------------
resource "random_integer" "table" {
    count   = "${var.enable_bigquery_table ? 1 : 0}"

    min     = 10
    max     = 1024
    keepers = {
        table_id = "${var.table_id}"
    }
}

resource "google_bigquery_table" "bigquery_table" {
    count           = "${var.enable_bigquery_table ? 1 : 0}"
    
    project         = "${var.project}"
    dataset_id      = "${var.dataset_id}"
    table_id        = "${length(var.table_id) >0 ? var.table_id : "${random_integer.table.result}" }"
    description     = "${var.table_description}"    
    
    expiration_time = "${var.expiration_time}"
    friendly_name   = "${length(var.table_friendly_name) >0 ? var.table_friendly_name : "${lower(var.name)}-bq-table-${lower(var.environment)}" }"
    
    time_partitioning {
        type            = "${var.time_partitioning_type}"
        expiration_ms   = "${var.time_partitioning_expiration_ms}"
        field           = "${var.time_partitioning_field}"
    } 

    #view {
    #    query           = "${var.view_query}"
    #    use_legacy_sql  = "${var.view_use_legacy_sql}"
    #}

    labels {
        name            = "${length(var.table_friendly_name) >0 ? var.table_friendly_name : "${lower(var.name)}-bq-table-${lower(var.environment)}" }"
        table_id        = "${length(var.table_id) >0 ? var.table_id : "${random_integer.table.result}" }"
        environment     = "${lower(var.environment)}"
        orchestration   = "${lower(var.orchestration)}"
    }

    schema = "${file("${path.module}/${var.schema_file}")}"

    lifecycle {
        ignore_changes = ["dataset_id"]
        create_before_destroy = true
    }

    depends_on  = ["random_integer.table"]
}

resource "random_integer" "table_view" {
    count   = "${var.enable_bigquery_table_view ? 1 : 0}"

    min     = 10
    max     = 1024
    keepers = {
        table_id = "${var.table_id}"
    }
}

resource "google_bigquery_table" "bigquery_table_view" {
    count           = "${var.enable_bigquery_table_view ? 1 : 0}"

    project         = "${var.project}"
    dataset_id      = "${var.dataset_id}"
    table_id        = "${length(var.table_id) >0 ? var.table_id : "${random_integer.table_view.result}" }"
    description     = "${var.table_description}"

    expiration_time = "${var.expiration_time}"
    friendly_name   = "${length(var.table_friendly_name) >0 ? var.table_friendly_name : "${lower(var.name)}-bq-table-${lower(var.environment)}" }"

    time_partitioning {
        type            = "${var.time_partitioning_type}"
        expiration_ms   = "${var.time_partitioning_expiration_ms}"
        field           = "${var.time_partitioning_field}"
    }

    view {
        query           = "${var.view_query}"
        use_legacy_sql  = "${var.view_use_legacy_sql}"
    }

    labels {
        name            = "${length(var.table_friendly_name) >0 ? var.table_friendly_name : "${lower(var.name)}-bq-table-${lower(var.environment)}" }"
        table_id        = "${length(var.table_id) >0 ? var.table_id : "${random_integer.table_view.result}" }"
        environment     = "${lower(var.environment)}"
        orchestration   = "${lower(var.orchestration)}"
    }

    schema = "${file("${path.module}/${var.schema_file}")}"

    lifecycle {
        ignore_changes = ["dataset_id"]
        create_before_destroy = true
    }

    depends_on  = ["random_integer.table_view"]
}

Открываем файл:

$ vim variables.tf

И прописываем:

variable "name" {
    description = "A unique name for the resource, required by GCE. Changing this forces a new resource to be created."
    default     = "TEST"
}

variable "zone" {
  description = "The zone that the machine should be created in"
  default     = "us-east1-b"    
} 

variable "environment" {
    description = "Environment for service"
    default     = "STAGE"
}

variable "orchestration" {
    description = "Type of orchestration"
    default     = "Terraform"
}

variable "enable_bigquery_dataset" {
    description = "Enable bigquery dataset usage"
    default     = "true"
}

variable "dataset_id" {
    description = "(Required) A unique ID for the resource. Changing this forces a new resource to be created."
    default     = ""
}

variable "friendly_name" {
    description = "(Optional) A descriptive name for the dataset."
    default     = ""
}

variable "description" {
    description = "(Optional) A user-friendly description of the dataset."
    default     = ""
}

variable "project" {
    description = "(Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used."
    default     = ""
}

variable "location" {
    description = "(Optional) The geographic location where the dataset should reside. See official docs. There are two types of locations, regional or multi-regional. A regional location is a specific geographic place, such as Tokyo, and a multi-regional location is a large geographic area, such as the United States, that contains at least two geographic places. Possible regional values include: asia-northeast1 Possible multi-regional values:EU and US. The default value is multi-regional location US. Changing this forces a new resource to be created."
    default     = "US"
}

variable "default_table_expiration_ms" {
    description = "(Optional) The default lifetime of all tables in the dataset, in milliseconds. The minimum value is 3600000 milliseconds (one hour). Once this property is set, all newly-created tables in the dataset will have an expirationTime property set to the creation time plus the value in this property, and changing the value will only affect new tables, not existing ones. When the expirationTime for a given table is reached, that table will be deleted automatically. If a table's expirationTime is modified or removed before the table expires, or if you provide an explicit expirationTime when creating a table, that value takes precedence over the default expiration time indicated by this property."
    default     = "3600000"
}

variable "enable_bigquery_table" {
    description = "Enable bigquery table usage"
    default     = "false"
}

variable "table_id" {
    description = "(Required) A unique ID for the resource. Changing this forces a new resource to be created."
    default     = ""
}

variable "table_description" {
    description = "(Optional) The field description."
    default     = ""
}

variable "expiration_time" {
    description = "(Optional) The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed."
    default     = "0"
}

variable "table_friendly_name" {
    description = "(Optional) A descriptive name for the table."
    default     = ""
}

variable "time_partitioning_type" {
    description = "(Required) The only type supported is DAY, which will generate one partition per day based on data loading time."
    default     = "DAY"
}
    
variable "time_partitioning_expiration_ms" {
    description = "(Optional) Number of milliseconds for which to keep the storage for a partition."
    default     = "0"
}

variable "time_partitioning_field" {
    description = "(Optional) The field used to determine how to create a time-based partition. If time-based partitioning is enabled without this value, the table is partitioned based on the load time."
    default     = ""
}

variable "view_query" {
    description = "(Required) A query that BigQuery executes when the view is referenced."
    default     = ""
}

variable "view_use_legacy_sql" {
    description = "(Optional) Specifies whether to use BigQuery's legacy SQL for this view. The default value is true. If set to false, the view will use BigQuery's standard SQL."
    default     = ""
}

variable "enable_bigquery_table_view" {
    description = "Enable bigquery table view usage"
    default     = "false"
}

variable "schema_file" {
    description = "(Optional) A JSON schema for the table."
    default     = "files/schema.json"
}

Собственно в этом файле храняться все переменные. Спасибо кэп!

Открываем последний файл:

$ vim outputs.tf

И в него вставить нужно следующие строки:

#---------------------------------------------------------------------------
# Google bigquery dataset
#---------------------------------------------------------------------------
output "google_bigquery_dataset_dataset_id" {
    description = "dataset_id of google_bigquery_dataset"
    value       = "${google_bigquery_dataset.bigquery_dataset.*.dataset_id}"
}

output "google_bigquery_dataset_id" {
    description = "ID"
    value       = "${google_bigquery_dataset.bigquery_dataset.*.id}"
}

output "google_bigquery_dataset_etag" {
    description = "etag"
    value       = "${google_bigquery_dataset.bigquery_dataset.*.etag}"
}

output "google_bigquery_dataset_friendly_name" {
    description = "friendly_name"
    value       = "${google_bigquery_dataset.bigquery_dataset.*.friendly_name}"
}

output "google_bigquery_dataset_self_link" {
    description = "self_link"
    value       = "${google_bigquery_dataset.bigquery_dataset.*.self_link}"
}

output "google_bigquery_dataset_creation_time" {
    description = "creation_time"
    value       = "${google_bigquery_dataset.bigquery_dataset.*.creation_time}"
}

#---------------------------------------------------------------------------
# Google bigquery table
#---------------------------------------------------------------------------
output "google_bigquery_table_etag" {
    description = "etag"
    value       = "${google_bigquery_table.bigquery_table.*.etag}"
}

output "google_bigquery_table_self_link" {
    description = "self_link"
    value       = "${google_bigquery_table.bigquery_table.*.self_link}"
}

output "google_bigquery_table_table_id" {
    description = "table_id"
    value       = "${google_bigquery_table.bigquery_table.*.table_id}"
}

output "google_bigquery_table_view_etag" {
    description = "etag"
    value       = "${google_bigquery_table.bigquery_table_view.*.etag}"
}

output "google_bigquery_table_view_self_link" {
    description = "self_link"
    value       = "${google_bigquery_table.bigquery_table_view.*.self_link}"
}

output "google_bigquery_table_view_table_id" {
    description = "table_id"
    value       = "${google_bigquery_table.bigquery_table_view.*.table_id}"
}

Переходим теперь в папку google_cloud_platform/examples и создадим еще одну папку для проверки написанного чуда:

$ mkdir google_bigquery && cd $_

Внутри созданной папки открываем файл:

$ vim main.tf

Вставляем:

#
# MAINTAINER Vitaliy Natarov "vitaliy.natarov@yahoo.com"
#
terraform {
  required_version = "> 0.9.0"
}
provider "google" {
    credentials = "${file("/Users/captain/.config/gcloud/creds/terraform_creds.json")}"
    project     = "terraform-2018"
    region      = "us-east1"
}   
module "google_bigquery" {
    source                              = "../../modules/google_bigquery"
    name                                = "TEST"

    enable_bigquery_dataset             = true
    #
    #enable_bigquery_table               = true
    #dataset_id                          = "668"
    
}

Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:

$ terraform init

Этим действием я инициализирую проект. Затем, подтягиваю модуль:

$ terraform get

PS: Для обновление изменений в самом модуле, можно выполнять:

$ terraform get -update

Проверим валидацию:

$ terraform validate

Запускем прогон:

$ terraform plan

Мне вывело что все у меня хорошо и можно запускать деплой:

$ terraform apply

Как видно с вывода, — все прошло гладко! Чтобы удалить созданное творение, можно выполнить:

$ terraform destroy

Весь материал аплоаджу в github аккаунт для удобства использования:

$ git clone https://github.com/SebastianUA/terraform.git

Вот и все на этом. Данная статья «Работа с Google Cloud Platform (google bigquery) и Terraform в Unix/Linux» завершена.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.