Начало работы: установка terraform в windows с помощью azure powershell

Нужно ли развертывание в облаке?

Вы, конечно же, можете сделать свой собственный AMI вместо использования типовых пустых, и, следовательно, пропустить полностью развертывание, но у этого способа есть фатальный недостаток. Каждое минимальнейшее изменение потребует пересоздания всего сервера. Если надо что-то поправить на базовом уровне, придется перезаливать все сервера. Это быстро надоедает в случае развертывания, установки обновлений безопасности, добавления или удаления пользователей, изменения настроек и прочих простых вещей.

Далее — если делаете свои AMI, вам все равно нужно как-то запускать развертывание, так что опять появляются такие вещи, как Ansible. Ну и опять же, я рекомендую использовать Packer вместе с Ansible.

Получается, что в большинстве случаев развертывание нужно, потому что оно — неизбежно.

»Replacing resources within a module

You may have an object that needs to be replaced with a new object for a reason
that isn’t automatically visible to Terraform, such as if a particular virtual
machine is running on degraded underlying hardware. In this case, you can use

to force Terraform to propose replacing that object.

If the object belongs to a resource within a nested module, specify the full
path to that resource including all of the nested module steps leading to it.
For example:

Copy

The above selects a declared inside a
child module declared inside your root module.

Because replacing is a very disruptive action, Terraform only allows selecting
individual resource instances. There is no syntax to force replacing all
resource instances belonging to a particular module.

3 преимущества Terraform

1. Универсальность. Инструмент поддерживают множество разных облачных провайдеров. Поэтому с помощью Terraform можно управлять инфраструктурой сразу в нескольких облаках. Помимо этого, он работает с Docker, Kubernetes, Chef и другими системами. С помощью Terraform вы можете встроить в архитектуру любое приложение на любом языке.

2. Безопасность. Без Terraform каждое ПО нужно обновлять там, где оно установлено. Таким образом, каждый сервер приобретает свою уникальную историю обновлений ПО. Незначительные различия в используемых в системе программах приводят к «конфигурационному дрифту», из-за которого возникают уязвимости для хакерских атак.

В основе Terraform лежит концепция неизменяемой инфраструктуры. Это значит, что любое обновление в коде приводит к созданию новой конфигурации. Следовательно, всё ПО можно очень легко и быстро обновлять во всей системе сразу.

3. Удобство и простота. Концепция неизменяемой инфраструктуры также сильно упрощает возврат к предыдущим версиям. С Terraform это не сложнее, чем выбрать конфигурацию из списка.

Кроме того, Terraform — это декларативный код. Для управления инфраструктурой вам нужно только указать, в каком виде она должна быть, а инструмент уже сам определяет оптимальные способы, как привести систему к этому состоянию.

Ещё один плюс Terraform — архитектуру он выстраивает через API. Не требуется никаких программ-агентов, отдельного сервера для управления конфигурациями и лишних проверок безопасности. Взаимодействие с системой идёт напрямую — это даёт практически полную свободу действий в плане оркестрации.

Реализация

  1. Создаем репозиторий для хранения конфигураций в нем (надежность, удобство).

2. Создаем .gitignore для нашего кейса конфигурации.

3. Чтобы начать использовать API, сначала нужно получить токен API.

Войдите в Hetzner Cloud Console https://console.hetzner.cloud, выберите проект, перейдите к Access→ Tokens и создайте новый токен. Обязательно скопируйте токен, потому что он вам больше не будет показан. Токен привязан к проекту, для взаимодействия с API другого проекта необходимо создать новый токен внутри проекта

4. Создаем файлы конфигураций (в формате json):

state.tf — конфигурация для бекенда где будет храниться состояние инфраструктуры. В нашем случае выбор пал на S3 bucket, так как не требует особых усилий в использовании, заранее создаем bucket на S3 и прописываем к нему доступы в файле

main.tf — файл, в котором будут определены основные конфигурации

variables.tf — файл с основными переменными

instance.tf — файл конфигурации инстанса

Файл юзер-даты user-data/instance.tpl — по сути является bash скриптом, в который можно записать действия в зависимости от задачи, в нашем случае идет:

  • Установка docker;
  • Docker-Compose;
  • и прочие настройки.

Как использовать Ansible вместе с Terraform

Возвращаемся к задаче развертывания: я нашел три способа использовать Ansible совместно с Terraform после прочтения этого обсуждения. Читайте дальше, чтобы выбрать подходящий вам.

Встроенный inventory с IP сервера

Наиболее очевидное и хакерское решение — запускать Ansible с помощью , например так:

Просто и приятно, но тут сразу же есть нюанс. запускается без ожидания запуска сервера, так что в большинстве случаев это не сработает, потому что на момент подключения еще некуда подключаться.

В качестве изящного обходного способа вы можете предварительно использовать , который будет ожидать соединения с сервером, а затем запускать .

В результате у меня получилась следующая вещь, запускающая роль «Ansible provisioner»:

Чтобы работал, вам надо иметь код для Ansible рядом с кодом для Terraform:

Встроенный inventory будет работать в большинстве случаев, кроме тех, когда необходимо иметь несколько серверов в inventory. Например, если вы устанавливаете агент Consul, вам нужен список серверов для создания файла настроек, это как правило можно найти в обычном репозитории. Но в приведенном выше способе это не сработает, поскольку у нас всего один сервер в inventory.

В любом случае, я использую такую возможность для базовых вещей, например, добавления пользователей или установки некоторых базовых пакетов.

Динамический inventory после работы Terraform

Еще одно простое решение для раскатки инфраструктуры, созданной Terraform — не связывать вместе Terraform и Ansible. Создаем инфраструктуру с помощью Terraform, а затем используем Ansible с динамическим inventory без привязки к тому, как сервера были созданы.

Так что вы сначала создаете инфраструктуру с помощью , затем запускаете , где — каталог, содержащий скрипты динамического inventory.

Это все будет шикарно работать, но есть небольшая ложка дегтя — если вам надо увеличить число серверов, не забывайте запускать Ansible после Terraform.

А это то, что я использую в дополнение к предыдущему способу.

Inventory, создаваемая из состояния Terraform

Есть еще одна интересная штука, которая, возможно, будет у вас работать — создание статического inventory из состояния Terraform.

Terraform при работе поддерживает состояние инфраструктуры, содержащее все, включая ваши сервера. При использовании local backend это состояние сохраняется в файле JSON, который можно потом легко разобрать и сконвертировать в inventory для Ansible.

Я нашел два проекта с примерами, так что вы можете их использовать, если будете работать с этим способом.

»Example Configuration

Copy

This assumes we have a bucket created called . The
Terraform state is written to the key .

Note that for the access credentials we recommend using a
.

S3 Bucket Permissions

Terraform will need the following AWS IAM permissions on
the target backend bucket:

  • on
  • on
  • on
  • on

This is seen in the following AWS IAM Statement:

Copy

Note: AWS can control access to S3 buckets with either IAM policies
attached to users/groups/roles (like the example above) or resource policies
attached to bucket objects (which look similar but also require a to
indicate which entity has those permissions). For more details, see Amazon’s
documentation about
S3 access control.

DynamoDB Table Permissions

If you are using state locking, Terraform will need the following AWS IAM
permissions on the DynamoDB table ():

This is seen in the following AWS IAM Statement:

Copy

Решение

Для начала будут расписаны основные конфигурации подключения к API хостинга, хранилище стейтов, и конфигурации для одного инстанса, и описание юзердаты (скриптов при старте инстанса)

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

  • variables.tf — файл с переменными, которые не являются секретными и могут храниться в репозитории.
  • terraform.tfvars — файл с переменными, которые не рекомендуется хранить в репозитории (ключи доступа, токены и прочее). Такие данные нужно хранить очень аккуратно. Кстати, мой коллега Олег рассказал, как правильно хранить сикреты в своей статье.

Импортируем ресурсы

Давайте, к примеру, импортируем все SSL-сертификаты (ACM) и базы данных (RDS) из Северной Виргинии (us-east-1) из нашего аккаунта AWS.

В моем случае используется несколько аккаунтов AWS, поэтому я использую профили, которые Terraformer, кстати, также поддерживает.

Начинаем импорт ресурсов:

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

Тут мы можем увидеть, что в каждой директории для ресурса появились файлы в формате HCL, а также стейт. Кстати, Terraformer поддерживает различные представления сгенерированных ресурсов, больше информации .

Давайте посмотрим вывод :

Тут видим, что состояние ресурсов описанное в конфигурации и в стейте совпадают. Круто.

По умолчанию, код генерируется для Terraform 0.12, однако я использую версию 0.14, поэтому столкнулся с такой ошибкой:

Это легко можно исправить с помощью команды:

Данная команда обновляет стейт с версии 3 до 4 и обновляет код до совместимости с Terraform 0.14.

Security & Compliance

Security scanning is graciously provided by Bridgecrew. Bridgecrew is the leading fully hosted, cloud-native solution providing continuous Terraform security and compliance.

Benchmark Description
Infrastructure Security Compliance
Center for Internet Security, KUBERNETES Compliance
Center for Internet Security, AWS Compliance
Center for Internet Security, AZURE Compliance
Payment Card Industry Data Security Standards Compliance
National Institute of Standards and Technology Compliance
Information Security Management System, ISO/IEC 27001 Compliance
Service Organization Control 2 Compliance
Center for Internet Security, GCP Compliance
Health Insurance Portability and Accountability Compliance

изучите пример теста

Комплексный тест написан на языке Go и использует платформу Terratest. Если вы , в файле будет определен тест .

В следующем исходном коде показана стандартная структура теста Golang с использованием Terratest:

Как видно из предыдущего фрагмента кода, этот тест включает три этапа.

  • Настройка. Terraform запускается для развертывания конфигурации.
  • Проверка. Выполняются проверки и утверждения.
  • Демонтаж. Инфраструктура очищается после выполнения теста.

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

  • terraform. Инитандаппли: включает выполнение и из кода Go
  • terraform.Output. Позволяет получить значение выходной переменной развертывания.
  • terraform. Destroy: выполняет команду из кода go.
  • test_structure.LoadTerraformOptions. Позволяет загрузить параметры Terraform, такие как конфигурация и переменные, из состояния.
  • test_structure.SaveTerraformOptions. Отвечает за сохранение параметров Terraform, таких как конфигурация и переменные, в состояние.

DevOps Accelerator for Startups

We deliver 10x the value for a fraction of the cost of a full-time engineer. Our track record is not even funny. If you want things done right and you need it done FAST, then we’re your best bet.

  • Reference Architecture. You’ll get everything you need from the ground up built using 100% infrastructure as code.
  • Release Engineering. You’ll have end-to-end CI/CD with unlimited staging environments.
  • Site Reliability Engineering. You’ll have total visibility into your apps and microservices.
  • Security Baseline. You’ll have built-in governance with accountability and audit logs for all changes.
  • GitOps. You’ll be able to operate your infrastructure via Pull Requests.
  • Training. You’ll receive hands-on training so your team can operate what we build.
  • Questions. You’ll have a direct line of communication between our teams via a Shared Slack channel.
  • Troubleshooting. You’ll get help to triage when things aren’t working.
  • Code Reviews. You’ll receive constructive feedback on Pull Requests.
  • Bug Fixes. We’ll rapidly work with you to fix any bugs in our projects.

»Command Line Arguments

This section describes legacy features that we’ve preserved for backward
compatibility but that we no longer recommend. See below for more details.

For configurations that include a block or that default to
the local backend by not specifying a backend at all, most commands that either
read or write state snapshots from the backend accept the following
additional arguments:

  • — overrides the state filename when reading the prior
    state snapshot.

  • — overrides the state filename when writing new state
    snapshots.

    If you use without also using then Terraform will
    use the filename for both and , which means
    Terraform will overwrite the input file if it creates a new state snapshot.

  • — overrides the default filename that the local backend
    would normally choose dynamically to create backup files when it writes new
    state.

    If you use without also using then Terraform will use
    the filename as a filename prefix for generating a backup filename.
    You can use (that is, set the filename to just the ASCII
    dash character) to disable the creation of backup files altogether.

These three options are preserved for backward-compatibility with earlier
workflows that predated the introduction of built-in remote state, where
users would write wrapper scripts that fetch prior state before running
Terraform and then save the new state after Terraform exits, in which case
the three arguments would typically all be paths within a temporary
directory used just for one operation.

Because these old workflows predate the introduction of the possibility of
multiple workspaces, setting them
overrides Terraform’s usual behavior of selecting a different state filename
based on the selected workspace. If you use all three of these options then
the selected workspace has no effect on which filenames Terraform will select
for state files, and so you’ll need to select different filenames yourself if
you wish to keep workspace state files distinct from one another.

These three options have no effect for configurations that have a different
backend type selected.

We do not recommend using these options in new systems, even if you are running
Terraform in automation. Instead,
select a different backend which supports remote state and configure it
within your root module, which ensures that everyone working on your
configuration will automatically retrieve and store state in the correct shared
location without any special command line options.

Определение кластера Kubernetes

Создайте файл конфигурации Terraform, который объявляет ресурсы для кластера Kubernetes.

  1. Создайте файл с именем .

  2. Вставьте следующий код в новый файл:

    Предыдущий код задает имя кластера (name), расположение (location) и имя группы ресурсов (resource_group_name). Также задается префикс полного доменного имени (FQDN). Полное доменное имя используется для доступа к кластеру.

    Запись позволяет настроить параметры, разрешающие вход на рабочие узлы с использованием SSH.

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

Настройка хранилища Azure для хранения данных о состоянии Terraform

Terraform отслеживает состояние локально через файл . Эта схема хорошо работает в среде с одним пользователем. В среде с несколькими пользователями для отслеживания состояния используется служба хранилища Azure.

В этом разделе вы узнаете как выполнять указанные ниже задачи.

  • Получение сведений об учетной записи хранения (имя учетной записи и ключ учетной записи)
  • Создание контейнера хранилища, в котором будут храниться сведения о состоянии Terraform.
  1. На портале Azure выберите Все службы в меню слева.

  2. Выберите Учетные записи хранения.

  3. На вкладке Учетные записи хранения выберите имя учетной записи хранения, в которой будет сохраняться состояние Terraform. Например, можно использовать учетную запись хранения, созданную при открытии Cloud Shell в первый раз. Имя учетной записи хранения, созданной с помощью Cloud Shell, обычно начинается с , после чего следует случайная строка из цифр и букв. Запишите выбранную учетную запись хранения. Это значение потребуется позже.

  4. На вкладке учетной записи хранения выберите Ключи доступа.

  5. Запишите значение ключа key1key. (Если щелкнуть значок справа от ключа, значение будет скопировано в буфер обмена.)

  6. Создайте контейнер в учетной записи хранения Azure. Замените заполнители на соответствующие значения для вашей среды.

Тестирование модуля terraform с помощью файла DOCKER

В этом разделе показано, как тестировать модуль Terraform с помощью файла Docker.

Примечание

В этом примере модуль выполняется не в Azure, а локально.

Убедитесь, что Docker установлен и запущен

Из командной строки введите .

Полученный результат подтверждает, что платформа Docker установлена.

Введите , чтобы убедиться, что Docker действительно запущен.

Настройка контейнера Docker

  1. Из командной строки введите

    .

    Будет отображаться сообщение Успешно создан

  2. В командной строке введите , чтобы увидеть в списке созданный модуль .

  3. Введите . После выполнения команды вы перейдете в среду Docker. На этом этапе файл можно обнаружить с помощью команды .

Запуск комплексного теста

  1. Выполните следующую команду:

  2. Через несколько секунд появится сообщение Проверка пройдена.

  3. Введите , чтобы завершить тест и выйти из среды Docker.

Inputs/Outputs

Чтобы сделать модули более полезными,чем простые изолированные контейнеры конфигурации Terraform,модули могут быть сконфигурированы,а также иметь выходы,которые могут потребляться вашей конфигурацией Terraform.

Входы модуля — это переменные, а выходы — выходы . Для их определения нет специального синтаксиса, они определяются так же, как любые другие переменные или выходы. Вы можете рассматривать эти переменные и выходные данные как интерфейс API для вашего модуля.

Давайте добавим переменную и вывод в наш модуль.

variable "memory" {}

output "received" {
  value = "${var.memory}"
}

Это создаст требуемую переменную, , а затем , который будет значением переменной .

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

module "child" {
  source = "./child"

  memory = "1G"
}

output "child_memory" {
  value = "${module.child.received}"
}

Если вы сейчас запустите , вы увидите, как это работает.

»Configuration

This backend requires the configuration of the AWS Region and S3 state storage. Other configuration, such as enabling DynamoDB state locking, is optional.

Credentials and Shared Configuration

The following configuration is required:

region — (Required) AWS Region of the S3 Bucket and DynamoDB Table (if used). This can also be sourced from the AWS_DEFAULT_REGION and AWS_REGION environment variables.

  • — (Optional) AWS access key. If configured, must also configure . This can also be sourced from the environment variable, AWS shared credentials file (e.g. ), or AWS shared configuration file (e.g. ).
  • — (Optional) AWS access key. If configured, must also configure . This can also be sourced from the environment variable, AWS shared credentials file (e.g. ), or AWS shared configuration file (e.g. ).
  • — (Optional) Custom endpoint for the AWS Identity and Access Management (IAM) API. This can also be sourced from the environment variable.
  • — (Optional) The maximum number of times an AWS API request is retried on retryable failure. Defaults to 5.
  • — (Optional) Name of AWS profile in AWS shared credentials file (e.g. ) or AWS shared configuration file (e.g. ) to use for credentials and/or configuration. This can also be sourced from the environment variable.
  • — (Optional) Path to the AWS shared credentials file. Defaults to .
  • — (Optional) Skip credentials validation via the STS API.
  • — (Optional) Skip validation of provided region name.
  • — (Optional) Skip usage of EC2 Metadata API.
  • — (Optional) Custom endpoint for the AWS Security Token Service (STS) API. This can also be sourced from the environment variable.
  • — (Optional) Multi-Factor Authentication (MFA) token. This can also be sourced from the environment variable.

Assume Role Configuration

  • — (Optional) Number of seconds to restrict the assume role session duration.
  • — (Optional) IAM Policy JSON describing further restricting permissions for the IAM Role being assumed.
  • — (Optional) Set of Amazon Resource Names (ARNs) of IAM Policies describing further restricting permissions for the IAM Role being assumed.
  • — (Optional) Map of assume role session tags.
  • — (Optional) Set of assume role session tag keys to pass to any subsequent sessions.
  • — (Optional) External identifier to use when assuming the role.
  • — (Optional) Amazon Resource Name (ARN) of the IAM Role to assume.
  • — (Optional) Session name to use when assuming the role.

S3 State Storage

The following configuration is required:

  • — (Required) Name of the S3 Bucket.
  • — (Required) Path to the state file inside the S3 Bucket. When using a non-default workspace, the state path will be (see also the configuration).
  • — (Optional) to be applied to the state file.
  • — (Optional) Enable server side encryption of the state file.
  • — (Optional) Custom endpoint for the AWS S3 API. This can also be sourced from the environment variable.
  • — (Optional) Enable path-style S3 URLs ( instead of ).
  • — (Optional) Amazon Resource Name (ARN) of a Key Management Service (KMS) Key to use for encrypting the state. Note that if this value is specified, Terraform will need , and permissions on this KMS key.
  • — (Optional) The key to use for encrypting state with Server-Side Encryption with Customer-Provided Keys (SSE-C). This is the base64-encoded value of the key, which must decode to 256 bits. This can also be sourced from the environment variable, which is recommended due to the sensitivity of the value. Setting it inside a terraform file will cause it to be persisted to disk in .
  • — (Optional) Prefix applied to the state path inside the bucket. This is only relevant when using a non-default workspace. Defaults to .
  • — (Optional) Custom endpoint for the AWS DynamoDB API. This can also be sourced from the environment variable.
  • — (Optional) Name of DynamoDB Table to use for state locking and consistency. The table must have a partition key named with type of . If not configured, state locking will be disabled.

»Usage

Usage:

Import will find the existing resource from ID and import it into your Terraform
state at the given ADDRESS.

ADDRESS must be a valid resource address.
Because any resource address is valid, the import command can import resources
into modules as well as directly into the root of your state.

ID is dependent on the resource type being imported. For example, for AWS
instances it is the instance ID () but for AWS Route53 zones
it is the zone ID (). Please reference the provider documentation for details
on the ID format. If you’re unsure, feel free to just try an ID. If the ID
is invalid, you’ll just receive an error message.

Warning: Terraform expects that each remote object it is managing will be
bound to only one resource address, which is normally guaranteed by Terraform
itself having created all objects. If you import existing objects into Terraform,
be careful to import each remote object to only one Terraform resource address.
If you import the same object multiple times, Terraform may exhibit unwanted
behavior. For more information on this assumption, see
the State section.

The command-line flags are all optional. The list of available flags are:

  • — Path to directory of Terraform configuration files that
    configure the provider for import. This defaults to your working directory.
    If this directory contains no Terraform configuration files, the provider
    must be configured via manual input or environmental variables.

  • — Whether to ask for input for provider configuration.

  • — Don’t hold a state lock during the operation. This is
    dangerous if others might concurrently run commands against the same
    workspace.

  • — Duration to retry a state lock.

  • — If specified, output won’t contain any color.

  • — Limit the number of concurrent operation as Terraform
    . Defaults
    to 10.

  • — Deprecated Override the provider configuration to
    use when importing the object. By default, Terraform uses the provider specified
    in the configuration for the target resource, and that is the best behavior in most cases.

  • — Set a variable in the Terraform configuration. This flag
    can be set multiple times. Variable values are interpreted as
    literal expressions in the
    Terraform language, so list and map values can be specified via this flag.
    This is only useful with the flag.

  • — Set variables in the Terraform configuration from
    a . If
    a or any files are present in the current
    directory, they will be automatically loaded. is loaded
    first and the files after in alphabetical order. Any files
    specified by override any values set automatically from files in
    the working directory. This flag can be used multiple times. This is only
    useful with the flag.

For configurations using
the backend
only,
also accepts the option
.

For configurations using
the backend only,
also accepts the legacy options
.

Пути и вложенные файлы

Иногда бывает полезно встроить в модуль файлы,не являющиеся конфигурационными файлами Terraform,например,скрипт для предоставления ресурса или файл для загрузки.

В этих случаях вы не можете использовать относительный путь, поскольку пути в Terraform обычно относятся к рабочему каталогу, из которого был запущен Terraform. Вместо этого вы хотите использовать путь относительно модуля. Для этого следует использовать переменные, интерполированные по пути .

resource "aws_instance" "server" {
  

  provisioner "remote-exec" {
    script = "${path.module}/script.sh"
  }
}

Здесь мы используем чтобы получить путь относительно модуля.

Проверка кластера Kubernetes

Средства Kubernetes позволяют проверить только что созданный кластер.

  1. Получите конфигурацию Kubernetes из данных о состоянии Terraform и сохраните ее в файле, который может прочитать средство kubectl.

  2. Убедитесь, что предыдущая команда не добавила символ ASCII EOT.

    Если вы видите в начале и в конце, измените содержимое файла, чтобы удалить эти символы. Это необходимое действие. В противном случае вы получите следующее сообщение: .

  3. Задайте переменную среды, позволяющую kubectl подобрать правильную конфигурацию.

  4. Проверьте работоспособность кластера.

    Должны отобразиться сведения о рабочих узлах. У всех узлов должно быть состояние Готово, как показано на следующем рисунке:

Модули публикации

Если вы создали модуль, который собираетесь использовать повторно, мы рекомендуем опубликовать его в реестре Terraform . Это приведет к версии вашего модуля, созданию документации и многому другому.

Опубликованные модули могут быть легко использованы Terraform,а в Terraform 0.11 вы также сможете сдерживать версии модулей для безопасного и предсказуемого обновления.Следующий пример показывает,как легко использовать модуль из реестра:

module "consul" {
  source = "hashicorp/consul/aws"
}

Вы также можете получить все преимущества реестра для частных модулей, зарегистрировавшись в частном реестре .

2018 HashiCorp По лицензии MPL 2.0.https://www.terraform.io/docs/modules/create.html

»Provider Configuration

Terraform will attempt to load configuration files that configure the
provider being used for import. If no configuration files are present or
no configuration for that specific provider is present, Terraform will
prompt you for access credentials. You may also specify environmental variables
to configure the provider.

The only limitation Terraform has when reading the configuration files
is that the import provider configurations must not depend on non-variable
inputs. For example, a provider configuration cannot depend on a data
source.

As a working example, if you’re importing AWS resources and you have a
configuration file with the contents below, then Terraform will configure
the AWS provider with this file.

Copy

Usage

IMPORTANT: We do not pin modules to versions in our examples because of the
difficulty of keeping the versions in the documentation in sync with the latest released versions.
We highly recommend that in your code you pin the version to the exact version you are
using so that your infrastructure remains stable, and update versions in a
systematic way so that they do not catch you by surprise.

Also, because of a bug in the Terraform registry (hashicorp/terraform#21417),
the registry shows many of our inputs as required when in fact they are optional.
The table below correctly indicates which inputs are required.

Create

Follow this procedure just once to create your deployment.

  1. Add the module to your file. The
    comment will help you remember to follow this procedure in the future:

    Module inputs and
    control the name of the backend
    definition file. Note that when is
    empty (the default), no file is created.

  2. . This downloads Terraform modules and providers.

  3. . This creates the state bucket and DynamoDB locking
    table, along with anything else you have defined in your file(s). At
    this point, the Terraform state is still stored locally.

    Module also creates a new file
    that defines the S3 state backend. For example:

    Henceforth, Terraform will also read this newly-created backend definition
    file.

  4. . Terraform detects that you want to move your
    Terraform state to the S3 backend, and it does so per . Now the
    state is stored in the S3 bucket, and the DynamoDB table will be used to lock
    the state to prevent concurrent modification.

This concludes the one-time preparation. Now you can extend and modify your
Terraform configuration as usual.

Destroy

Follow this procedure to delete your deployment.

  1. In , change the module arguments as
    follows:

  2. .
    This implements the above modifications by deleting the file
    and enabling deletion of the S3 state bucket.
  3. . Terraform detects that you want to move your
    Terraform state from the S3 backend to local files, and it does so per
    . Now the state is once again stored locally and the S3
    state bucket can be safely deleted.
  4. . This deletes all resources in your deployment.
  5. Examine local state file to verify that it contains
    no resources.
Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Мой редактор ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: