Облачная экосистема - Евгений Сергеевич Штольц 18 стр.


Terraform не возник на пустом месте, а стал продолжением длинной истории появления программных продуктов конфигурирования и управления серверной инфраструктуры, перечислю в прядке появления и перехода:

** CFN;

** Pupet;

** Chef;

** Ansible;

** Облачные AWS API, Kubernetes API;

* IasC: Terraform не зависит от типа инфраструктуры (поддерживает более 120 провайдеров, среди которых не только облака), в отличии от ведровых аналогов, поддерживающих только себя: CloudFormation для Amazon WEB Service, Azure Resource Manager для Microsoft Azure, Google Cloud Deployment Manager от Google Cloud Engine.

CloudFormation создан Amazon и предназначен для негоже, также полностью интегрирован в CI/CD его инфраструктуры размещением на AWS S3, что усложняет версионирование через GIT. Мы рассмотрим платформой независимый Terraform: синтаксис базовой функциональности един, а специфичная подключается через сущности Провайдеры (https://www.terraform.io/docs/providers/index. html). Terraform один бинарный файл, поддерживает огромное количество провайдеров, и, конечно же, таких как AWS и GCE. Terraform, как и большинство продуктов от Hashicorp написаны на Go и представляют из себя один бинарный исполняемый файл, не требует установки, достаточно просто скачать его в папку Linux:

(agile-aleph-203917)$ wget https://releases.hashicorp.com/terraform/0.11.13/terraform_0.11.13_linux_amd64.zip

(agile-aleph-203917)$ unzip terraform_0.11.13_linux_amd64.zip -d .

(agile-aleph-203917)$ rm -f terraform_0.11.13_linux_amd64.zip

(agile-aleph-203917)$ ./terraform version

Terraform v0.11.13

Он поддерживает разбиение на модули, которые можно написать самому или использовать готовые (https://registry.terraform.io/browse?offset=27&provider=google). Для оркестрации и поддержки изменений в зависимостях можно воспользоваться Terragrunt (https://davidbegin.github.io/terragrunt/), например:

terragrant = {

terraform {

source = "terraform-aws-modules/"

}

dependencies {

path = ["..network"]

}

}

name = ""

ami = ""

instance_type = "t3.large"

Единая семантика для разных провайдеров (AWS, GCE, Яндекс. Облако и многих других) конфигураций, что позволяет создать трансцендентную инфраструктуру, например, постоянные нагруженные сервисы расположить для экономии на собственных мощностях, а переменно нагружены (например, в период акций) в публичных облаках. Благодаря тому, что управление декларативно и может быть описана файлами (IaC, инфраструктура как код), создание инфраструктуры можно добавить в pipeline CI/CD (разработка, тестирование, доставка, всё автоматически и с контролем версий). Без CI/CD поддерживается блокировка файла конфигурации для предотвращения конкурентного его редактирования при совместной работе. инфраструктура создаётся не скриптом, а приводится в соответствие с конфигурацией, которая декларативна и не может содержать логики, хотя, можно и внедрить в неё BASH- скрипты и использовать Conditions (термальный оператор) для разных окружений.

Terraform будет читать все файлы в текущем каталоге с расширением .tf в Hachiсort Configuraiton Language (HCL) формате или .tf. json в JSON формате. Часто, вместо одного файл его разделяют на несколько, как минимум на два: первый содержащий конфигурацию, второй приватные данные, вынесенные в переменными.

Для демонстрации возможностей Terraform мы создадим репозиторий GitHub из-за его простоты авторизации и API. Сперва получим токен, сгенерирована в WEB-интерфейсе: SettingsDeveloper sittings -> Personal access token > Generate new token и установив разрешения. Ничего не будем создавать, просто проверим подключение:

(agile-aleph-203917)$ ls *.tf

main.tf variables.tf


$ cat variables.tf

variable "github_token" {

default = "630bc9696d0b2f4ce164b1cabb118eaaa1909838"

}

$ cat main.tf

provider "github" {

token = "${var.github_token}"

}


(agile-aleph-203917)$ ./terraform init

(agile-aleph-203917)$ ./terraform apply


Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Теперь, создадим управляющий аккаунт Settings > Organizations > New organization > Create organization.. Используя: API Terraform по создания репозитория www.terraform.io/docs/providers/github/r/repository. html добавим в конфиг описание репозитория:

(agile-aleph-203917)$ cat main.tf

provider "github" {

token = "${var.github_token}"

}

resource "github_repository" "terraform_repo" {

name = "terraform-repo"

description = "my terraform repo"

auto_init = true

}

Теперь осталось применить, посмотреть с планом создания репозитория, согласиться с ним:

(agile-aleph-203917)$ ./terraform apply

provider.github.organization

The GitHub organization name to manage.


Enter a value: essch2


An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

+ create


Terraform will perform the following actions:


+ github_repository.terraform_repo

id:<computed>

allow_merge_commit: "true"

allow_rebase_merge: "true"

allow_squash_merge: "true"

archived: "false"

auto_init: "true"

default_branch: <computed>

description: "my terraform repo"

etag: <computed>

full_name: <computed>

git_clone_url: <computed>

html _url: <computed>

http_clone_url: <computed>

provider.github.organization

The GitHub organization name to manage.


Enter a value: essch2


An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

+ create


Terraform will perform the following actions:


+ github_repository.terraform_repo

id:<computed>

allow_merge_commit: "true"

allow_rebase_merge: "true"

allow_squash_merge: "true"

archived: "false"

auto_init: "true"

default_branch: <computed>

description: "my terraform repo"

etag: <computed>

full_name: <computed>

git_clone_url: <computed>

html _url: <computed>

http_clone_url: <computed>

name: "terraform-repo"

ssh_clone_url: <computed>

svn_url: <computed>


Plan: 1 to add, 0 to change, 0 to destroy.


Do you want to perform these actions?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.


Enter a value: yes


github_repository.terraform_repo: Creating

allow_merge_commit: "" => "true"

allow_rebase_merge: "" => "true"

allow_squash_merge: "" => "true"

archived: "" => "false"

auto_init: "" => "true"

default_branch: "" => "<computed>"

description: "" => "my terraform repo"

etag: "" => "<computed>"

full_name: "" => "<computed>"

git_clone_url: "" => "<computed>"

html_url: "" => "<computed>"

http_clone_url: "" => "<computed>"

name: "" => "terraform-repo"

ssh_clone_url: "" => "<computed>"

svn_url: "" => "<computed>"

github_repository.terraform_repo: Creation complete after 4s (ID: terraform-repo)


Apply complete! Resources: 1 added, 0 changed, 0 destroyed

Теперь можно наблюдать пустой репозиторий terraform-repo в WEB-интерфейсе. При повторном применении репозиторий не будет создан, так как Terraform применяет только изменения, который не было:

(agile-aleph-203917)$ ./terraform apply

provider.github.organization

The GITHub organization name to manage.

Enter a value: essch2

github_repository.terraform_repo: Refreshing state (ID: terraform-repo)

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

А вот если я изменю название, то Terraform постарается применить изменения название через удаление и создание нового с актуальным названием. Важно заметить, что любые данные, которые мы бы запушили бы в этот репозиторий после смены названия были бы удалены. Для проверки, как будет производиться обновления можно предварительно спросить перечень производимых действий командой ./Terraform plane. И так, приступим:

(agile-aleph-203917)$ cat main.tf

provider "github" {

token = "${var.github_token}"

}

resource "github_repository" "terraform_repo" {

name = "terraform-repo2"

description = "my terraform repo"

auto_init = true

}


(agile-aleph-203917)$ ./terraform plan

provider.github.organization

The GITHub organization name to manage.


Enter a value: essch


Refreshing Terraform state in-memory prior to plan

The refreshed state will be used to calculate this plan, but will not be

persisted to local or remote state storage.


github_repository.terraform_repo: Refreshing state (ID: terraform-repo)


-


An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

+ create


Terraform will perform the following actions:


+ github_repository.terraform_repo

id:<computed>

allow_merge_commit: "true"

allow_rebase_merge: "true"

allow_squash_merge: "true"

archived: "false"

auto_init: "true"

default_branch: <computed>

description: "my terraform repo"

etag: <computed>

full_name: <computed>

git_clone_url: <computed>

html_url: <computed>

http_clone_url: <computed>

name: "terraform-repo2"

ssh_clone_url: <computed>

svn_url: <computed>


"terraform apply" is subsequently run.

esschtolts@cloudshell:~/terraform (agile-aleph-203917)$ ./terraform apply

provider.github.organization

The GITHub organization name to manage.

Enter a value: essch2

github_repository.terraform_repo: Refreshing state (ID: terraform-repo)

An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

/+ destroy and then create replacement

Terraform will perform the following actions:

/+ github_repository.terraform_repo (new resource required)

id:"terraform-repo" => <computed> (forces new resource)

allow_merge_commit: "true" => "true"

allow_rebase_merge: "true" => "true"

allow_squash_merge: "true" => "true"

archived: "false" => "false"

auto_init: "true" => "true"

default_branch: "master" => <computed>

description: "my terraform repo" => "my terraform repo"

etag: "W/\"a92e0b300d8c8d2c869e5f271da6c2ab\"" => <computed>

full_name: "essch2/terraform-repo" => <computed>

git_clone_url: "git://github.com/essch2/terraform-repo.git" => <computed>

html_url: "https://github.com/essch2/terraform-repo" => <computed>

http_clone_url: "https://github.com/essch2/terraform-repo.git" => <computed>

name: "terraform-repo" => "terraform-repo2" (forces new resource)

ssh_clone_url: "git@github.com:essch2/terraform-repo.git" => <computed>

svn_url: "https://github.com/essch2/terraform-repo" => <computed>

Plan: 1 to add, 0 to change, 1 to destroy.

Do you want to perform these actions?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.

Enter a value: yes

github_repository.terraform_repo: Destroying (ID: terraform-repo)

github_repository.terraform_repo: Destruction complete after 0s

github_repository.terraform_repo: Creating

allow_merge_commit: "" => "true"

allow_rebase_merge: "" => "true"

allow_squash_merge: "" => "true"

archived: "" => "false"

auto_init: "" => "true"

default_branch: "" => "<computed>"

description: "" => "my terraform repo"

etag: "" => "<computed>"

full_name: "" => "<computed>"

git_clone_url: "" => "<computed>"

html_url: "" => "<computed>"

http_clone_url: "" => "<computed>"

name: "" => "terraform-repo2"

ssh_clone_url: "" => "<computed>"

svn_url: "" => "<computed>"

github_repository.terraform_repo: Creation complete after 5s (ID: terraform-repo2)

Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

Назад Дальше