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

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

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

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

Cloud Endpoints — это набор технологий, обеспечивающих сквозное управление API: написания и обслуживания вашего API (путем его обеспечения и мониторинга во время выполнения). Функциональность управления обеспечивается через Extensible Service Proxy или с использованием Framework Endpoints в Java или Python.

Установка 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

fdsfs

Генерация документации для 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 (endpoints service) и 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/endpoints_service

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

$ cd modules/endpoints_service

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

$ vim endpoints_service.tf

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

#---------------------------------------------------
# Create endpoints service (openapi)
#---------------------------------------------------
resource "google_endpoints_service" "endpoints_service_openapi" {
    count           = "${var.enable_endpoints_service_openapi && length(var.openapi_config) >0 ? 1 : 0}"  

    service_name    = "${var.service_name}"
    project         = "${var.project}"
    openapi_config  = "${file("${path.module}/${var.openapi_config}")}"

    lifecycle {
        ignore_changes = []
        create_before_destroy = true
    }
}

#---------------------------------------------------
# Create endpoints service (grpc)
#---------------------------------------------------
resource "google_endpoints_service" "endpoints_service_grpc" {
    count                   = "${var.enable_endpoints_service_grpc && length(var.grpc_config) >0 && length(var.protoc_output_base64) >0 ? 1 : 0}"  
                
    service_name            = "${var.service_name}"
    project                 = "${var.project}"
    grpc_config             = "${file("${path.module}/${var.grpc_config}")}"
    protoc_output_base64    = "${file("${path.module}/${var.protoc_output_base64}")}"
                    
    lifecycle {
        ignore_changes = []
        create_before_destroy = true
    }
}

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

$ vim variables.tf

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

variable "project" {
  description = "(Optional) The project ID that the service belongs to. If not provided, provider project is used."
  default     = ""    
} 

variable "enable_endpoints_service_openapi" {
    description = "Enable endpoints service openapi usage"
    default     = "false"
}

variable "openapi_config" {
    description = "(Optional) The full text of the OpenAPI YAML configuration as described. Set path to openapi config file. Ex: openapi_spec.yml."
    default     = ""
}

variable "enable_endpoints_service_grpc" {
    description = "Enable endpoints service grpc usage"
    default     = "false"
}

variable "grpc_config" {
    description = "(Optional) The full text of the Service Config YAML file (Example located here). If provided, must also provide protoc_output. open_api config must not be provided. Set path to grpc config file. Ex: service_spec.yml"
    default     = ""
}

variable "protoc_output_base64" {
    description = "(Optional) The full contents of the Service Descriptor File generated by protoc. This should be a compiled .pb file, base64-encoded. Set path to protoc output file. Ex: compiled_descriptor_file.pb"
    default     = ""
}

variable "service_name" {
    description = "(Required) The name of the service. Usually of the form $apiname.endpoints.$projectid.cloud.goog."
    default     = ""
}

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

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

$ vim outputs.tf

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

#-----------------------------------------------------------------------
# Openapi
#-----------------------------------------------------------------------
output "google_endpoints_service_openapi_id" {
    description = "ID"
    value       = "${google_endpoints_service.endpoints_service_openapi.*.id}"
}

output "google_endpoints_service_openapi_endpoints" {
    description = "endpoints"
    value       = "${google_endpoints_service.endpoints_service_openapi.*.endpoints}"
}

output "google_endpoints_service_openapi_dns_address" {
    description = "dns_address"
    value       = "${google_endpoints_service.endpoints_service_openapi.*.dns_address}"
}

output "google_endpoints_service_openapi_apis" {
    description = "apis"
    value       = "${google_endpoints_service.endpoints_service_openapi.*.apis}"
}
#-----------------------------------------------------------------------
#
#-----------------------------------------------------------------------
output "google_endpoints_service_grpc_id" {
    description = "ID"
    value       = "${google_endpoints_service.endpoints_service_grpc.*.id}"
}

output "google_endpoints_service_grpc_endpoints" {
    description = "endpoints"
    value       = "${google_endpoints_service.endpoints_service_grpc.*.endpoints}"
}

output "google_endpoints_service_grpc_dns_address" {
    description = "dns_address"
    value       = "${google_endpoints_service.endpoints_service_grpc.*.dns_address}"
}

output "google_endpoints_service_grpc_apis" {
    description = "apis"
    value       = "${google_endpoints_service.endpoints_service_grpc.*.apis}"
}

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

$ mkdir endpoints_service && 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 "endpoints_service" {
    source                              = "../../modules/endpoints_service"

    # Use openapi 
    enable_endpoints_service_openapi    = true
    openapi_config                      = "files/openapi_spec.yml"   
    #
    # Use grpc
    #enable_endpoints_service_grpc        = true
    #grpc_config                         = "files/service_spec.yml"
    #protoc_output_base64                = "files/compiled_descriptor_file.pb"

   service_name                         = "api-name.endpoints.terraform-2018.cloud.goog"
}

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

$ 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 (endpoints service) и Terraform в Unix/Linux» завершена.

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

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

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