
Работа с Google Cloud Platform (spanner instance) и Terraform в Unix/Linux
Google Cloud Platrorm — это платформа вида «инфраструктура как сервис» (IaaS), позволяющая клиентам создавать, тестировать и развертывать собственные приложения на инфраструктуре Google, в высокопроизводительных виртуальных машинах.
Google Compute Engine предоставляет виртуальные машины, работающие в инновационных центрах обработки данных Google и всемирной сети.
Cloud Spanner – полностью управляемый сервис реляционных баз данных, который обеспечивает согласованность критически важных транзакций на глобальном уровне. Он поддерживает стандартную реляционную семантику (схемы, ACID-транзакции, SQL) и автоматическую синхронную репликацию для обеспечения высокой доступности.
Установка 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
Генерация документации для 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 (spanner instance) и 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/spanner_instance
Переходим в нее:
$ cd modules/spanner_instance
Открываем файл:
$ vim spanner_instance.tf
В данный файл, вставляем:
#--------------------------------------------------- # Create google spanner instance #--------------------------------------------------- resource "google_spanner_instance" "spanner_instance" { config = "${var.config}" display_name = "${length(var.display_name) >0 ? var.display_name : "${lower(var.name)}-si-${lower(var.environment)}" }" name = "${lower(var.name)}-si-${lower(var.environment)}" num_nodes = "${var.num_nodes}" project = "${var.project}" labels { name = "${lower(var.name)}-si-${lower(var.environment)}" environment = "${lower(var.environment)}" orchestration = "${lower(var.orchestration)}" } lifecycle { ignore_changes = [] create_before_destroy = true } } #--------------------------------------------------- # Create google spanner iam #--------------------------------------------------- data "google_iam_policy" "iam_policy" { binding { role = "${var.role}" members = ["${var.members}"] } } resource "google_spanner_instance_iam_policy" "spanner_instance_iam_policy" { count = "${var.enable_spanner_instance_iam_policy ? 1 : 0}" instance = "${var.instance}" policy_data = "${data.google_iam_policy.iam_policy.policy_data}" depends_on = ["data.google_iam_policy.iam_policy"] lifecycle { ignore_changes = [] create_before_destroy = true } } resource "google_spanner_instance_iam_binding" "spanner_instance_iam_binding" { count = "${var.enable_spanner_instance_iam_binding ? 1 : 0}" instance = "${var.instance}" role = "${var.role}" members = ["${var.members}"] lifecycle { ignore_changes = [] create_before_destroy = true } } resource "google_spanner_instance_iam_member" "spanner_instance_iam_member" { count = "${var.enable_spanner_instance_iam_member ? 1 : 0}" instance = "${var.instance}" role = "${var.role}" member = "${element(var.members, 0)}" lifecycle { ignore_changes = [] create_before_destroy = true } } #--------------------------------------------------- # Create spanner database #--------------------------------------------------- resource "google_spanner_database" "spanner_database" { count = "${var.enable_spanner_database ? 1 : 0}" instance = "${var.instance}" name = "${var.db_name}" project = "${var.project}" ddl = ["${var.ddl}"] lifecycle { ignore_changes = [] create_before_destroy = true } } #--------------------------------------------------- # Create spanner database iam #--------------------------------------------------- data "google_iam_policy" "database_iam_policy" { binding { role = "${var.role}" members = ["${var.members}"] } } resource "google_spanner_database_iam_policy" "spanner_database_iam_policy" { count = "${var.enable_spanner_database_iam_policy ? 1 : 0}" instance = "${var.instance}" database = "${var.db_name}" policy_data = "${data.google_iam_policy.database_iam_policy.policy_data}" depends_on = ["data.google_iam_policy.database_iam_policy"] lifecycle { ignore_changes = [] create_before_destroy = true } } resource "google_spanner_database_iam_binding" "spanner_database_iam_binding" { count = "${var.enable_spanner_database_iam_binding ? 1 : 0}" instance = "${var.instance}" database = "${var.db_name}" role = "${var.role}" members = ["${var.members}"] lifecycle { ignore_changes = [] create_before_destroy = true } } resource "google_spanner_database_iam_member" "spanner_database_iam_member" { count = "${var.enable_spanner_database_iam_member ? 1 :0}" instance = "${var.instance}" database = "${var.db_name}" role = "${var.role}" member = "${element(var.members, 0)}" 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 "environment" { description = "Environment for service" default = "STAGE" } variable "project" { description = "(Optional) The ID of the project in which to look for the instance specified. If it is not provided, the provider project is used." default = "" } variable "orchestration" { description = "Type of orchestration" default = "Terraform" } variable "config" { description = "(Required) The name of the instance's configuration (similar but not quite the same as a region) which defines defines the geographic placement and replication of your databases in this instance. It determines where your data is stored. Values are typically of the form regional-europe-west1 , us-central etc. In order to obtain a valid list please consult the Configuration section of the docs." default = "nam3" } variable "display_name" { description = "(Required) The descriptive name for this instance as it appears in UIs. Can be updated, however should be kept globally unique to avoid confusion." default = "" } variable "num_nodes" { description = "(Optional, Computed) The number of nodes allocated to this instance. Defaults to 1. This can be updated after creation." default = "1" } variable "enable_spanner_instance_iam_policy" { description = "Enable spanner instance iam policy" default = "false" } variable "role" { description = "(Required) The role that should be applied. Only one google_spanner_instance_iam_binding can be used per role. Note that custom roles must be of the format [projects|organizations]/{parent-name}/roles/{role-name}." default = "roles/editor" } variable "members" { description = "(Required) Identities that will be granted the privilege in role." default = [] } variable "instance" { description = "(Required) The name of the instance." default = "" } variable "enable_spanner_instance_iam_binding" { description = "Enable spanner instance iam binding" default = "false" } variable "enable_spanner_instance_iam_member" { description = "Enable spanner instance iam member" default = "false" } variable "enable_spanner_database" { description = "Enable spanner DB" default = "false" } variable "db_name" { description = "(Required) The name of the database." default = "db-test" } variable "ddl" { description = "(Optional) An optional list of DDL statements to run inside the newly created database. Statements can create tables, indexes, etc. These statements execute atomically with the creation of the database: if there is an error in any statement, the database is not created." default = [] } variable "enable_spanner_database_iam_policy" { description = "Enable spanner database iam policy" default = "false" } variable "enable_spanner_database_iam_binding" { description = "Enable spanner database iam binding" default = "false" } variable "enable_spanner_database_iam_member" { description = "Enable spanner database iam member" default = "false" }
Собственно в этом файле храняться все переменные. Спасибо кэп!
Открываем последний файл:
$ vim outputs.tf
И в него вставить нужно следующие строки:
#------------------------------------------------------------------- # instance #------------------------------------------------------------------- output "google_spanner_instance_name" { description = "Name of spanner_instance" value = "${google_spanner_instance.spanner_instance.name}" } output "google_spanner_instance_state" { description = "The current state of the instance." value = "${google_spanner_instance.spanner_instance.state}" } output "google_spanner_instance_id" { description = "ID" value = "${google_spanner_instance.spanner_instance.id}" } #------------------------------------------------------------------- # IAM #------------------------------------------------------------------- output "google_spanner_instance_iam_policy_etag" { description = "etag" value = "${google_spanner_instance_iam_policy.spanner_instance_iam_policy.*.etag}" } output "google_spanner_instance_iam_binding_etag" { description = "etag" value = "${google_spanner_instance_iam_binding.spanner_instance_iam_binding.*.etag}" } output "google_spanner_instance_iam_member_etag" { description = "etag" value = "${google_spanner_instance_iam_member.spanner_instance_iam_member.*.etag}" } #------------------------------------------------------------------- # DB #------------------------------------------------------------------- output "google_spanner_database_name" { description = "Name" value = "${google_spanner_database.spanner_database.*.name}" } output "google_spanner_database_state" { description = "state" value = "${google_spanner_database.spanner_database.*.state}" } #------------------------------------------------------------------- # DM IAM #------------------------------------------------------------------- output "google_spanner_database_iam_policy_etag" { description = "Etag" value = "${google_spanner_database_iam_policy.spanner_database_iam_policy.*.etag}" } output "google_spanner_database_iam_binding_etag" { description = "Etag" value = "${google_spanner_database_iam_binding.spanner_database_iam_binding.*.etag}" } output "google_spanner_database_iam_member_etag" { description = "Etag" value = "${google_spanner_database_iam_member.spanner_database_iam_member.*.etag}" }
Переходим теперь в папку google_cloud_platform/examples и создадим еще одну папку для проверки написанного чуда:
$ mkdir spanner_instance && 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 "spanner_instance" { source = "../../modules/spanner_instance" name = "TEST" num_nodes = 1 # spanner instance iam policy #enable_spanner_instance_iam_policy = true #instance = "test-si-stage" #members = ["user:solo.metaliSebastian@gmail.com",] #role = "roles/editor" # # spanner instance iam binding #enable_spanner_instance_iam_binding = true #instance = "test-si-stage" #members = [ # "user:solo.metaliSebastian@gmail.com", #] #role = "roles/editor" # # spanner instance iam member #enable_spanner_instance_iam_member = true #instance = "test-si-stage" #members = [ # "user:solo.metaliSebastian@gmail.com", #] #role = "roles/editor" # # spanner_database #enable_spanner_database = true #instance = "test-si-stage" #db_name = "db-test" #ddl = [ #] # # Create spanner database iam #enable_spanner_database_iam_policy = true #instance = "test-si-stage" #members = [ # "user:solo.metaliSebastian@gmail.com", #] #role = "roles/editor" # # spanner_database_iam_binding #enable_spanner_database_iam_binding = true #instance = "test-si-stage" #members = [ # "user:solo.metaliSebastian@gmail.com", #] #role = "roles/editor" # # spanner_database_iam_member #enable_spanner_database_iam_member = true #instance = "test-si-stage" #members = [ # "user:solo.metaliSebastian@gmail.com", #] #role = "roles/editor" }
Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:
$ 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 (spanner instance) и Terraform в Unix/Linux» завершена.