
Работа с Google Cloud Platform (compute health check) и Terraform в Unix/Linux
Google Cloud Platrorm — это платформа вида «инфраструктура как сервис» (IaaS), позволяющая клиентам создавать, тестировать и развертывать собственные приложения на инфраструктуре Google, в высокопроизводительных виртуальных машинах.
google_compute_health_check — позволяет проверять машины в GCE (хелзчек). Данный модуль используется для мониторинга экземпляров в балансировщиках нагрузки. Таймауты или ошибки HTTP заставляют экземпляры удаляться из пула.
Установка terraform в Unix/Linux
Установка крайне примитивная и я описал как это можно сделать тут:
Установка terraform в 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 (compute health check) и Terraform в Unix/Linux
Первое что нужно сделать — это настроить «Cloud Identity». С помощью сервиса Google Cloud Identity вы сможете предоставлять доменам, пользователям и аккаунтам в организации доступ к ресурсам Cloud, а также централизованно управлять пользователями и группами через консоль администратора Google.
Полезное чтиво:
Установка Google Cloud SDK/gcloud в Unix/Linux
Приведу пример настройки аккаунта, для этого открываем консоль с гуглом и переходим в «IAM и администрирование»->»Сервисные аккаунты»:

IAM и администрирование в Google Cloud
Нажимаем на «Создать сервисный аккаунт»:

Создать сервисный аккаунт в Google Cloud
Прописываем необходимые данные и нажимаем на «Сохранить». Создать то создали, но нужно еще и разрешить использование необходимых ресурсов:

Создать сервисный аккаунт в Google Cloud
Выбираем необходимые политики и нажимаем на «Сохранить».
PS: Можно все это дело наклацать в консоле, следующим образом:
$ gcloud iam service-accounts create terraform \ --display-name "Terraform admin account" $ gcloud iam service-accounts keys create /Users/captain/.config/gcloud/creds/terraform_creds.json \ --iam-account terraform@terraform-2018.iam.gserviceaccount.com
Где:
- terraform — Название юзера. Данный юзер будет использоватся для дальнейшего использования.
- /Users/captain/.config/gcloud/creds/terraform_creds.json — Путь куда сохранится файл.
- terraform-2018 — название проекта. Данный проект будет фигурировать и в следующих моих статьях.
Предоставьте разрешение учетной записи службы для просмотра проекта Admin и управления облачным хранилищем:
$ gcloud projects add-iam-policy-binding terraform-2018 \ --member serviceAccount:terraform@terraform-2018.iam.gserviceaccount.com \ --role roles/owner $ gcloud projects add-iam-policy-binding terraform-2018 \ --member serviceAccount:terraform@terraform-2018.iam.gserviceaccount.com \ --role roles/storage.admin
Любые действия, которые выполняються через Terraform, требуют, чтобы API был включен. В этом руководстве Terraform требует следующее:
$ gcloud services enable cloudresourcemanager.googleapis.com $ gcloud services enable cloudbilling.googleapis.com $ gcloud services enable iam.googleapis.com $ gcloud services enable compute.googleapis.com
Я не уверен что это вся политика которая необходима мне для дальнейшей работы. Но будем смотреть по обстоятельствам, у меня не много опыта с Google Cloud, по этому — вникать приходится сразу. Иногда, материал очень устаревший, даже не официальном сайте — это возмутимо!
У меня есть папка terraform, в ней у меня будут лежать провайдеры с которыми я буду работать. Т.к в этом примере я буду использовать google_cloud_platform, то создам данную папку и перейду в нее. Далее, в этой папке, стоит создать:
$ mkdir examples modules
В папке examples, я буду хранить так званые «плейбуки» для разварачивания различных служб, например — zabbix-server, grafana, web-серверы и так далее. В modules директории, я буду хранить все необходимые модули.
Начнем писать модуль, но для этой задачи, я создам папку:
$ mkdir modules/compute_health_check
Переходим в нее:
$ cd modules/compute_health_check
Открываем файл:
$ vim compute_health_check.tf
В данный файл, вставляем:
#--------------------------------------------------- # Create compute http health check #--------------------------------------------------- resource "google_compute_health_check" "compute_http_health_check" { count = "${var.enable_compute_http_health_check ? 1 : 0 }" project = "${var.project}" name = "${length(var.custom_name) > 0 ? var.custom_name : "${lower(var.name)}-http-hc-${lower(var.environment)}" }" description = "${var.description}" check_interval_sec = "${var.check_interval_sec}" timeout_sec = "${var.timeout_sec}" healthy_threshold = "${var.healthy_threshold}" unhealthy_threshold = "${var.unhealthy_threshold}" http_health_check { host = "${var.http_health_check_host}" port = "${var.http_health_check_port}" proxy_header = "${var.http_health_check_proxy_header}" request_path = "${var.http_health_check_request_path}" } lifecycle { ignore_changes = [] create_before_destroy = true } } #--------------------------------------------------- # Create compute https health check #--------------------------------------------------- resource "google_compute_health_check" "compute_https_health_check" { count = "${var.enable_compute_https_health_check ? 1 : 0 }" project = "${var.project}" name = "${length(var.custom_name) > 0 ? var.custom_name : "${lower(var.name)}-https-hc-${lower(var.environment)}" }" description = "${var.description}" check_interval_sec = "${var.check_interval_sec}" timeout_sec = "${var.timeout_sec}" healthy_threshold = "${var.healthy_threshold}" unhealthy_threshold = "${var.unhealthy_threshold}" https_health_check { host = "${var.https_health_check_host}" port = "${var.https_health_check_port}" proxy_header = "${var.https_health_check_proxy_header}" request_path = "${var.https_health_check_request_path}" } lifecycle { ignore_changes = [] create_before_destroy = true } } #--------------------------------------------------- # Create compute SSL health check #--------------------------------------------------- resource "google_compute_health_check" "compute_ssl_health_check" { count = "${var.enable_compute_ssl_health_check ? 1 : 0 }" project = "${var.project}" name = "${length(var.custom_name) > 0 ? var.custom_name : "${lower(var.name)}-ssl-hc-${lower(var.environment)}" }" description = "${var.description}" check_interval_sec = "${var.check_interval_sec}" timeout_sec = "${var.timeout_sec}" healthy_threshold = "${var.healthy_threshold}" unhealthy_threshold = "${var.unhealthy_threshold}" ssl_health_check { port = "${var.ssl_health_check_port}" proxy_header = "${var.ssl_health_check_proxy_header}" request = "${var.ssl_health_check_request}" response = "${var.ssl_health_check_response}" } lifecycle { ignore_changes = [] create_before_destroy = true } } #--------------------------------------------------- # Create compute TCP health check #--------------------------------------------------- resource "google_compute_health_check" "compute_tcp_health_check" { count = "${var.enable_compute_tcp_health_check ? 1 : 0 }" project = "${var.project}" name = "${length(var.custom_name) > 0 ? var.custom_name : "${lower(var.name)}-tcp-hc-${lower(var.environment)}" }" description = "${var.description}" check_interval_sec = "${var.check_interval_sec}" timeout_sec = "${var.timeout_sec}" healthy_threshold = "${var.healthy_threshold}" unhealthy_threshold = "${var.unhealthy_threshold}" tcp_health_check { port = "${var.tcp_health_check_port}" proxy_header = "${var.tcp_health_check_proxy_header}" request = "${var.tcp_health_check_request}" response = "${var.tcp_health_check_response}" } lifecycle { ignore_changes = [] create_before_destroy = true } }
Открываем файл:
$ 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 "custom_name" { description = "A custom name for the resource, required by GCE. Changing this forces a new resource to be created." default = "" } variable "project" { description = "The project in which the resource belongs. If it is not provided, the provider project is used." default = "" } 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 "createdby" { description = "Created by" default = "Vitaliy Natarov" } variable "project_name" { description = "The ID of the project in which the resource belongs. If it is not provided, the provider project is used." default = "" } variable "check_interval_sec" { description = "The number of seconds between each poll of the instance instance (default 5)." default = "5" } variable "timeout_sec" { description = "The number of seconds to wait before declaring failure (default 5)." default = 5 } variable "description" { description = "Textual description field." default = "" } variable "healthy_threshold" { description = "Consecutive successes required (default 2)." default = 2 } variable "unhealthy_threshold" { description = "Consecutive failures required (default 2)." default = 2 } #---------------------------------------------------------------- # compute_http_health_check #---------------------------------------------------------------- variable "enable_compute_http_health_check" { description = "Enable compute http health check usage" default = false } variable "http_health_check_host" { description = "HTTP host header field (default instance's public ip)." default = "" } variable "http_health_check_port" { description = "HTTP port to connect to (default 80)." default = "80" } variable "http_health_check_proxy_header" { description = "Type of proxy header to append before sending data to the backend, either NONE or PROXY_V1 (default NONE)." default = "NONE" } variable "http_health_check_request_path" { description = "URL path to query (default /)." default = "/" } #---------------------------------------------------------------- # enable_compute_https_health_check #---------------------------------------------------------------- variable "enable_compute_https_health_check" { description = "Enable compute https health check usage" default = false } variable "https_health_check_host" { description = "HTTPS host header field (default instance's public ip)." default = "" } variable "https_health_check_port" { description = "HTTPS port to connect to (default 443)." default = "443" } variable "https_health_check_proxy_header" { description = "Type of proxy header to append before sending data to the backend, either NONE or PROXY_V1 (default NONE)." default = "NONE" } variable "https_health_check_request_path" { description = "URL path to query (default /)." default = "/" } #---------------------------------------------------------------- #enable_compute_ssl_health_check #---------------------------------------------------------------- variable "enable_compute_ssl_health_check" { description = "Enable compute ssl health check usage" default = false } variable "ssl_health_check_port" { description = "SSL port to connect to (default 443)." default = "443" } variable "ssl_health_check_proxy_header" { description = "Type of proxy header to append before sending data to the backend, either NONE or PROXY_V1 (default NONE)." default = "NONE" } variable "ssl_health_check_request" { description = "Application data to send once the SSL connection has been established (default '')." default = "" } variable "ssl_health_check_response" { description = "The response that indicates health (default '')" default = "" } #---------------------------------------------------------------- #enable_compute_tcp_health_check #---------------------------------------------------------------- variable "enable_compute_tcp_health_check" { description = "Enable compute tcp health check usage" default = false } variable "tcp_health_check_port" { description = "TCP port to connect to (default 80)." default = "80" } variable "tcp_health_check_proxy_header" { description = "Type of proxy header to append before sending data to the backend, either NONE or PROXY_V1 (default NONE)." default = "NONE" } variable "tcp_health_check_request" { description = "Application data to send once the TCP connection has been established (default '')." default = "" } variable "tcp_health_check_response" { description = "The response that indicates health (default '')" default = "" }
Собственно в этом файле храняться все переменные. Спасибо кэп!
Открываем последний файл:
$ vim outputs.tf
И в него вставить нужно следующие строки:
output "http_name" { description = "Name of http HC" value = "${google_compute_health_check.compute_http_health_check.*.name}" } output "http_self_link" { description = "self_link of http HC" value = "${google_compute_health_check.compute_http_health_check.*.self_link}" } output "https_name" { description = "Name of https HC" value = "${google_compute_health_check.compute_https_health_check.*.name}" } output "https_self_link" { description = "self_link of https HC" value = "${google_compute_health_check.compute_https_health_check.*.self_link}" } output "ssl_name" { description = "Name of ssl HC" value = "${google_compute_health_check.compute_ssl_health_check.*.name}" } output "ssl_self_link" { description = "self_link of ssl HC" value = "${google_compute_health_check.compute_ssl_health_check.*.self_link}" }
Переходим теперь в папку google_cloud_platform/examples и создадим еще одну папку для проверки написанного чуда:
$ mkdir compute_health_check && 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/captain_creds.json")}" credentials = "${file("/Users/captain/.config/gcloud/creds/terraform_creds.json")}" project = "terraform-2018" region = "us-east-1" } module "compute_health_check" { source = "../../modules/compute_health_check" name = "TEST" project = "terraform-2018" enable_compute_http_health_check = true enable_compute_https_health_check = true enable_compute_ssl_health_check = true enable_compute_tcp_health_check = true }
Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:
$ 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 (compute health check) и Terraform в Unix/Linux» завершена.