Рубрики
Uncategorized

Начало работы с террафом на AWS

Сначала представляется подавляющим, но в конце очень легко начать работать управление вашей инфраструктурой с использованием террафора. Помечено террафом, AWS, DEVOPS.

Сначала он подавляет, чтобы начать управлять инфраструктурой с использованием террафора. Это также похоже на излишки, если вы не большая компания с командой DevOps но в конце вы поблагодарите себе за это Но это действительно проще, чем вы думаете.

Сначала вам нужно установить террафом:

brew install terraform

Чем создайте каталог, где вы будете хранить свои файлы:

mkdir terraform
cd terraform

И начните создавать свою инфраструктуру.

Давайте начнем с создания простого файла init.tf:

provider "aws" {
  region = "us-east-1"
}

Для этого вам нужно правильно настроить AWS-CLI С учетными данными, сохраненными в ~/.aws/учетные данные файл. Это сэкономит вас от размещения ваших секретов в файлы Terraform и позволить вам совершить все для контроля источника.

Другие полезные варианты:

  • Профиль — если у вас есть несколько профилей в вас .aws/реквизиты для входа
  • shared_credentials_file — Если вы хотите использовать учетные данные файл

Больше о том: https://www.terraform.io/docs/providers/aws/index.html#shared-credentials-file

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.56.0...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.aws: version = "~> 2.56"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

В качестве примера мы создадим ведро S3. Для того, чтобы сделать это, мы создадим файл S3.TF:

resource "aws_s3_bucket" "private-backups" {
  bucket = "private-backups"
  acl = "private"
  tags = {
    product = "infra"
  }
}

Как вы можете видеть, это довольно просто и самоопределение.

Теперь мы можем увидеть, что будет выполнено, если мы применим команду, выполнив:

tf plan

После подтверждения мы можем просто подать заявку:

tf apply

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:

  # aws_s3_bucket.private-backups will be created
  + resource "aws_s3_bucket" "private-backups" {
      + acceleration_status         = (known after apply)
      + acl                         = "private"
      + arn                         = (known after apply)
      + bucket                      = "private-backups"
      + bucket_domain_name          = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + tags                        = {
          + "product" = "infra"
        }
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)

      + versioning {
          + enabled    = (known after apply)
          + mfa_delete = (known after apply)
        }
    }

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

aws_s3_bucket.private-backups: Creating...
aws_s3_bucket.private-backups: Still creating... [10s elapsed]
aws_s3_bucket.private-backups: Still creating... [20s elapsed]
aws_s3_bucket.private-backups: Still creating... [30s elapsed]
aws_s3_bucket.private-backups: Creation complete after 30s [id=private-backups]

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

Если мы сейчас выполним план, он просто скажет, что ничего не нужно изменить:

tf plan
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.

aws_s3_bucket.private-backups: Refreshing state... [id=private-backups]

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.

Следующим шагом будет представить файлы на некоторое управление исходным управлением, поэтому мы отслеживаем изменения.

Оригинал: «https://dev.to/digitaldisorder/getting-started-with-terraform-on-aws-2eip»