
Работа с Google Cloud Platform (cloudbuild_trigger) и Terraform в Unix/Linux
Google Cloud Platrorm — это платформа вида «инфраструктура как сервис» (IaaS), позволяющая клиентам создавать, тестировать и развертывать собственные приложения на инфраструктуре Google, в высокопроизводительных виртуальных машинах.
Google Compute Engine предоставляет виртуальные машины, работающие в инновационных центрах обработки данных Google и всемирной сети.
Google cloudbuild_trigger — инструктирует Container Builder автоматически создавать имедж всякий раз, когда происходят изменения в репозитории. Вы можете установить триггер для повторной сборки образов.
Установка 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
Генерация документации для 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 (cloudbuild_trigger) и 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/cloudbuild_trigger
Переходим в нее:
$ cd modules/cloudbuild_trigger
Открываем файл:
$ vim cloudbuild_trigger.tf
В данный файл, вставляем:
#--------------------------------------------------- # Create cloudbuild trigger #--------------------------------------------------- resource "google_cloudbuild_trigger" "cloudbuild_trigger_filename" { count = "${var.enable_cloudbuild_trigger_filename && length(var.filename) >0 ? 1 : 0}" project = "${var.project}" description = "${var.description}" trigger_template { branch_name = "${var.trigger_template_branch_name}" project = "${var.trigger_template_project}" repo_name = "${var.trigger_template_repo_name}" commit_sha = "${var.trigger_template_commit_sha}" dir = "${var.trigger_template_dir}" tag_name = "${var.trigger_template_tag_name}" } filename = "${var.filename}" lifecycle { ignore_changes = [] create_before_destroy = true } } resource "google_cloudbuild_trigger" "cloudbuild_trigger" { count = "${!var.enable_cloudbuild_trigger_filename && length(var.trigger_template_branch_name) >0 ? 1 : 0}" project = "${var.project}" description = "${var.description}" trigger_template { branch_name = "${var.trigger_template_branch_name}" project = "${var.trigger_template_project}" repo_name = "${var.trigger_template_repo_name}" commit_sha = "${var.trigger_template_commit_sha}" dir = "${var.trigger_template_dir}" tag_name = "${var.trigger_template_tag_name}" } build { images = ["${var.build_images}"] step { name = "${var.build_step_name}" args = "${var.build_step_args}" } tags = ["${var.build_tags}"] } 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 "orchestration" { description = "Type of orchestration" default = "Terraform" } variable "enable_cloudbuild_trigger_filename" { description = "Enable cloudbuild trigger filename. Default - true. If not, will use biult inside structure of module" default = "true" } variable "project" { description = "Project name" default = "" } variable "description" { description = "(Optional) A brief description of this resource." default = "" } variable "trigger_template_branch_name" { description = "(Optional) Name of the branch to build." default = "" } variable "trigger_template_project" { description = "(Optional) ID of the project that owns the Cloud Source Repository." default = "" } variable "trigger_template_repo_name" { description = "(Optional) Name of the Cloud Source Repository." default = "" } variable "trigger_template_commit_sha" { description = "(Optional) Explicit commit SHA to build." default = "" } variable "trigger_template_dir" { description = "(Optional) Directory, relative to the source root, in which to run the build. This must be a relative path. If a step's dir is specified and is an absolute path, this value is ignored for that step's execution." default = "" } variable "trigger_template_tag_name" { description = "(Optional) Name of the tag to build." default = "" } variable "filename" { description = "(Optional) Specify the path to a Cloud Build configuration file in the Git repo. This is mutually exclusive with build. This is typically cloudbuild.yaml however it can be specified by the user." default = "" } variable "build_images" { description = "(Optional) A list of images to be pushed upon the successful completion of all build steps. Ex: 'gcr.io/$PROJECT_ID/$REPO_NAME:$COMMIT_SHA'" default = [] } variable "build_step_name" { description = "(Optional) The name of the container image that will run this particular build step. If the image is available in the host's Docker daemon's cache, it will be run directly. If not, the host will attempt to pull the image first, using the builder service account's credentials if necessary. The Docker daemon's cache will already have the latest versions of all of the officially supported build steps (https://github.com/GoogleCloudPlatform/cloud-builders). The Docker daemon will also have cached many of the layers for some popular images, like 'ubuntu', 'debian', but they will be refreshed at the time you attempt to use them. If you built an image in a previous build step, it will be stored in the host's Docker daemon's cache and is available to use as the name for a later build step." default = "" } variable "build_step_args" { description = "(Optional) A list of arguments that will be presented to the step when it is started. If the image used to run the step's container has an entrypoint, the args are used as arguments to that entrypoint. If the image does not define an entrypoint, the first element in args is used as the entrypoint, and the remainder will be used as arguments." default = "" } variable "build_tags" { description = "(Optional) Tags for annotation of a build. These are not docker tags" default = [] }
Собственно в этом файле храняться все переменные. Спасибо кэп!
Открываем последний файл:
$ vim outputs.tf
И в него вставить нужно следующие строки:
output "cloudbuild_trigger_id" { description = "ID" value = "${google_cloudbuild_trigger.cloudbuild_trigger.*.id}" } output "cloudbuild_trigger_filename_id" { description = "ID" value = "${google_cloudbuild_trigger.cloudbuild_trigger_filename.*.id}" }
Переходим теперь в папку google_cloud_platform/examples и создадим еще одну папку для проверки написанного чуда:
$ mkdir cloudbuild_trigger && 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 "cloudbuild_trigger" { source = "../../modules/cloudbuild_trigger" name = "TEST" #enable_cloudbuild_trigger_filename = true #filename = "" # enable_cloudbuild_trigger_filename = false trigger_template_branch_name = "master" }
Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:
$ 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 (cloudbuild_trigger) и Terraform в Unix/Linux» завершена.