One place for hosting & domains

      Packer

      Cómo crear un Vault Server de Hashicorp usando Packer y Terraform en DigitalOcean


      El autor seleccionó la Free and Open Source Fund para recibir una donación como parte del programa Write for DOnations.

      Introducción

      Vault, de Hashicorp, es una herramienta de código abierto que permite almacenar de forma segura datos secretos y sensibles en entornos dinámicos en la nube. Ofrece un cifrado de datos seguro, acceso basado en identidad usando políticas personalizadas, y arrendamiento y revocación de secretos, además de un registro de auditoría detallado que se asienta en todo momento. Vault también cuenta con una API HTTP, lo que lo convierte en la opción ideal para almacenar credenciales en implementaciones diseminadas orientadas al servicio, como Kubernetes.

      Packer y Terraform, también desarrollados por Hashicorp, pueden usarse juntos para crear e implementar imágenes de Vault. En este flujo de trabajo, los desarrolladores pueden usar Packer para escribir imágenes inmutables para diferentes plataformas desde un único archivo de configuración, que especifica lo que la imagen debería contener. Posteriormente, Terraform implementa tantas instancias personalizadas de las imágenes creadas como sea necesario.

      En este tutorial, usará Packer para crear una instantánea inmutable del sistema con Vault instalado y orquestará su implementación usando Terraform. Al final, tendrá un sistema automatizado para implementar Vault, lo que le permitirá centrarse en trabajar con Vault y no en el proceso de instalación y aprovisionamiento subyacente.

      Requisitos previos

      • Packer instalado en su máquina local. Para acceder a instrucciones, consulte la documentación oficial.
      • Terraform instalado en su computadora local. Consulte la documentación oficial para obtener ayuda.
      • Un token de acceso personal (clave de API) con permisos de lectura y escritura para su cuenta de DigitalOcean. Para aprender a crear uno, consulte Cómo crear un token de acceso personal en los documentos.
      • Una clave SSH que usará para la autenticación con los Droplets de Vault implementados, disponible en su equipo local y añadida a su cuenta de DigitalOcean. También necesitará su huella; podrá copiarla de la página Seguridad de su cuenta una vez que la haya añadido. Consulte la documentación de DigitalOcean para hallar instrucciones detalladas o el tutorial Cómo configurar claves SSH.

      Paso 1: Crear una plantilla de Packer

      En este paso, escribirá un archivo de configuración de Packer, llamado template, que indicará a Packer cómo crear una imagen que tenga Vault previamente instalado. Escribirá la configuración en formato JSON, un formato de archivo de configuración legible para humanos que se usa comúnmente.

      A los efectos de este tutorial, almacenará todos los archivos en ~/vault-orchestration. Cree el directorio ejecutando el siguiente comando:

      • mkdir ~/vault-orchestration

      Diríjase a este:

      Almacenará los archivos de configuración para Packer y Terraform por separado, en subdirectorios diferentes. Créelos usando el siguiente comando:

      Debido a que primero trabajará con Packer, diríjase al directorio de este:

      Usar variables de plantilla

      Almacenar datos privados y secretos de la aplicación en un archivo de variables independiente es una excelente alternativa para mantenerlos fuera de su plantilla. Cuando se cree la imagen, Packer sustituirá las variables referenciadas por sus valores. Codificar de forma rígida valores secretos en su plantilla es un riesgo de seguridad, en particular si se compartirá con miembros del equipo o se dispondrá en sitios públicos, como GitHub.

      Los almacenará en el subdirectorio packer, en un archivo llamado variables.json. Créelo usando su editor de texto favorito:

      Añada las siguientes líneas:

      ~/vault-orchestration/packer/variables.json

      {
          "do_token": "your_do_api_key",
          "base_system_image": "ubuntu-18-04-x64",
          "region": "nyc3",
          "size": "s-1vcpu-1gb"
      }
      

      El archivo de variables consiste en un diccionario JSON, que asigna los nombres de variables a sus valores. Usará estas variables en la plantilla que está a punto de crear. Si lo desea, puede editar los valores básicos de imagen, región y tamaño del Droplet conforme a los documentos para desarrolladores.

      Recuerde sustituir your_do_api_key por la clave de API que creó como parte de los requisitos previos, y luego guarde y cierre el archivo.

      Crear compiladores y aprovisionadores

      Una vez que esté listo el archivo de variables, creará la plantilla de Packer.

      Guardará la plantilla de Packer para Vault en un archivo llamado template.json. Créelo usando su editor de texto:

      Añada las siguientes líneas:

      ~/vault-orchestration/packer/template.json

      {
           "builders": [{
               "type": "digitalocean",
               "api_token": "{{user `do_token`}}",
               "image": "{{user `base_system_image`}}",
               "region": "{{user `region`}}",
               "size": "{{user `size`}}",
               "ssh_username": "root"
           }],
           "provisioners": [{
               "type": "shell",
               "inline": [
                   "sleep 30",
                   "sudo apt-get update",
                   "sudo apt-get install unzip -y",
                   "curl -L https://releases.hashicorp.com/vault/1.3.2/vault_1.3.2_linux_amd64.zip -o vault.zip",
                   "unzip vault.zip",
                   "sudo chown root:root vault",
                   "mv vault /usr/local/bin/",
                   "rm -f vault.zip"
               ]
          }]
      }
      

      En la plantilla, se definen conjuntos de compiladores y aprovisionadores. Los compiladores indican a Packer la manera de compilar la imagen del sistema (según su tipo) y el espacio en el que se almacenará, mientras que los aprovisionadores contienen conjuntos de acciones que Packer debería realizar en el sistema antes de convertirlo en una imagen inmutable; por ejemplo, instalar o configurar software. Sin aprovisionadores, obtendría una imagen de sistema básica intacta. Tanto los compiladores como los aprovisionadores exponen parámetros para una personalización del flujo de trabajo más completa.

      Primero se define un compilador individual del tipo digitalocean; esto significa que, cuando se le ordene crear una imagen, Packer usará los parámetros proporcionados para crear un Droplet temporal del tamaño definido usando la clave de API proporcionada, con la imagen del sistema básica y en la región especificada. El formato para obtener una variable es {{user 'variable_name'}}, donde la parte resaltada es su nombre.

      Cuando se proporcione el Droplet temporal, el proveedor establecerá conexión con él usando SSH con el nombre de usuario especificado y de forma secuencial ejecutará todos los proveedores definidos antes de crear una instantánea de DigitalOcean desde el Droplet y eliminarlo.

      Es del tipo shell, que ejecutará los comando determinados en el destino. Los comandos pueden especificarse inline, como un conjunto de cadenas, o definirse en archivos de secuencias de comandos independientes si su inserción en la plantilla dificulta la manipulación debido al tamaño. Los comandos de la plantilla esperarán 30 segundos para que el sistema arranque, y luego descargarán y desempaquetarán Vault 1.3.2. Consulte la página oficial de descarga de Vault y sustituya el enlace de los comandos por una versión más reciente de Linux, si está disponible.

      Cuando termine, guarde y cierre el archivo.

      Para verificar la validez de su plantilla, ejecute el siguiente comando:

      • packer validate -var-file=variables.json template.json

      Packer acepta una ruta al archivo de variables a través del argumento -var-file.

      Verá el siguiente resultado:

      Output

      Template validated successfully.

      Si ve un error, Packer especificará con exactitud dónde se produjo para que pueda corregirlo.

      Ahora tiene una plantilla en funcionamiento que produce una imagen con Vault instalado, con su clave de API y otros parámetros definidos en un archivo independiente. Con esto, estará listo para invocar Packer y crear la instantánea.

      Paso 2: Crear la instantánea

      En este paso, creará una instantánea de DigitalOcean desde su plantilla usando el comando build de Packer.

      Para crear su instantánea, ejecute el siguiente comando:

      • packer build -var-file=variables.json template.json

      Este comando tardará un tiempo en ejecutarse. Verá muchos resultados que tendrán un aspecto similar a este:

      Output

      digitalocean: output will be in this color. ==> digitalocean: Creating temporary ssh key for droplet... ==> digitalocean: Creating droplet... ==> digitalocean: Waiting for droplet to become active... ==> digitalocean: Using ssh communicator to connect: ... ==> digitalocean: Waiting for SSH to become available... ==> digitalocean: Connected to SSH! ==> digitalocean: Provisioning with shell script: /tmp/packer-shell035430322 ... ==> digitalocean: % Total % Received % Xferd Average Speed Time Time Time Current ==> digitalocean: Dload Upload Total Spent Left Speed digitalocean: Archive: vault.zip ==> digitalocean: 100 45.5M 100 45.5M 0 0 154M 0 --:--:-- --:--:-- --:--:-- 153M digitalocean: inflating: vault ==> digitalocean: Gracefully shutting down droplet... ==> digitalocean: Creating snapshot: packer-1581537927 ==> digitalocean: Waiting for snapshot to complete... ==> digitalocean: Destroying droplet... ==> digitalocean: Deleting temporary ssh key... Build 'digitalocean' finished. ==> Builds finished. The artifacts of successful builds are: --> digitalocean: A snapshot was created: 'packer-1581537927' (ID: 58230938) in regions '...'

      Packer registra todos los pasos que realizó al crear su plantilla. La última línea contiene el nombre de la instantánea (como packer-1581537927) y su ID entre paréntesis marcado en rojo. Anote el ID de la instantánea, lo necesitará en el paso siguiente.

      Si el proceso de creación falla debido a errores de API, espere unos minutos y realice un nuevo intento.

      Creó una instantánea de DigitalOcean conforme a su plantilla. La instantánea tiene Vault previamente instalado, y ahora puede implementar Droplets con él como su imagen de sistema. En el siguiente paso, escribirá la configuración de Terraform para automatizar dichas implementaciones.

      Paso 3: Escribir la configuración de Terraform

      En este paso, escribirá la configuración de Terraform para automatizar implementaciones de Droplets de la instantánea que contiene el Vault que acaba de crear usando Packer.

      Antes de escribir la configuración real de Terraform para implementar Vault desde la instantánea creada previamente, primero deberá configurar el proveedor de DigitalOcean. Diríjase al subdirectorio terraform ejecutando lo siguiente:

      • cd ~/vault-orchestration/terraform

      A continuación, cree un archivo llamado do-provider.tf en el que almacenará el proveedor:

      Añada las siguientes líneas:

      ~/vault-orchestration/terraform/do-provider.tf

      variable "do_token" {
      }
      
      variable "ssh_fingerprint" {
      }
      
      variable "instance_count" {
        default = "1"
      }
      
      variable "do_snapshot_id" {
      }
      
      variable "do_name" {
        default = "vault"
      }
      
      variable "do_region" {
      }
      
      variable "do_size" {
      }
      
      variable "do_private_networking" {
        default = true
      }
      
      provider "digitalocean" {
        token = var.do_token
      }
      

      Este archivo declara las variables del parámetro y proporciona al proveedor digitalocean una clave de API. Posteriormente, usará estas variables en su plantilla de Terraform, pero primero deberá especificar sus valores. Para ello, Terraform admite la especificación de valores de variables en un archivo de definiciones de variables de forma similar a Packer. El nombre del archivo debe terminar en .tfvars o .tfvars.jason. Luego, pasará ese archivo a Terraform usando el argumento –var-file.

      Guarde y cierre el archivo.

      Cree un archivo de definiciones de variables llamado definitions.tfvars usando su editor de texto:

      Añada las siguientes líneas:

      ~/vault-orchestration/terraform/definitions.tf

      do_token         = "your_do_api_key"
      ssh_fingerprint  = "your_ssh_key_fingerprint"
      do_snapshot_id   = your_do_snapshot_id
      do_name          = "vault"
      do_region        = "nyc3"
      do_size          = "s-1vcpu-1gb"
      instance_count   = 1
      

      Recuerde sustituir your_do_api_key, your_ssh_key_fingerprint y your_do_snapshot_id por la clave de API de su cuenta, la huella de su clave SSH y el ID de la instantánea que anotó en el paso anterior, respectivamente. Los parámetros do_region y do_size deben tener los mismos valores que en el archivo de variables de Packer. Si desea implementar varias instancias de una vez, ajuste instance_count según su valor deseado.

      Cuando termine, guarde y cierre el archivo.

      Para obtener más información sobre el proveedor de Terraform de DigitalOcean, consulte los documentos oficiales.

      Guardará la configuración de la implementación de la instantánea de Vault en un archivo llamado deployment.tf, en el directorio terraform. Créelo usando su editor de texto:

      Añada las siguientes líneas:

      ~/vault-orchestration/terraform/deployment.tf

      resource "digitalocean_droplet" "vault" {
        count              = var.instance_count
        image              = var.do_snapshot_id
        name               = var.do_name
        region             = var.do_region
        size               = var.do_size
        private_networking = var.do_private_networking
        ssh_keys = [
          var.ssh_fingerprint
        ]
      }
      
      output "instance_ip_addr" {
        value = {
          for instance in digitalocean_droplet.vault:
          instance.id => instance.ipv4_address
        }
        description = "The IP addresses of the deployed instances, paired with their IDs."
      }
      

      Aquí, define un único recurso del tipo digitalocean_droplet llamado vault. A continuación, establecerá sus parámetros según los valores de las variables y añadirá una clave SSH (usando la huella de esta) de su cuenta de DigitalOcean al recurso del Droplet. Finalmente, usará output para mostrar las direcciones IP de todas las instancias recién implementadas en la consola.

      Guarde y cierre el archivo.

      Antes de aplicar cualquier otra acción a la configuración de su implementación, deberá inicializar el directorio como proyecto de Terraform:

      Verá el siguiente resultado:

      Output

      Initializing the backend... Initializing provider plugins... 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.digitalocean: version = "~> 1.14" 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.

      Cuando se inicia un directorio como un proyecto, Terraform lee los archivos de configuración disponibles y los complementos de descargas considerados necesarios, según lo que se registre en el resultado.

      Ahora cuenta con la configuración de Terraform para implementar su instantánea de Vault. Podrá proceder a validarla e implementarla en un Droplet.

      Paso 4: Implementar Vault usando Terraform

      En esta sección, verificará su configuración de Terraform usando el comando validate. Una vez que se verifique correctamente, utilizará apply en ella e implementará un Droplet como resultado.

      Ejecute el siguiente comando para probar la validez de su configuración:

      Verá el siguiente resultado:

      Output

      Success! The configuration is valid.

      A continuación, ejecute el comando plan para ver qué intentará hacer Terraform cuando se aprovisione la infraestructura según su configuración:

      • terraform plan -var-file="definitions.tfvars"

      Terraform acepta un archivo de definiciones de variables a través del parámetro -var-file.

      El resultado será similar a este:

      Output

      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. ------------------------------------------------------------------------ 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: # digitalocean_droplet.vault[0] will be created + resource "digitalocean_droplet" "vault" { ... } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions will be performed if "terraform apply" is subsequently run.

      El signo + verde al principio de la línea resource "digitalocean_droplet" "vault" implica que Terraform creará un nuevo Droplet llamado vault y usará los parámetros que siguen. Esto es correcto; por ello, ahora podrá implementar el plan ejecutando terraform apply:

      • terraform apply -var-file="definitions.tfvars"

      Introduzca yes cuando se solicite. Después de unos minutos, el Droplet finalizará el aprovisionamiento y verá un resultado similar a este:

      Output

      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: + digitalocean_droplet.vault-droplet ... Plan: 1 to add, 0 to change, 0 to destroy. ... digitalocean_droplet.vault-droplet: Creating... ... Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: instance_ip_addr = { "181254240" = "your_new_server_ip" }

      En el resultado, Terraform registra las acciones que realizó (en este caso, para crear un Droplet) y muestra su dirección IP pública al final. La usará para establecer conexión con su nuevo Droplet en el siguiente paso.

      Creó un nuevo Droplet a partir de la instantánea que contiene Vault y ahora está listo para verificarlo.

      Paso 5: Verificar su Droplet implementado

      En este paso, accederá a su nuevo Droplet usando SSH y verificará que Vault se haya instalado correctamente.

      En equipos con Windows, puede usar un software como Kitty o Putty para establecer conexión con el Droplet con una clave SSH.

      En equipos con Linux o macOS, puede usar el comando ssh disponible para la conexión.

      Responda yes cuando se solicite. Una vez que acceda, inicie Vault ejecutanto lo siguiente:

      Verá el resultado de “ayuda”, que tiene este aspecto:

      Output

      Usage: vault <command> [args] Common commands: read Read data and retrieves secrets write Write data, configuration, and secrets delete Delete secrets and configuration list List data or secrets login Authenticate locally agent Start a Vault agent server Start a Vault server status Print seal and HA status unwrap Unwrap a wrapped secret Other commands: audit Interact with audit devices auth Interact with auth methods debug Runs the debug command kv Interact with Vault's Key-Value storage lease Interact with leases namespace Interact with namespaces operator Perform operator-specific tasks path-help Retrieve API help for paths plugin Interact with Vault plugins and catalog policy Interact with policies print Prints runtime configurations secrets Interact with secrets engines ssh Initiate an SSH session token Interact with tokens

      Puede cerrar la conexión escribiendo exit.

      De esta manera, habrá verificado verificó que su Droplet recién implementado se creó a partir de la instantánea que realizó y que Vault se instaló correctamente.

      Conclusión

      Ahora dispone de un sistema automatizado para implementar Hashicorp Vault en Droplets de DigitalOcean usando Terraform y Packer. Ahora puede implementar tantos servidores Vault como necesite. Para comenzar a usar Vault, deberá iniciarlo y realizar algunas configuraciones adicionales. Para hallar instrucciones sobre cómo hacerlo, consulte la documentación oficial.

      Para hallar más tutoriales sobre Terraform, consulte nuestra página de contenido de Terraform.



      Source link

      Создание сервера Vault от Hashicorp с помощью Packer и Terraform в DigitalOcean


      Автор выбрал фонд Free and Open Source Fund для получения пожертвования в рамках программы Write for DOnations.

      Введение

      Vault от Hashicorp — это инструмент с открытым исходным кодом, предназначенный для безопасного хранения секретов и конфиденциальных данных в динамических облачных средах. Он обеспечивает надежное шифрование данных, доступ на основе идентификации с помощью настраиваемых политик, возможность предоставления в аренду и аннулирования секретов, а также подробный журнал аудита, который поддерживается в любой момент времени. Также Vault содержит HTTP API, что делает его идеальным решением для хранения учетных данных при использовании распределенного сервисно-ориентированного развертывания, например, Kubernetes.

      Packer и Terraform, также разработанные Hashicorp, могут использоваться совместно для создания и развертывания образов Vault. В рамках данного рабочего процесса разработчики могут использовать Packer для записи неизменяемых образов для различных платформ из одного файла конфигурации, который указывает, что должен содержать этот образ. После этого Terraform выполняет развертывание любого необходимого количества настраиваемых экземпляров созданных образов.

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

      Предварительные требования

      • Packer, установленный на локальном компьютере. Для получения инструкций по установке ознакомьтесь с официальной документацией.
      • Terraform, установленный на локальном компьютере. Дополнительную информацию можно найти в официальной документации.
      • Персональный токен доступа (ключ API) с правами на чтение и запись для вашей учетной записи DigitalOcean. Чтобы узнать, как получить этот токен, ознакомьтесь со статьей Создание персонального токена доступа в документации.
      • Ключ SSH, который вы будете использовать для аутентификации с развернутыми дроплетами Vault, доступный на локальном компьютере и добавленный для вашей учетной записи DigitalOcean. Также вам потребуется его отпечаток, который вы можете скопировать на странице Безопасность вашей учетной записи, после его добавления. Ознакомьтесь с документацией DigitalOcean для получения подробных инструкций или с руководством Настройка ключей SSH.

      Шаг 1 — Создание шаблона Packer

      На данном шаге вы создадите файл конфигурации Packer с именем template, который будет указывать Packer, как следует собирать образ, который содержит предустановленный Vault. Вы будете использовать файл в формате JSON, широко используемый человекочитаемый формат файла конфигурации.

      Для целей настоящего обучающего модуля все файлы следует хранить в каталоге ~/vault-orchestration. Создайте директорию, запустив следующую команду:

      • mkdir ~/vault-orchestration

      Перейдите в директорию:

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

      Поскольку сначала мы будем работать с Packer, перейдите в его директорию:

      Использование переменных шаблона

      Хранение частных данных и секретов приложений в отдельном файле переменных является идеальным способом вынесения их из вашего шаблона. При создании образа Packer заменит указанные переменные на эти значения. Жесткое кодирование значений секретов в шаблоне влечет риски для безопасности, особенно если данные будут использоваться другими членами команды или публиковаться на общедоступных сайтов, например, GitHub.

      Мы будем хранить их в подкаталоге packer в файле с именем variables.json. Создайте его с помощью текстового редактора:

      Добавьте следующие строки:

      ~/vault-orchestration/packer/variables.json

      {
          "do_token": "your_do_api_key",
          "base_system_image": "ubuntu-18-04-x64",
          "region": "nyc3",
          "size": "s-1vcpu-1gb"
      }
      

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

      Не забудьте заменить your_do_api_key на ваш ключ API, созданный согласно предварительным требованиям, после чего сохраните и закройте файл.

      Создание средств для сборки и поставщиков

      После подготовки файла переменных вы сможете самостоятельно создать шаблон Packer.

      Шаблон Packer для Vault хранится в файле с именем template.json. Создайте его с помощью текстового редактора:

      Добавьте следующие строки:

      ~/vault-orchestration/packer/template.json

      {
           "builders": [{
               "type": "digitalocean",
               "api_token": "{{user `do_token`}}",
               "image": "{{user `base_system_image`}}",
               "region": "{{user `region`}}",
               "size": "{{user `size`}}",
               "ssh_username": "root"
           }],
           "provisioners": [{
               "type": "shell",
               "inline": [
                   "sleep 30",
                   "sudo apt-get update",
                   "sudo apt-get install unzip -y",
                   "curl -L https://releases.hashicorp.com/vault/1.3.2/vault_1.3.2_linux_amd64.zip -o vault.zip",
                   "unzip vault.zip",
                   "sudo chown root:root vault",
                   "mv vault /usr/local/bin/",
                   "rm -f vault.zip"
               ]
          }]
      }
      

      В шаблоне задаются массивы средств для сборки и поставщиков. Средства сборки указывают Packer, как выполнять сбор образа системы (в зависимости от типа) и где его хранить, а поставщики содержат набор действий, которые Packer должен выполнять для системы, прежде чем преобразовывать ее в неизменяемый образ, например, установка или настройка ПО. Без поставщиков вы получите нетронутый образ базовой системы. Как средства сборки, так и поставщики предоставляют параметры для дальнейшей настройки рабочего процесса.

      Сначала вы задаете единое средство сборки типа digitalocean, что значит, что при необходимости создания образа Packer будет использовать предоставленные параметры для создания временного дроплета определенного размера с помощью предоставленного ключа API, который содержит заданный образ базовой системы и указанный регион. Формат для получения переменной — {{user 'variable_name'}}​​​, где выделенная часть является именем.

      После предоставления временного дроплета поставщик будет подключаться к нему с помощью SSH с указанным именем пользователя и будет последовательно выполнять все указанные меры перед созданием снимка DigitalOcean Snapshot из дроплета и удалением последнего.

      Он имеет тип shell, который будет выполнять определенные команды для цели. Команды могут быть указаны как внутри в виде массива строк или определены в отдельных файлах скриптов, если их включение в шаблон будет затруднено из-за большого размера. Команды в шаблоне будут 30 секунд ждать загрузки системы, а затем будут загружать и распаковать Vault 1.3.2. Проверьте официальную страницу загрузки Vault и замените ссылку в командах на самую последнюю версию для Linux, если таковая существует.

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

      Чтобы подтвердить валидность шаблона, запустите следующую команду:

      • packer validate -var-file=variables.json template.json

      Packer принимает путь к файлу переменных с помощью аргумента -var-file.

      Вывод должен выглядеть так:

      Output

      Template validated successfully.

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

      Теперь у вас есть рабочий шаблон, который позволяет получить образ с установленным Vault, а ключ API и прочие параметры определены в отдельном файле. Теперь вы готовы к вызову Packer и сборке снимка.

      Шаг 2 — Сборка снимка

      На данном шаге вы выполните сборку снимка DigitalOcean из вашего шаблона с помощью команды build в Packer.

      Чтобы выполнить сборку снимка, запустите следующую команду:

      • packer build -var-file=variables.json template.json

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

      Output

      digitalocean: output will be in this color. ==> digitalocean: Creating temporary ssh key for droplet... ==> digitalocean: Creating droplet... ==> digitalocean: Waiting for droplet to become active... ==> digitalocean: Using ssh communicator to connect: ... ==> digitalocean: Waiting for SSH to become available... ==> digitalocean: Connected to SSH! ==> digitalocean: Provisioning with shell script: /tmp/packer-shell035430322 ... ==> digitalocean: % Total % Received % Xferd Average Speed Time Time Time Current ==> digitalocean: Dload Upload Total Spent Left Speed digitalocean: Archive: vault.zip ==> digitalocean: 100 45.5M 100 45.5M 0 0 154M 0 --:--:-- --:--:-- --:--:-- 153M digitalocean: inflating: vault ==> digitalocean: Gracefully shutting down droplet... ==> digitalocean: Creating snapshot: packer-1581537927 ==> digitalocean: Waiting for snapshot to complete... ==> digitalocean: Destroying droplet... ==> digitalocean: Deleting temporary ssh key... Build 'digitalocean' finished. ==> Builds finished. The artifacts of successful builds are: --> digitalocean: A snapshot was created: 'packer-1581537927' (ID: 58230938) in regions '...'

      Packer фиксирует в журнале все шаги в процессе сборки шаблона. Последняя строка содержит имя снимка (например, packer-1581537927), а также его идентификатор в скобках, выделенный красным. Запишите ваш идентификатор снимка, поскольку он потребуется на следующем шаге.

      Если процесс сборки не удалось завершить из-за ошибок API, подождите несколько минут и повторите попытку.

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

      Шаг 3 — Создание конфигурации Terraform

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

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

      • cd ~/vault-orchestration/terraform

      Затем создайте файл с именем do-provider.tf, где будет храниться поставщик:

      Добавьте следующие строки:

      ~/vault-orchestration/terraform/do-provider.tf

      variable "do_token" {
      }
      
      variable "ssh_fingerprint" {
      }
      
      variable "instance_count" {
        default = "1"
      }
      
      variable "do_snapshot_id" {
      }
      
      variable "do_name" {
        default = "vault"
      }
      
      variable "do_region" {
      }
      
      variable "do_size" {
      }
      
      variable "do_private_networking" {
        default = true
      }
      
      provider "digitalocean" {
        token = var.do_token
      }
      

      В этом файле объявляются переменные параметров и предоставляется поставщик digitalocean с ключом API. Позднее вы будете использовать эти переменные в шаблоне Terraform, но сначала вам потребуется задать их значения. Для таких целей Terraform поддерживает указание значений переменных в файле определений переменных, как и Packer. Имя файла должно заканчиваться на .tfvars или .tfvars.json. Позже вы передадите этот файл в Terraform с помощью аргумента -var-file.

      Сохраните и закройте файл.

      Создайте файл определений переменных с именем definitions.tfvars с помощью текстового редактора:

      Добавьте следующие строки:

      ~/vault-orchestration/terraform/definitions.tf

      do_token         = "your_do_api_key"
      ssh_fingerprint  = "your_ssh_key_fingerprint"
      do_snapshot_id   = your_do_snapshot_id
      do_name          = "vault"
      do_region        = "nyc3"
      do_size          = "s-1vcpu-1gb"
      instance_count   = 1
      

      Не забудьте заменить your_do_api_key, your_ssh_key_fingerprint и your_do_snapshot_id на ваш ключ API, отпечаток вашего ключа SSH и идентификатор снимка, который вы записали на предыдущем шаге. Параметры do_region и do_size должны иметь те же значения, что и в файле переменных Packer. Если вам потребуется выполнить развертывание сразу нескольких экземпляров, измените значение instance_count на желаемое.

      После завершения редактирования сохраните и закройте файл.

      Дополнительную информацию по поставщику DigitalOcean Terraform можно найти в официальной документации.

      Вы будете хранить конфигурацию развертывания снимка с Vault в файле deployment.tf в директории terraform. Создайте его с помощью текстового редактора:

      Добавьте следующие строки:

      ~/vault-orchestration/terraform/deployment.tf

      resource "digitalocean_droplet" "vault" {
        count              = var.instance_count
        image              = var.do_snapshot_id
        name               = var.do_name
        region             = var.do_region
        size               = var.do_size
        private_networking = var.do_private_networking
        ssh_keys = [
          var.ssh_fingerprint
        ]
      }
      
      output "instance_ip_addr" {
        value = {
          for instance in digitalocean_droplet.vault:
          instance.id => instance.ipv4_address
        }
        description = "The IP addresses of the deployed instances, paired with their IDs."
      }
      

      Здесь вы определяете единый ресурс типа digitalocean_droplet с именем vault. Затем вы задаете параметры в соответствии со значениями переменных и добавляете ключ SSH (с помощью его отпечатка) из вашей учетной записи DigitalOcean в ресурс дроплета. Наконец, вы выводите IP-адреса всех вновь развернутых экземпляров в консоль.

      Сохраните и закройте файл.

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

      Вывод должен выглядеть так:

      Output

      Initializing the backend... Initializing provider plugins... 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.digitalocean: version = "~> 1.14" 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.

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

      Теперь у вас есть конфигурация Terraform для развертывания вашего снимка Vault. Теперь вы можете перейти к его проверке и развертыванию в дроплете.

      Шаг 4 — Развертывание Vault с помощью Terraform

      В этом разделе вы выполните проверку вашей конфигурации Terraform с помощью команды validate. После успешной проверки вы должны будете принять ее и развернуть дроплет в качестве результата.

      Запустите следующую команду для проверки вашей конфигурации:

      Вывод должен выглядеть так:

      Output

      Success! The configuration is valid.

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

      • terraform plan -var-file="definitions.tfvars"

      Terraform принимает файл определений переменных с помощью параметра -var-file.

      Результат будет выглядеть примерно следующим образом:

      Output

      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. ------------------------------------------------------------------------ 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: # digitalocean_droplet.vault[0] will be created + resource "digitalocean_droplet" "vault" { ... } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions will be performed if "terraform apply" is subsequently run.

      Зеленый знак + в начале строки resource "digitalocean_droplet" "vault" означает, что Terraform будет создавать новый дроплет с именем vault, используя следующие параметры. Это правильно, поэтому теперь вы можете воспользоваться командой terraform apply:

      • terraform apply -var-file="definitions.tfvars"

      Введите yes при запросе. Через несколько минут дроплет завершит предоставление ресурсов, а вы увидите примерно следующее:

      Output

      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: + digitalocean_droplet.vault-droplet ... Plan: 1 to add, 0 to change, 0 to destroy. ... digitalocean_droplet.vault-droplet: Creating... ... Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: instance_ip_addr = { "181254240" = "your_new_server_ip" }

      На экране результатов Terraform показывает выполненные действия (в нашем случае — для создания дроплета) и отображает свой публичный IP-адрес в конце. Вы будете использовать его для подключения к вашему новому дроплету в следующем шаге.

      Вы создали новый дроплет из снимка с Vault и теперь можете проверить его.

      Шаг 5 — Проверка вашего развернутого дроплета

      На данном шаге вы получите доступ к вашему новому дроплету с помощью SSH и убедитесь, что Vault установлен корректно.

      Если вы используете Windows, вы можете использовать программные продукты Kitty или Putty для подключения к дроплету с ключом SSH.

      На компьютерах Linux и macOS вы можете использовать уже имеющуюся команду ssh для подключения:

      Введите yes при запросе. После входа запустите Vault с помощью следующей команды:

      :

      Output

      Usage: vault <command> [args] Common commands: read Read data and retrieves secrets write Write data, configuration, and secrets delete Delete secrets and configuration list List data or secrets login Authenticate locally agent Start a Vault agent server Start a Vault server status Print seal and HA status unwrap Unwrap a wrapped secret Other commands: audit Interact with audit devices auth Interact with auth methods debug Runs the debug command kv Interact with Vault's Key-Value storage lease Interact with leases namespace Interact with namespaces operator Perform operator-specific tasks path-help Retrieve API help for paths plugin Interact with Vault plugins and catalog policy Interact with policies print Prints runtime configurations secrets Interact with secrets engines ssh Initiate an SSH session token Interact with tokens

      Подключение можно закрыть с помощью команды exit.

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

      Заключение

      Вы создали автоматизированную систему для развертывания Hashicorp Vault в дроплетах DigitalOcean с помощью Terraform и Packer. Теперь вы можете развернуть необходимое вам количество серверов Vault. Для начала использования Vault вам потребуется инициализировать его и выполнить настройку. Соответствующие инструкции можно найти в официальной документации.

      Дополнительные обучающие материалы по работе с Terraform можно найти на странице материалов по Terraform.



      Source link

      How To Build a Hashicorp Vault Server Using Packer and Terraform on DigitalOcean [Quickstart]


      Introduction

      Vault, by Hashicorp, is an open-source tool for securely storing secrets and sensitive data in dynamic cloud environments. Packer and Terraform, also developed by Hashicorp, can be used together to create and deploy images of Vault.

      In this tutorial, you’ll use Packer to create an immutable snapshot of the system with Vault installed, and orchestrate its deployment using Terraform.

      For a more detailed version of this tutorial, please refer to How To Build a Hashicorp Vault Server Using Packer and Terraform on DigitalOcean.

      Prerequisites

      • Packer installed on your local machine. For instructions, visit the official documentation.
      • Terraform installed on your local machine. Visit the official documentation for a guide.
      • A personal access token (API key) with read and write permissions for your DigitalOcean account. Visit How to Create a Personal Access Token to create one.
      • An SSH key you’ll use to authenticate with the deployed Vault Droplets, available on your local machine and added to your DigitalOcean account. You’ll also need its fingerprint, which you can copy from the Security page of your account once you’ve added it. See the DigitalOcean documentation for detailed instructions or the How To Set Up SSH Keys tutorial.

      Step 1 — Creating a Packer Template

      Create and move into the ~/vault-orchestration directory to store your Vault files:

      • mkdir ~/vault-orchestration
      • cd ~/vault-orchestration

      Create separate directories for Packer and Terraform configuration by running:

      Navigate to the Packer directory:

      Using Template Variables

      Create a variables.json in your packer subdirectory to store your private variable data:

      Add the following lines:

      ~/vault-orchestration/packer/variables.json

      {
        "do_token": "your_do_api_key",
        "base_system_image": "ubuntu-18-04-x64",
        "region": "nyc3",
        "size": "s-1vcpu-1gb"
      }
      

      You’ll use these variables in the template you are about to create. You can edit the base image, region, and Droplet size values according to the developer docs.

      Replace your_do_api_key with your API key, then save and close the file.

      Creating Builders and Provisioners

      Create your Packer template for Vault in a file named template.json:

      Add the following lines:

      ~/vault-orchestration/packer/template.json

      {
         "builders": [{
             "type": "digitalocean",
             "api_token": "{{user `do_token`}}",
             "image": "{{user `base_system_image`}}",
             "region": "{{user `region`}}",
             "size": "{{user `size`}}",
             "ssh_username": "root"
         }],
         "provisioners": [{
             "type": "shell",
             "inline": [
                 "sleep 30",
                 "sudo apt-get update",
                 "sudo apt-get install unzip -y",
                 "curl -L https://releases.hashicorp.com/vault/1.3.2/vault_1.3.2_linux_amd64.zip -o vault.zip",
                 "unzip vault.zip",
                 "sudo chown root:root vault",
                 "mv vault /usr/local/bin/",
                 "rm -f vault.zip"
             ]
      }]
      }
      

      You define a single digitalocean builder. Packer will create a temporary Droplet of the defined size, image, and region using the provided API key.

      The provisioner will connect to it using SSH with the specified username and will sequentially execute all defined provisioners before creating a DigitalOcean Snapshot from the Droplet and deleting it.

      It’s of type shell, which will execute given commands on the target. The commands in the template will wait 30 seconds for the system to boot up, and will then download and unpack Vault 1.3.2. Check the official Vault download page for the most up-to-date version for Linux.

      Save and close the file.

      Verify the validity of your template:

      • packer validate -var-file=variables.json template.json

      You’ll see the following output:

      Output

      Template validated successfully.

      Step 2 — Building the Snapshot

      Build your snapshot with the Packer build command:

      • packer build -var-file=variables.json template.json

      You’ll see a lot of output, which will look like this:

      Output

      digitalocean: output will be in this color. ==> digitalocean: Creating temporary ssh key for droplet... ==> digitalocean: Creating droplet... ==> digitalocean: Waiting for droplet to become active... ==> digitalocean: Using ssh communicator to connect: ... ==> digitalocean: Waiting for SSH to become available... ==> digitalocean: Connected to SSH! ==> digitalocean: Provisioning with shell script: /tmp/packer-shell035430322 ... ==> digitalocean: % Total % Received % Xferd Average Speed Time Time Time Current ==> digitalocean: Dload Upload Total Spent Left Speed digitalocean: Archive: vault.zip ==> digitalocean: 100 45.5M 100 45.5M 0 0 154M 0 --:--:-- --:--:-- --:--:-- 153M digitalocean: inflating: vault ==> digitalocean: Gracefully shutting down droplet... ==> digitalocean: Creating snapshot: packer-1581537927 ==> digitalocean: Waiting for snapshot to complete... ==> digitalocean: Destroying droplet... ==> digitalocean: Deleting temporary ssh key... Build 'digitalocean' finished. ==> Builds finished. The artifacts of successful builds are: --> digitalocean: A snapshot was created: 'packer-1581537927' (ID: 58230938) in regions '...'

      The last line contains the name of the snapshot (such as packer-1581537927) and its ID in parentheses, highlighted here. Note your ID of the snapshot, because you’ll need it in the next step.

      If the build process fails due to API errors, wait a few minutes and then retry.

      Step 3 — Writing Terraform Configuration

      Navigate to the terraform subdirectory:

      • cd ~/vault-orchestration/terraform

      Create a file named do-provider.tf to store the provider:

      Add the following lines:

      ~/vault-orchestration/terraform/do-provider.tf

      variable "do_token" {
      }
      
      variable "ssh_fingerprint" {
      }
      
      variable "instance_count" {
      default = "1"
      }
      
      variable "do_snapshot_id" {
      }
      
      variable "do_name" {
      default = "vault"
      }
      
      variable "do_region" {
      }
      
      variable "do_size" {
      }
      
      variable "do_private_networking" {
      default = true
      }
      
      provider "digitalocean" {
      token = var.do_token
      }
      

      This file provides the digitalocean provider with an API key. To specify the values of these variables you’ll create a variable definitions file similarly to Packer. The filename must end in either .tfvars or .tfvars.json.

      Save and close the file.

      Create a variable definitions file:

      Add the following lines:

      ~/vault-orchestration/terraform/definitions.tf

      do_token         = "your_do_api_key"
      ssh_fingerprint  = "your_ssh_key_fingerprint"
      do_snapshot_id   = your_do_snapshot_id
      do_name          = "vault"
      do_region        = "nyc3"
      do_size          = "s-1vcpu-1gb"
      instance_count   = 1
      

      Replace your_do_api_key, your_ssh_key_fingerprint, and your_do_snapshot_id (the snapshot ID you noted from the previous step). The do_region and do_size parameters must have the same values as in the Packer variables file.

      Save and close the file.

      Create the following file to store the Vault snapshot deployment configuration:

      Add the following lines:

      ~/vault-orchestration/terraform/deployment.tf

      resource "digitalocean_droplet" "vault" {
      count              = var.instance_count
      image              = var.do_snapshot_id
      name               = var.do_name
      region             = var.do_region
      size               = var.do_size
      private_networking = var.do_private_networking
      ssh_keys = [
        var.ssh_fingerprint
      ]
      }
      
      output "instance_ip_addr" {
      value = {
        for instance in digitalocean_droplet.vault:
        instance.id => instance.ipv4_address
      }
      description = "The IP addresses of the deployed instances, paired with their IDs."
      }
      

      You define a single resource of the type digitalocean_droplet named vault. You set its parameters according to the variable values and add an SSH key (using its fingerprint) from your DigitalOcean account to the Droplet resource. You output the IP addresses of all newly deployed instances to the console.

      Save and close the file.

      Initialize the directory as a Terraform project:

      You’ll see the following output:

      Output

      Initializing the backend... Initializing provider plugins... 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.digitalocean: version = "~> 1.14" 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.

      Step 4 — Deploying Vault Using Terraform

      Test the validity of your configuration:

      You’ll see the following output:

      Output

      Success! The configuration is valid.

      Run the plan command to see what Terraform will attempt when it comes to provision the infrastructure:

      • terraform plan -var-file="definitions.tfvars"

      The output will look similar to:

      Output

      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. ------------------------------------------------------------------------ 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: # digitalocean_droplet.vault[0] will be created + resource "digitalocean_droplet" "vault" { ... } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions will be performed if "terraform apply" is subsequently run.

      Execute the plan:

      • terraform apply -var-file="definitions.tfvars"

      The Droplet will finish provisioning and you’ll see output similar to this:

      Output

      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: + digitalocean_droplet.vault-droplet ... Plan: 1 to add, 0 to change, 0 to destroy. ... digitalocean_droplet.vault-droplet: Creating... ... Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: instance_ip_addr = { "181254240" = "your_new_server_ip" }

      Step 5 — Verifying Your Deployed Droplet

      Run the following to connect to your new Droplet:

      Once you are logged in, run Vault with:

      You’ll see its “help” output:

      Output

      Usage: vault <command> [args] Common commands: read Read data and retrieves secrets write Write data, configuration, and secrets delete Delete secrets and configuration list List data or secrets login Authenticate locally agent Start a Vault agent server Start a Vault server status Print seal and HA status unwrap Unwrap a wrapped secret Other commands: audit Interact with audit devices auth Interact with auth methods debug Runs the debug command kv Interact with Vault's Key-Value storage lease Interact with leases namespace Interact with namespaces operator Perform operator-specific tasks path-help Retrieve API help for paths plugin Interact with Vault plugins and catalog policy Interact with policies print Prints runtime configurations secrets Interact with secrets engines ssh Initiate an SSH session token Interact with tokens

      Conclusion

      You now have an automated system for deploying Hashicorp Vault on DigitalOcean Droplets using Terraform and Packer. To start using Vault, you’ll need to initialize it and further configure it. For instructions on how to do that, visit the official docs.

      For more tutorials using Terraform, check out our Terraform content page.



      Source link