Next: , Previous: , Up: Configuración del sistema   [Contents][Index]


11.17 Invoking guix deploy

Ya hemos visto como usar declaraciones operating-system para gestionar la configuración de una máquina de manera local. Supongamos no obstante que necesita configurar múltiples máquinas—quizá esté gestionando un servicio en la web que se componga de varios servidores. guix deploy le permite usar las mismas declaraciones operating-system para gestionar múltiples máquinas remotas como un único “despliegue” lógico.

Nota: La funcionalidad descrita en esta sección está todavía en desarrollo y sujeta a cambios. Puede ponerse en contacto con nosotras a través de guix-devel@gnu.org.

guix deploy archivo

Dicha invocación llevará a cabo en las máquinas el despliegue al cual el archivo evalúe. Como ejemplo, archivo puede contener una definición como esta:

;; Este es un despliegue de Guix con una configuración en
;; mínima ("en los huesos"), sin servidor gráfico X11,
;; en una máquina con un daemon SSH escuchando en
;; localhost:2222. Una configuración como esta puede ser
;; apropiada para máquinas virtuales con puertos redirigidos
;; a la interfaz local de la máquina anfitriona.
(use-service-modules networking ssh)
(use-package-modules bootloaders)

(define %system
  (operating-system
   (host-name "gnu-deployed")
   (timezone "Etc/UTC")
   (bootloader (bootloader-configuration
                (bootloader grub-bootloader)
                (targets '("/dev/vda"))
                (terminal-outputs '(console))))
   (file-systems (cons (file-system
                        (mount-point "/")
                        (device "/dev/vda1")
                        (type "ext4"))
                       %base-file-systems))
   (services
    (append (list (service dhcp-client-service-type)
                  (service openssh-service-type
                           (openssh-configuration
                            (permit-root-login #t)
                            (allow-empty-passwords? #t))))
            %base-services))))

(list (machine
       (operating-system %sistema)
       (environment managed-host-environment-type)
       (configuration (machine-ssh-configuration
                       (host-name "localhost")
                       (system "x86_64-linux")
                       (user "alicia")
                       (identity "./id_rsa")
                       (port 2222)))))

El archivo debe evaluar a una lista de objetos machine. Este ejemplo, durante el despliegue, creará una nueva generación en el sistema remoto que implemente la declaración operating-system %system. environment y configuration especifican cómo debe aprovisionarse la máquina—es decir, cómo se crean y gestionan los recursos computacionales. El ejemplo previo no crea ningún recurso, ya que 'managed-host es una máquina que ya está ejecutando el sistema Guix y está disponible a través de la red. Este es un caso particularmente simple; un despliegue más complejo puede implicar, por ejemplo, el arranque de máquinas virtuales a través de un proveedor de servidores privados virtuales (VPS). En dicho caso se usaría un tipo distinto en environment.

Tenga en cuenta que primero debe generar un par de claves en la máquina coordinadora para permitir al daemon exportar archivos firmados de archivos en el almacén (see Invocación de guix archive), aunque este paso se realiza de manera automática en el sistema Guix:

# guix archive --generate-key

Cada máquina de destino debe autorizar a la clave de la máquina maestra para que acepte elementos del almacén que reciba de la coordinadora:

# guix archive --authorize < clave-publica-coordinadora.txt

La usuaria proporcionada en user, en este ejemplo, especifica la cuenta de la usuaria con la que ingresar en el sistema para realizar el despliegue. Su valor predeterminado es root, pero el ingreso al sistema como root a través de SSH en algunos casos puede no estar permitido. Para solventar este problema, guix deploy puede ingresar al sistema como una usuaria sin privilegios y ejecutar sudo para escalar privilegios. Esto funciona únicamente si sudo está instalado en el sistema remoto y se puede invocar de manera no interactiva como user. Es decir: la línea de sudoers que permite a la usuaria user la capacidad de usar sudo debe contener la etiqueta NOPASSWD. Esto se puede conseguir con el siguiente fragmento de la configuración de sistema operativo:

(use-modules ...
             (gnu system))               ;para %sudoers-specification

(define %usuaria "nombre")

(operating-system
  ...
  (sudoers-file
     (plain-file "sudoers"
                 (string-append (plain-file-content %sudoers-specification)
                                (format #f "~a ALL = NOPASSWD: ALL~%"
                                        %usuaria)))))

Para obtener más información sobre el formato del archivo sudoers consulte man sudoers.

Once you’ve deployed a system on a set of machines, you may find it useful to run a command on all of them. The --execute or -x option lets you do that; the example below runs uname -a on all the machines listed in the deployment file:

guix deploy file -x -- uname -a

One thing you may often need to do after deployment is restart specific services on all the machines, which you can do like so:

guix deploy file -x -- herd restart service

The guix deploy -x command returns zero if and only if the command succeeded on all the machines.

Below are the data types you need to know about when writing a deployment file.

Tipo de datos: machine

Tipo de datos que representa una máquina individual en un despliegue heterogéneo de Guix.

operating-system

El objeto de la configuración de sistema operativo a desplegar.

environment

Un objeto environment-type que describe como debe aprovisionarse la máquina.

configuration (predeterminado: #f)

Un objeto que describe la configuración para el entorno (environment) de la máquina. Si environment tiene una configuración predeterminada, puede usarse #f. No obstante, si se usa #f para un entorno sin configuración predeterminada se emitirá un error.

Tipo de datos: machine-ssh-configuration

Tipo de datos que representa los parámetros del cliente SSH para una máquina con un entorno (environment) de tipo gestionado (managed-host-environment-type).

host-name
build-locally? (predeterminado: #t)

Si es falso, las derivaciones del sistema se construirán en la máquina sobre la que se realiza el despliegue.

system

El tipo de sistema que describe la arquitectura de la máquina sobre la que se realiza el despliegue—por ejemplo, "x86_64-linux".

authorize? (predeterminado: #t)

Si es verdadero, la clave de firma de la máquina coordinadora debe añadirse al anillo de claves del control de acceso (ACL) de la máquina remota.

port (predeterminado: 22)
user (predeterminada: "root")
identity (predeterminada: #f)

Cuando se especifica, indica la ruta al archivo que contiene la clave privada de SSH para la identificación con la máquina remota.

host-key (predeterminada: #f)

Esta debería ser la clave SSH de la máquina, que puede ser más o menos así:

ssh-ed25519 AAAAC3Nz… root@example.org

Cuando host-key es #f, el servidor se identifica con el archivo ~/.ssh/known_hosts, igual que hace el cliente ssh de OpenSSH.

allow-downgrades? (predeterminado: #f)

Determina si se permiten instalaciones de versiones potencialmente anteriores.

Al igual que guix system reconfigure, guix deploy compara la revisión del canal desplegada actualmente en la máquina remota (como muestra guix system describe) con aquella que se esté usando en ese momento (como muestra guix describe) para determinar si las revisiones que se despliegan son descendientes de aquellas en uso. Cuando no es el caso y el valor de allow-downgrades? es falso, emite un error. Esto le permite no instalar accidentalmente una versión anterior en máquinas remotas.

safety-checks? (default: #t)

Whether to perform “safety checks” before deployment. This includes verifying that devices and file systems referred to in the operating system configuration actually exist on the target machine, and making sure that Linux modules required to access storage devices at boot time are listed in the initrd-modules field of the operating system.

These safety checks ensure that you do not inadvertently deploy a system that would fail to boot. Be careful before turning them off!

Tipo de datos: digital-ocean-configuration

Tipo de datos que representa el Droplet que debe crearse para la máquina con environment digital-ocean-environment-type.

ssh-key

The path to the SSH private key to use to authenticate with the remote host. In the future, this field may not exist.

tags

A list of string “tags” that uniquely identify the machine. Must be given such that no two machines in the deployment have the same set of tags.

region

Descriptor (slug) de región de Digital Ocean, como "nyc3".

size

Descriptor (slug) de tamaño de Digital Ocean, como "s-1vcpu-1gb"

enable-ipv6?

Determina si droplet debe crearse con capacidad de usar redes IPv6 o no.

Data Type: hetzner-configuration

This is the data type describing the server that should be created for a machine with an environment of hetzner-environment-type. It allows you to configure deployment to a VPS (virtual private server) hosted by Hetzner.

allow-downgrades? (predeterminado: #f)

Determina si se permiten instalaciones de versiones potencialmente anteriores.

authorize? (predeterminado: #t)

If true, the public signing key "/etc/guix/signing-key.pub" of the machine that invokes guix deploy will be added to the operating system ACL keyring of the target machine.

build-locally? (predeterminado: #t)

If true, system derivations will be built on the machine that invokes guix deploy, otherwise derivations are build on the target machine. Set this to #f if the machine you are deploying from has a different architecture than the target machine and you can’t build derivations for the target architecture by other means, like offloading (see Uso de la facilidad de delegación de trabajo) or emulation (see Transparent Emulation with QEMU).

delete? (default: #t)

If true, the server will be deleted when an error happens in the provisioning phase. If false, the server will be kept in order to debug any issues.

labels (default: '())

A user defined alist of key/value pairs attached to the SSH key and the server on the Hetzner API. Keys and values must be strings, e.g. '(("environment" . "development")). For more information, see Labels.

location (default: "fsn1")

The name of a location to create the server in. For example, "fsn1" corresponds to the Hetzner site in Falkenstein, Germany, while "sin" corresponds to its site in Singapore.

server-type (default: "cx42")

The name of the server type this virtual server should be created with. For example, "cx42" corresponds to a x86_64 server that has 8 VCPUs, 16 GB of memory and 160 GB of storage, while "cax31" to the AArch64 equivalent. Other server types and their current prices can be found here.

ssh-key

The file name of the SSH private key to use to authenticate with the remote host.

When deploying a machine for the first time, the following steps are taken to provision a server for the machine on the Hetzner Cloud service:

  • Create the SSH key of the machine on the Hetzner API.
  • Create a server for the machine on the Hetzner API.
  • Format the root partition of the disk using the file system of the machine’s operating system. Supported file systems are btrfs and ext4.
  • Install a minimal Guix operating system on the server using the rescue mode. This minimal system is used to install the machine’s operating system, after rebooting.
  • Reboot the server and apply the machine’s operating system on the server.

Once the server has been provisioned and SSH is available, deployment continues by delegating it to the managed-host-environment-type.

Servers on the Hetzner Cloud service can be provisioned on the AArch64 architecture using UEFI boot mode, or on the x86_64 architecture using BIOS boot mode. The (gnu machine hetzner) module exports the %hetzner-os-arm and %hetzner-os-x86 operating systems that are compatible with those two architectures, and can be used as a base for defining your custom operating system.

The following example shows the definition of two machines that are deployed on the Hetzner Cloud service. The first one uses the %hetzner-os-arm operating system to run a server with 16 shared vCPUs and 32 GB of RAM on the aarch64 architecture, the second one uses the %hetzner-os-x86 operating system on a server with 16 shared vCPUs and 32 GB of RAM on the x86_64 architecture.

(use-modules (gnu machine)
             (gnu machine hetzner))

(list (machine
       (operating-system %hetzner-os-arm)
       (environment hetzner-environment-type)
       (configuration (hetzner-configuration
                       (server-type "cax41")
                       (ssh-key "/home/charlie/.ssh/id_rsa"))))
      (machine
       (operating-system %hetzner-os-x86)
       (environment hetzner-environment-type)
       (configuration (hetzner-configuration
                       (server-type "cpx51")
                       (ssh-key "/home/charlie/.ssh/id_rsa")))))

Passing this file to guix deploy with the environment variable GUIX_HETZNER_API_TOKEN set to a valid Hetzner API key should provision two machines for you.


Next: Ejecución de Guix en una máquina virtual, Previous: Invoking guix system, Up: Configuración del sistema   [Contents][Index]