Tutorial

Cómo crear un servidor de Hashicorp Vault con Packer y Terraform en DigitalOcean [Inicio rápido]

Published on April 10, 2020
Español
Cómo crear un servidor de Hashicorp Vault con Packer y Terraform en DigitalOcean [Inicio rápido]

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. Packer y Terraform, también desarrollados por Hashicorp, pueden usarse juntos para crear e implementar imágenes de Vault.

En este tutorial, usará Packer para crear una instantánea inmutable del sistema con Vault instalado y orquestará su implementación usando Terraform.

Para acceder a una versión más detallada de este tutorial, consulte Cómo crear un servidor de Vault de Hashicorp usando Packer y Terraform en DigitalOcean.

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. Consulte Cómo crear un token de acceso personal para crear uno.
  • 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

Cree el directorio ~/vault-orchestration y posiciónese en él para almacenar sus archivos de Vault:

  1. mkdir ~/vault-orchestration
  2. cd ~/vault-orchestration

Cree directorios separados para la configuración de Packer y Terraform ejecutando lo siguiente:

  1. mkdir packer terraform

Diríjase al directorio de Packer:

  1. cd packer

Usar variables de plantilla

Cree variables.json en el subdirectorio packer para almacenar sus datos de variables privadas:

  1. nano variables.json

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"
}

Usará estas variables en la plantilla que está a punto de crear. Puede editar los valores básicos de imagen, región y tamaño de Droplet conforme a los documentos para desarrolladores.

Sustituya your_do_api_key por su clave de API y, luego, guarde y cierre el archivo.

Crear compiladores y aprovisionadores

Cree su plantilla de Packer para Vault en un archivo llamado template.json:

  1. nano template.json

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"
       ]
}]
}

Definirá un solo generador digitalocean. Packer creará un Droplet temporal con el tamaño, la imagen y la región definidos usando la clave API proporcionada.

El proveedor establecerá conexión con él usando SSH con el nombre de usuario especificado y ejecutará todos los proveedores definidos antes de crear una instantánea de DigitalOcean del Droplet y eliminarlo.

Es del tipo shell, que ejecutará los comando determinados en el destino. 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 para acceder a la versión más reciente para Linux.

Guarde y cierre el archivo.

Verifique la validez de su plantilla:

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

Verá el siguiente resultado:

Output
Template validated successfully.

Paso 2: Crear la instantánea

Cree su instantánea con el comando build de Packer:

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

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 '...'

La última línea contiene el nombre de la instantánea (como packer-1581537927) y su ID entre paréntesis, resaltados aquí. Tome nota del ID de la instantánea, ya que lo necesitará en el siguiente paso.

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

Paso 3: Escribir la configuración de Terraform

Diríjase al subdirectorio terraform:

  1. cd ~/vault-orchestration/terraform

Cree un archivo llamado do-provider.tf para almacenar el proveedor:

  1. nano do-provider.tf

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 proporciona una clave de API al proveedor digitalocean. Para especificar los valores de estas variables, creará un archivo de definiciones de variables similar a Packer. El nombre del archivo debe terminar en .tfvars o .tfvars.jason.

Guarde y cierre el archivo.

Cree un archivo de definiciones de variables:

  1. nano definitions.tfvars

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

Sustituya your_do_api_key, your_ssh_key_fingerprint y your_do_snapshot_id, (el ID de la instantánea del que tomó nota en el paso anterior). ​​ Los parámetros do_region y do_size deben tener los mismos valores que en el archivo de variables de Packer.

Guarde y cierre el archivo.

Cree el siguiente archivo para almacenar la configuración de la implementación de la instantánea de Vault:

  1. nano deployment.tf

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."
}

Defina un único recurso del tipo digitalocean_droplet llamado vault. Establezca sus parámetros según los valores de las variables y añada una clave SSH (usando su huella) de su cuenta de DigitalOcean al recurso del Droplet. Use output para mostrar las direcciones IP de todas las instancias recientemente implementadas en la consola.

Guarde y cierre el archivo.

Inicie el directorio como proyecto de Terraform:

  1. terraform init

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.

Paso 4: Implementar Vault usando Terraform

Pruebe la validez de la configuración:

  1. terraform validate

Verá el siguiente resultado:

Output
Success! The configuration is valid.

Ejecute el comando plan para ver qué intentará hacer Terraform respecto del aprovisionamiento de la infraestructura:

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

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.

Ejecute el plan:

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

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" }

Paso 5: Verificar su Droplet implementado

Ejecute lo siguiente para establecer conexión con su nuevo Droplet:

  1. ssh root@your_server_ip

Una vez que inicie sesión, ejecute Vault con lo siguiente:

  1. vault

Verá su resultado de “ayuda”:

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

Conclusión

Ahora dispone de un sistema automatizado para implementar Hashicorp Vault en Droplets de DigitalOcean usando Terraform y Packer. 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Savic

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel