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

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

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

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

Sql database instance — сервис от гугл для создания кластера (MySQL или Postgres). Так же поддерживает репликацию.

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

Генерация документации для 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 (sql database 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/sql_database

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

$ cd modules/sql_database

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

$ vim sql_database.tf

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

#---------------------------------------------------
# Create google sql database instance
#---------------------------------------------------
resource "google_sql_database_instance" "sql_database_instance_mysql" {
    count                            = "${var.database_version !="POSTGRES_9_6" && !var.enable_replication ? var.count_sql_database_instance : 0}"
                                                                                                                                             
    name                             = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
    project                          = "${var.project}"                
    database_version                 = "${var.database_version}"
    region                           = "${lookup(var.region, var.database_version)}"
                                                 
    master_instance_name             = "${var.master_instance_name}"
    
    settings {
        tier                        = "${lookup(var.settings_tier, var.database_version)}"
        activation_policy           = "${var.settings_activation_policy}"
        authorized_gae_applications = ["${var.settings_authorized_gae_applications}"]
        availability_type           = "${var.settings_availability_type}"
        crash_safe_replication      = "${var.settings_crash_safe_replication}"
        replication_type            = "${var.settings_replication_type}"
        pricing_plan                = "${var.settings_pricing_plan}"        
                
        user_labels {
            name            = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
            environment     = "${lower(var.environment)}"
            orchestration   = "${lower(var.orchestration)}"
        }
        
        database_flags  = ["${var.settings_database_flags}"]
        
        backup_configuration {      
            binary_log_enabled  = "${var.settings_backup_configuration_binary_log_enabled}"
            enabled             = "${var.settings_backup_configuration_enabled}"
            start_time          = "${var.settings_backup_configuration_start_time}"
        }
        
        ip_configuration {
            ipv4_enabled    = "${var.settings_ip_configuration_ipv4_enabled}"
            require_ssl     = "${var.settings_ip_configuration_require_ssl}"
             
            authorized_networks {
                expiration_time = "${var.settings_authorized_networks_expiration_time}"
                name            = "${var.settings_authorized_networks_name}"
                value           = "${var.settings_authorized_networks_value}" 
            }
        }
        
        location_preference {           
            follow_gae_application  = "${var.settings_location_preference_follow_gae_application}"
            zone                    = "${var.settings_location_preference_zone}"
        }
    
        maintenance_window = []
         
    }
    
    timeouts {
        create  = "${var.timeouts_create}"
        update  = "${var.timeouts_update}"
        delete  = "${var.timeouts_delete}"
    }

    lifecycle {
        ignore_changes = []
        create_before_destroy = true
    }
}

resource "google_sql_database_instance" "sql_database_instance_postgres" {
    count                            = "${var.database_version =="POSTGRES_9_6" && !var.enable_replication ? var.count_sql_database_instance : 0}"

    name                             = "${lower(var.name)}-sd-instance15-${lower(var.environment)}-${count.index+1}"
    project                          = "${var.project}"         
    database_version                 = "${var.database_version}"
    region                           = "${lookup(var.region, var.database_version)}"

    master_instance_name             = "${var.master_instance_name}"

    settings {
        tier                        = "${lookup(var.settings_tier, var.database_version)}"
        activation_policy           = "${var.settings_activation_policy}"
        authorized_gae_applications = ["${var.settings_authorized_gae_applications}"]
        availability_type           = "${var.settings_availability_type}"
        crash_safe_replication      = "${var.settings_crash_safe_replication}"
        replication_type            = "${var.settings_replication_type}"
        
        disk_autoresize             = "${var.settings_disk_autoresize}"
        disk_size                   = "${var.database_version =="POSTGRES_9_6" ? var.settings_disk_size : 0}"
        disk_type                   = "${var.settings_disk_type}"
        
        user_labels {
            name            = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
            environment     = "${lower(var.environment)}"
            orchestration   = "${lower(var.orchestration)}"
        }
        
        database_flags  = ["${var.settings_database_flags}"]
        
        backup_configuration {
            binary_log_enabled  = "${var.settings_backup_configuration_binary_log_enabled}"
            enabled             = "${var.settings_backup_configuration_enabled}"
            start_time          = "${var.settings_backup_configuration_start_time}"
        }
        
        ip_configuration {
            ipv4_enabled    = "${var.settings_ip_configuration_ipv4_enabled}"
            require_ssl     = "${var.settings_ip_configuration_require_ssl}"
        
            authorized_networks {
                expiration_time = "${var.settings_authorized_networks_expiration_time}"
                name            = "${var.settings_authorized_networks_name}"
                value           = "${var.settings_authorized_networks_value}"
            }
        }
        
        location_preference {
            follow_gae_application  = "${var.settings_location_preference_follow_gae_application}"
            zone                    = "${var.settings_location_preference_zone}"
        }
        
        maintenance_window = []

    }

    timeouts {
        create  = "${var.timeouts_create}"
        update  = "${var.timeouts_update}"
        delete  = "${var.timeouts_delete}"
    }

    lifecycle {
        ignore_changes = []
        create_before_destroy = true
    }
}
#---------------------------------------------------
# Create google sql database instance replication
#---------------------------------------------------
resource "google_sql_database_instance" "sql_database_instance_mysql_replication" {
    count                            = "${var.database_version !="POSTGRES_9_6" && var.enable_replication ? var.count_sql_database_instance : 0}"

    name                             = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
    project                          = "${var.project}"             
    database_version                 = "${var.database_version}"
    region                           = "${lookup(var.region, var.database_version)}"

    master_instance_name             = "${var.master_instance_name}"

    replica_configuration {
        ca_certificate              = "${var.replica_configuration_ca_certificate}"
        client_certificate          = "${var.replica_configuration_client_certificate}"
        client_key                  = "${var.replica_configuration_client_key}"
        connect_retry_interval      = "${var.replica_configuration_connect_retry_interval}"
        dump_file_path              = "${var.replica_configuration_dump_file_path}"
        failover_target             = "${var.replica_configuration_failover_target}"
        master_heartbeat_period     = "${var.replica_configuration_master_heartbeat_period}"
        username                    = "${var.replica_configuration_username}"
        password                    = "${var.replica_configuration_password}"
        verify_server_certificate   = "${var.replica_configuration_verify_server_certificate}"
    }

    settings {
        tier                        = "${lookup(var.settings_tier, var.database_version)}"
        activation_policy           = "${var.settings_activation_policy}"
        authorized_gae_applications = ["${var.settings_authorized_gae_applications}"]
        availability_type           = "${var.settings_availability_type}"
        crash_safe_replication      = "${var.settings_crash_safe_replication}"
        replication_type            = "${var.settings_replication_type}"
        pricing_plan                = "${var.settings_pricing_plan}"

        user_labels {
            name            = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
            environment     = "${lower(var.environment)}"
            orchestration   = "${lower(var.orchestration)}"
        }

        database_flags  = ["${var.settings_database_flags}"]

        backup_configuration {
            binary_log_enabled  = "${var.settings_backup_configuration_binary_log_enabled}"
            enabled             = "${var.settings_backup_configuration_enabled}"
            start_time          = "${var.settings_backup_configuration_start_time}"
        }

        ip_configuration {
            ipv4_enabled    = "${var.settings_ip_configuration_ipv4_enabled}"
            require_ssl     = "${var.settings_ip_configuration_require_ssl}"

            authorized_networks {
                expiration_time = "${var.settings_authorized_networks_expiration_time}"
                name            = "${var.settings_authorized_networks_name}"
                value           = "${var.settings_authorized_networks_value}"
            }
        }

        location_preference {
            follow_gae_application  = "${var.settings_location_preference_follow_gae_application}"
            zone                    = "${var.settings_location_preference_zone}"
        }

        maintenance_window = []

    }

    timeouts {
        create  = "${var.timeouts_create}"
        update  = "${var.timeouts_update}"
        delete  = "${var.timeouts_delete}"
    }

    lifecycle {
        ignore_changes = []
        create_before_destroy = true
    }
}

resource "google_sql_database_instance" "sql_database_instance_postgres_replication" {
    count                            = "${var.database_version =="POSTGRES_9_6" && var.enable_replication ? var.count_sql_database_instance : 0}"

    name                             = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
    project                          = "${var.project}"
    database_version                 = "${var.database_version}"
    region                           = "${lookup(var.region, var.database_version)}"

    master_instance_name             = "${var.master_instance_name}"

    replica_configuration {
        ca_certificate              = "${var.replica_configuration_ca_certificate}"
        client_certificate          = "${var.replica_configuration_client_certificate}"
        client_key                  = "${var.replica_configuration_client_key}"
        connect_retry_interval      = "${var.replica_configuration_connect_retry_interval}"
        dump_file_path              = "${var.replica_configuration_dump_file_path}"
        failover_target             = "${var.replica_configuration_failover_target}"
        master_heartbeat_period     = "${var.replica_configuration_master_heartbeat_period}"
        username                    = "${var.replica_configuration_username}"
        password                    = "${var.replica_configuration_password}"
        verify_server_certificate   = "${var.replica_configuration_verify_server_certificate}"
    }

    settings {
        tier                        = "${lookup(var.settings_tier, var.database_version)}"
        activation_policy           = "${var.settings_activation_policy}"
        authorized_gae_applications = ["${var.settings_authorized_gae_applications}"]
        availability_type           = "${var.settings_availability_type}"
        crash_safe_replication      = "${var.settings_crash_safe_replication}"
        replication_type            = "${var.settings_replication_type}"

        disk_autoresize             = "${var.settings_disk_autoresize}"
        disk_size                   = "${var.database_version =="POSTGRES_9_6" ? var.settings_disk_size : 0}"
        disk_type                   = "${var.settings_disk_type}"

        user_labels {
            name            = "${lower(var.name)}-sd-instance-${lower(var.environment)}-${count.index+1}"
            environment     = "${lower(var.environment)}"
            orchestration   = "${lower(var.orchestration)}"
        }

        database_flags  = ["${var.settings_database_flags}"]

        backup_configuration {
            binary_log_enabled  = "${var.settings_backup_configuration_binary_log_enabled}"
            enabled             = "${var.settings_backup_configuration_enabled}"
            start_time          = "${var.settings_backup_configuration_start_time}"
        }

        ip_configuration {
            ipv4_enabled    = "${var.settings_ip_configuration_ipv4_enabled}"
            require_ssl     = "${var.settings_ip_configuration_require_ssl}"

            authorized_networks {
                expiration_time = "${var.settings_authorized_networks_expiration_time}"
                name            = "${var.settings_authorized_networks_name}"
                value           = "${var.settings_authorized_networks_value}"
            }
        }

        location_preference {
            follow_gae_application  = "${var.settings_location_preference_follow_gae_application}"
            zone                    = "${var.settings_location_preference_zone}"
        }

        maintenance_window = []

    }

    timeouts {
        create  = "${var.timeouts_create}"
        update  = "${var.timeouts_update}"
        delete  = "${var.timeouts_delete}"
    }

    lifecycle {
        ignore_changes = []
        create_before_destroy = true
    }
}

#---------------------------------------------------
# Create google sql database
#---------------------------------------------------
resource "google_sql_database" "sql_database" {
    count       = "${var.enable_sql_database_creating && length(var.sql_database_instance_name) >0 ? 1 : 0}"  

    name        = "${var.sql_database_name}"
    project     = "${var.project}"
    instance    = "${var.sql_database_instance_name}"
    charset     = "${var.sql_database_charset}"
    collation   = "${var.sql_database_collation}"
}

#---------------------------------------------------
# Create google sql user
#---------------------------------------------------
resource "google_sql_user" "sql_user" {
    count       = "${var.enable_sql_user_creating && length(var.sql_database_instance_name) >0 ? 1 : 0}"

    name        = "${var.sql_user_name}"
    project     = "${var.project}"
    instance    = "${var.sql_database_instance_name}"
    host        = "${var.sql_user_host}"
    password    = "${var.sql_user_password}"
}

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

$ 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 "orchestration" {
    description = "Type of orchestration"
    default     = "Terraform"
}

variable "count_sql_database_instance" {
    description = "Counter, which count how many nodes which will be created"
    default     = "1"
}

variable "database_version" {
    description = "(Optional, Default: MYSQL_5_6) The MySQL version to use. Can be MYSQL_5_6, MYSQL_5_7 or POSTGRES_9_6 for second-generation instances, or MYSQL_5_5 or MYSQL_5_6 for first-generation instances. See Second Generation Capabilities for more information. POSTGRES_9_6 support is in Beta."
    default     = "MYSQL_5_6"
}

variable "region" {
    description = "(Required) The region the instance will sit in. Note, first-generation Cloud SQL instance regions do not line up with the Google Compute Engine (GCE) regions, and Cloud SQL is not available in all regions - choose from one of the options listed here. A valid region must be provided to use this resource. If a region is not provided in the resource definition, the provider region will be used instead, but this will be an apply-time error for all first-generation instances and for second-generation instances if the provider region is not supported with Cloud SQL. If you choose not to provide the region argument for this resource, make sure you understand this."
    type        = "map"
    default     = {
        MYSQL_5_6       = "us-east1"
        MYSQL_5_7       = "us-east1"
        POSTGRES_9_6    = "us-east1"
    }
}

variable "timeouts_create" {
    description = "Time to create redis node. Default is 6 minutes. Valid units of time are s, m, h."
    default     = "6m"
}

variable "timeouts_update" {
    description = "Time to update redis node. Default is 4 minutes. Valid units of time are s, m, h."
    default     = "4m"
}

variable "timeouts_delete" {
    description = "Time to delete redis node. Default is 4 minutes. Valid units of time are s, m, h."
    default     = "4m"
}

variable "master_instance_name" { 
    description = "(Optional) The name of the instance that will act as the master in the replication setup. Note, this requires the master to have binary_log_enabled set, as well as existing backups."
    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     = "terraform-2018"
}

variable "replica_configuration_ca_certificate" {
    description = "(Optional) PEM representation of the trusted CA's x509 certificate."
    default     = ""
}

variable "replica_configuration_client_certificate" {
    description = "(Optional) PEM representation of the slave's x509 certificate."
    default     = ""
}

variable "replica_configuration_client_key" {
    description = "(Optional) PEM representation of the slave's private key. The corresponding public key in encoded in the client_certificate."
    default     = ""
}

variable "replica_configuration_connect_retry_interval" {
    description = "(Optional, Default: 60) The number of seconds between connect retries."
    default     = "60"
}

variable "replica_configuration_dump_file_path" {
    description = "(Optional) Path to a SQL file in GCS from which slave instances are created. Format is gs://bucket/filename."
    default     = ""
}

variable "replica_configuration_failover_target" {
    description = "(Optional) Specifies if the replica is the failover target. If the field is set to true the replica will be designated as a failover replica. If the master instance fails, the replica instance will be promoted as the new master instance."
    default     = ""
}

variable "replica_configuration_master_heartbeat_period" {
    description = "(Optional) Time in ms between replication heartbeats."
    default     = "60000"
}

variable "replica_configuration_password" {
    description = "(Optional) Password for the replication connection."
    default     = ""
}

variable "replica_configuration_username" {
    description = "(Optional) Username for replication connection."
    default     = ""
}

variable "replica_configuration_verify_server_certificate" {
    description = "(Optional) True if the master's common name value is checked during the SSL handshake."
    default     = ""
}

variable "settings_tier" {
    description = "(Required) The machine tier (First Generation) or type (Second Generation) to use. See tiers for more details and supported versions. Postgres supports only shared-core machine types such as db-f1-micro, and custom machine types such as db-custom-2-13312. See the Custom Machine Type Documentation to learn about specifying custom machine types."
    type        = "map"
    default     = {
        MYSQL_5_6       = "D0"
        MYSQL_5_7       = "D0"
        POSTGRES_9_6    = "db-f1-micro"
    }
}

variable "settings_activation_policy" {
    description = "(Optional) This specifies when the instance should be active. Can be either ALWAYS, NEVER or ON_DEMAND."
    default     = "ALWAYS"
}

variable "settings_authorized_gae_applications" {
    description = "(Optional) A list of Google App Engine (GAE) project names that are allowed to access this instance."
    default     = []
}

variable "settings_availability_type" {
    description = "(Optional) This specifies whether a PostgreSQL instance should be set up for high availability (REGIONAL) or single zone (ZONAL)."
    default     = "REGIONAL"
}

variable "settings_crash_safe_replication" {
    description = "(Optional) Specific to read instances, indicates when crash-safe replication flags are enabled."
    default     = ""
}

variable "settings_disk_autoresize" {
    description = "(Optional, Second Generation, Default: true) Configuration to increase storage size automatically."
    default     = "true"
}

variable "settings_disk_size" {
    description = "(Optional, Second Generation, Default: 10) The size of data disk, in GB. Size of a running instance cannot be reduced but can be increased."
    default     = "10"
}

variable "settings_disk_type" {
    description = "(Optional, Second Generation, Default: PD_SSD) The type of data disk: PD_SSD or PD_HDD."
    default     = "PD_SSD"
}

variable "settings_pricing_plan" {
    description = "(Optional, First Generation) Pricing plan for this instance, can be one of PER_USE or PACKAGE."
    default     = "PER_USE"
}

variable "settings_replication_type" {
    description = "(Optional) Replication type for this instance, can be one of ASYNCHRONOUS or SYNCHRONOUS."
    default     = "SYNCHRONOUS"
}

variable "settings_backup_configuration_binary_log_enabled" {
    description = "(Optional) True if binary logging is enabled. If logging is false, this must be as well."
    default     = "false"
}

variable "settings_backup_configuration_enabled" {
    description = "(Optional) True if backup configuration is enabled."
    default     = "true"
}

variable "settings_backup_configuration_start_time" {
    description = "(Optional) HH:MM format time indicating when backup configuration starts."
    default     = "23:00"
}

variable "settings_ip_configuration_ipv4_enabled" {
    description = "(Optional) True if the instance should be assigned an IP address. The IPv4 address cannot be disabled for Second Generation instances."
    default     = "true"
}

variable "settings_ip_configuration_require_ssl" {
    description = "(Optional) True if mysqld should default to REQUIRE X509 for users connecting over IP."
    default     = ""
}

variable "settings_authorized_networks_expiration_time" {
    description = "(Optional) The RFC 3339 formatted date time string indicating when this whitelist expires."
    default     = ""
}

variable "settings_authorized_networks_name" {
    description = "(Optional) A name for this whitelist entry."
    default     = "allow_from_all"
}

variable "settings_authorized_networks_value" {
    description = "(Optional) A CIDR notation IPv4 or IPv6 address that is allowed to access this instance. Must be set even if other two attributes are not for the whitelist to become active."
    default     = "0.0.0.0/0"
}

variable "settings_location_preference_follow_gae_application" {
    description = "(Optional) A GAE application whose zone to remain in. Must be in the same region as this instance."
    default     = ""
}

variable "settings_location_preference_zone" {
    description = "(Optional) The preferred compute engine zone."
    default     = ""
}

variable "settings_maintenance_window" {
    description = "Set maintenance window. Need to set flags (day (1-7), start from Monday; hour (0-23); update_track ((Optional) Receive updates earlier (canary) or later (stable)))."
    default     = []
}

variable "settings_database_flags" {
    description = "Set database flags"
    default     = []
}

variable "enable_replication" {
    description = "Enable replication"
    default     = "false"
}

variable "enable_sql_database_creating" {
    description = "Enable sql DB creating"
    default     = "true"
}

variable "sql_database_name" {
    description = "(Required) The name of the database."
    default     = "test_db"
}

variable "sql_database_instance_name" {
    description = "(Required) The name of containing instance."
    default     = ""
}

variable "sql_database_charset" {
    description = "(Optional) The charset value. See MySQL's Supported Character Sets and Collations and Postgres' Character Set Support for more details and supported values. Postgres databases are in Beta, and have limited charset support; they only support a value of UTF8 at creation time."
    default     = ""
}

variable "sql_database_collation" {
    description = "(Optional) The collation value. See MySQL's Supported Character Sets and Collations and Postgres' Collation Support for more details and supported values. Postgres databases are in Beta, and have limited collation support; they only support a value of en_US.UTF8 at creation time."
    default     = ""
}

variable "enable_sql_user_creating" {
    description = "Enable sql user"
    default     = "true"
}

variable "sql_user_name" {
    description = "(Required) The name of the user. Changing this forces a new resource to be created."
    default     = "test_user"
}

variable "sql_user_host" {
    description = "(Optional) The host the user can connect from. This is only supported for MySQL instances. Don't set this field for PostgreSQL instances. Can be an IP address. Changing this forces a new resource to be created."
    default     = ""
}

variable "sql_user_password" {
    description = "(Optional) The password for the user. Can be updated."
    default     = ""
}

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

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

$ vim outputs.tf

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

#--------------------------------------------------------------------------------
# MySQL
#--------------------------------------------------------------------------------
output "sql_database_instance_mysql_name" {
    description = "Name of sql database instance for MYSQL"
    value       = "${google_sql_database_instance.sql_database_instance_mysql.*.name}"
}

output "sql_database_instance_mysql_replication_name" {
    description = "Name of sql database instance for MYSQL replica"
    value       = "${google_sql_database_instance.sql_database_instance_mysql_replication.*.name}"
}

output "sql_database_instance_mysql_self_link" {
    description = "self_link of sql database instance for MYSQL"
    value       = "${google_sql_database_instance.sql_database_instance_mysql.*.self_link}"
}

output "sql_database_instance_mysql_replication_self_link" {
    description = "self_link of sql database instance for mysql replica"
    value       = "${google_sql_database_instance.sql_database_instance_mysql_replication.*.self_link}"
}

output "sql_database_instance_mysql_connection_name" {
    description = "connection_name of sql database instance for MYSQL"
    value       = "${google_sql_database_instance.sql_database_instance_mysql.*.connection_name}"
}

output "sql_database_instance_mysql_replication_connection_name" {
    description = "connection_name of sql database instance for mysql replica"
    value       = "${google_sql_database_instance.sql_database_instance_mysql_replication.*.connection_name}"
}
#--------------------------------------------------------------------------------
# PostGres
#--------------------------------------------------------------------------------

output "sql_database_instance_postgres_name" {
    description = "Name of sql database instance for postgres"
    value       = "${google_sql_database_instance.sql_database_instance_postgres.*.name}"
}

output "sql_database_instance_postgres_replication_name" {
    description = "Name of sql database instance for postgres replica"
    value       = "${google_sql_database_instance.sql_database_instance_postgres_replication.*.name}"
}

output "sql_database_instance_postgres_self_link" {
    description = "self_link of sql database instance for postgres"
    value       = "${google_sql_database_instance.sql_database_instance_postgres.*.self_link}"
}

output "sql_database_instance_postgres_replication_self_link" {
    description = "self_link of sql database instance for postgres replica"
    value       = "${google_sql_database_instance.sql_database_instance_postgres_replication.*.self_link}"
}

output "sql_database_instance_postgres_connection_name" {
    description = "connection_name of sql database instance for postgres"
    value       = "${google_sql_database_instance.sql_database_instance_postgres.*.connection_name}"
}       

output "sql_database_instance_postgres_replication_connection_name" {
    description = "connection_nameof sql database instance for postgres replica"
    value       = "${google_sql_database_instance.sql_database_instance_postgres_replication.*.connection_name}"
}

#--------------------------------------------------------------------------------
# DB
#--------------------------------------------------------------------------------
output "sql_database_name" {
    description = "Name of sql database"
    value       = "${google_sql_database.sql_database.*.name}"
}

output "sql_database_self_link" {
    description = "self_link for DB"
    value       = "${google_sql_database.sql_database.*.self_link}"
}

#--------------------------------------------------------------------------------
# User
#--------------------------------------------------------------------------------
output "sql_user_name" {
    description = "User"
    value       = "${google_sql_user.sql_user.*.name}"
}

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

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

    #MySQL without replication
    enable_replication                  = false
    database_version                    = "MYSQL_5_6"
    settings_database_flags             = [
        {    
            name    = "skip_show_database"
            value   = "on"
        }
    ]
    #settings_maintenance_window         = []
    #
    #MySQL with replication
    #enable_replication                  = true
    #database_version                    = "MYSQL_5_6"    
    #settings_database_flags             = [
    #    {
    #        name    = "skip_show_database"
    #        value   = "on"
    #    }
    #]
    #settings_maintenance_window         = []
    #
    # Postgres without replication
    #enable_replication                  = false
    #database_version                    = "POSTGRES_9_6"
    #settings_database_flags             = []
    #settings_maintenance_window         = [
    #    {
    #        day             = "6"
    #        hour            = "23"
    #        update_track    = ""
    #    }
    #]
    # Postgres with replication
    #enable_replication                  = true
    #database_version                    = "POSTGRES_9_6"
    #settings_database_flags             = []
    #settings_maintenance_window         = [
    #    {
    #        day             = "6"
    #        hour            = "23"
    #        update_track    = ""
    #    }
    #]

    # DB
    sql_database_instance_name           = "test-sd-instance-stage-1"
    enable_sql_database_creating         = true
    enable_sql_user_creating             = 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 (redis instance) и Terraform в Unix/Linux» завершена.

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

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

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