Ricerca nel sito web

Come installare e utilizzare Ansible su Debian 11


Su questa pagina

  1. Prerequisiti
  2. Installa Ansible su Debian 11
    1. Installa Ansible utilizzando APT
    2. Installa Ansible tramite PIP

    Ansible è uno strumento di gestione della configurazione gratuito, open source e uno dei più popolari. È uno strumento multipiattaforma che semplifica il cloud computing, la gestione della configurazione, l'installazione dei pacchetti e la configurazione del servizio. Utilizza un file YAML che contiene i passaggi che l'utente desidera eseguire su una determinata macchina. Con Ansible puoi configurare e gestire più host con un solo comando. Ansible è un'alternativa agli altri strumenti di gestione della configurazione come Chef e Puppet.

    In questo articolo, ti mostrerò come installare e utilizzare lo strumento di gestione della configurazione Ansible su Debian 11.

    Prerequisiti

    • Tre server che eseguono Debian 11.
    • Su ogni server è configurata una password di root.

    Ai fini di questo tutorial, utilizzeremo la seguente configurazione:

    • Controller Ansible - 192.168.10.9
    • Host Ansible - 192.168.10.10, 192.168.10.11

    Installa Ansible su Debian 11

    Per impostazione predefinita, il pacchetto Ansible non è incluso nel repository predefinito Debian. Esistono due modi per installare Ansible su Debian 11.

    1. Uso del comando APT
    2. Uso del comando PIP

    Installa Ansible usando APT

    Innanzitutto, dovrai installare alcune dipendenze nel tuo sistema. È possibile installare le dipendenze richieste utilizzando il seguente comando:

    apt-get install gnupg2 curl wget -y

    Una volta installate tutte le dipendenze, modifica APT source.list e aggiungi il repository Ansible:

    nano /etc/apt/sources.list

    Aggiungi la seguente riga:

    deb http://ppa.launchpad.net/ansible/ansible/ubuntu focal main
    

    Salva e chiudi il file quando hai finito, quindi aggiungi la chiave Ansible GPG usando il seguente comando:

    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367

    Dovresti vedere il seguente output:

    Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
    Executing: /tmp/apt-key-gpghome.lFEjztT9TY/gpg.1.sh --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367
    gpg: key 93C4A3FD7BB9C367: public key "Launchpad PPA for Ansible, Inc." imported
    gpg: Total number processed: 1
    gpg:               imported: 1
    

    Ora aggiorna il repository e installa Ansible con il seguente comando:

    apt-get update
    apt-get install ansible -y

    Una volta installato Ansible, verifica la versione di Ansible con il seguente comando:

    ansible --version

    Dovresti ottenere il seguente output:

    ansible 2.10.8
      config file = None
      configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
      ansible python module location = /usr/lib/python3/dist-packages/ansible
      executable location = /usr/bin/ansible
      python version = 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110]
    

    Installa Ansible usando PIP

    Innanzitutto, dovrai installare Python e PIP sul tuo sistema. Puoi installarlo usando il seguente comando:

    apt-get install python3 python3-pip -y

    Una volta completata l'installazione, utilizzare il comando pip per installare Ansible come mostrato di seguito:

    pip install ansible

    Installa sshpass

    sshpass è uno strumento da riga di comando che consente di fornire password con comandi SSH. Qui utilizzeremo sshpass sul nodo del controller Ansible con Ansible per autenticare un host remoto.

    Puoi installare sshpass con il seguente comando:

    apt-get install sshpass -y

    Successivamente, connettiti al primo host remoto ansible per aggiungere un'impronta digitale SSH al tuo file known_hosts:

    ssh 

    Ti verrà chiesto di fornire una password SSH come mostrato di seguito:

    The authenticity of host '192.168.10.10 (192.168.10.10)' can't be established.
    ECDSA key fingerprint is SHA256:q3zMoJ6qdjYvAdL7/w4Z0gm0ZEgGOB+rNIPKEMdYS6o.
    Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
    Warning: Permanently added '192.168.10.10' (ECDSA) to the list of known hosts.
    Password: 
    

    Fornisci la tua password e premi Invio per aggiungere un'impronta digitale SSH.

    Successivamente, connettiti al secondo host remoto ansible per aggiungere un'impronta digitale SSH al tuo file known_hosts:

    ssh 

    Ti verrà chiesto di fornire una password SSH come mostrato di seguito:

    The authenticity of host '192.168.10.11 (192.168.10.11)' can't be established.
    ECDSA key fingerprint is SHA256:q3zMoJ6qdjYvAdL7/w4Z0gm0ZEgGOB+rNIPKEMdYS6o.
    Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
    Warning: Permanently added '192.168.10.11' (ECDSA) to the list of known hosts.
    Password: 
    

    Fornisci la tua password e premi Invio.

    Ora puoi utilizzare il comando sshpass per verificare la connessione SSH:

    sshpass -p yourpassword ssh 

    Crea il file di inventario degli host Ansible

    Successivamente, dovrai creare un file di inventario per definire l'indirizzo IP, il nome utente, la password e la porta SSH degli host remoti:

    nano ~/.hosts

    Aggiungi le seguenti righe:

    [servers]
    server1 ansible_host=192.168.10.10 ansible_user=root ansible_ssh_pass=password ansible_ssh_port=22
    server2 ansible_host=192.168.10.11 ansible_user=root ansible_ssh_pass=password ansible_ssh_port=22
    

    Salva e chiudi il file.

    Nota: nel file sopra, useremo host remoti IP, nome utente, password e porta SSH.

    Lavorare con Ansible

    Ansible fornisce molti moduli che ti aiutano a gestire gli host remoti.

    La sintassi di base per eseguire Ansible come mostrato di seguito:

    ansible -i [inventory_file] -m [module] [host]

    Verifichiamo la connettività ping a tutti gli host:

    ansible -i ~/.hosts -m ping all

    Se tutto va bene, dovresti ottenere il seguente output:

    server2 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }
    server1 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }
    

    Se si desidera verificare la connettività ping dell'unico server1, eseguire il seguente comando:

    ansible -i ~/.hosts -m ping server1

    Dovresti ottenere il seguente output:

    server1 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }
    

    È possibile utilizzare il modulo shell per eseguire tutti i comandi sugli host remoti.

    Ad esempio, per eseguire il comando \free -m\ su server2, eseguire il seguente comando:

    ansible -i ~/.hosts -m shell -a "free -m" server2

    Dovresti vedere il seguente output:

    server2 | CHANGED | rc=0 >>
                   total        used        free      shared  buff/cache   available
    Mem:            1982         128         491           2        1363        1669
    Swap:              0           0           0
    

    Per eseguire un comando \df -h\ su server2, eseguire il seguente comando:

    ansible -i ~/.hosts -m shell -a "df -h" server2

    Dovresti ottenere il seguente output:

    server2 | CHANGED | rc=0 >>
    Filesystem      Size  Used Avail Use% Mounted on
    udev            976M     0  976M   0% /dev
    tmpfs           199M  404K  198M   1% /run
    /dev/sda1        50G  2.4G   45G   5% /
    tmpfs           992M  124K  992M   1% /dev/shm
    tmpfs           5.0M     0  5.0M   0% /run/lock
    tmpfs           199M     0  199M   0% /run/user/0
    

    Ansible fornisce un modulo apt per installare qualsiasi pacchetto sugli host remoti.

    Per installare il pacchetto Nginx su server1, eseguire il seguente comando:

    ansible -i ~/.hosts -m ansible.builtin.apt -a "name=nginx state=present" server1

    Dovresti ottenere il seguente output:

    server1 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "cache_update_time": 1631424599,
        "cache_updated": false,
        "changed": true,
        "stderr": "",
        "stderr_lines": [],
            "Upgrading binary: nginx.",
            "Setting up nginx (1.18.0-6.1) ...",
            "Processing triggers for man-db (2.9.4-2) ...",
            "Processing triggers for libc-bin (2.31-13) ..."
        ]
    }
    

    Per verificare lo stato del servizio Nginx su server1, eseguire il seguente comando:

    ansible -i ~/.hosts -m shell -a "systemctl status nginx" server1

    Dovresti ottenere il seguente output:

    server1 | CHANGED | rc=0 >>
    ? nginx.service - A high performance web server and a reverse proxy server
         Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
         Active: active (running) since Sun 2021-09-12 05:55:36 UTC; 49s ago
           Docs: man:nginx(8)
        Process: 10761 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
        Process: 10764 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
       Main PID: 10871 (nginx)
          Tasks: 2 (limit: 2341)
         Memory: 5.8M
            CPU: 54ms
         CGroup: /system.slice/nginx.service
                 ??10871 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
                 ??10874 nginx: worker process
    
    Sep 12 05:55:36 ansible systemd[1]: Starting A high performance web server and a reverse proxy server...
    Sep 12 05:55:36 ansible systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
    Sep 12 05:55:36 ansible systemd[1]: Started A high performance web server and a reverse proxy server.
    

    Ansible fornisce un modulo utente per creare e gestire gli utenti sugli host remoti.

    Per creare un nuovo utente denominato user1 su server1, eseguire il seguente comando:

    ansible -i ~/.hosts -m ansible.builtin.user -a "name=user1 password=yourpassword" server1

    Dovresti vedere il seguente output:

    server1 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": true,
        "comment": "",
        "create_home": true,
        "group": 1000,
        "home": "/home/user1",
        "name": "user1",
        "password": "NOT_LOGGING_PASSWORD",
        "shell": "/bin/sh",
        "state": "present",
        "system": false,
        "uid": 1000
    }
    

    Conclusione

    In questo articolo, hai imparato come installare Ansible con APT e PIP. Hai anche imparato come utilizzare diversi moduli Ansible per gestire host remoti. Spero che ora tu abbia abbastanza comprensione di Ansible. Non esitate a chiedermi se avete domande.