ansible-howto

First steps with ansible:

Install

$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible
vi /etc/ansible/hosts

[webserver]
192.168.56.102

Now we create the key and deliver to the remote host:

looser@looserbox:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/looser/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/looser/.ssh/id_rsa.
Your public key has been saved in /home/looser/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:o6B5YX0CBSNdtLTdrUolaiO6ehnh1K21PSJEgUNCZ58 looser@looserbox
The key's randomart image is:
+--[ RSA 2048]----+
|        .        |
|       + .       |
|      . B .      |
|     o * +       |
|    X * S        |
|   + O o . .     |
|    .   E . o    |
|       . . o     |
|        . .      |
+-----------------+
looser@looserbox:~$

Deliver:

looser@looserbox:~$ ssh-copy-id looser@192.168.56.102
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/looser/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
looser@192.168.56.102's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'looser@192.168.56.102'"
and check to make sure that only the key(s) you wanted were added.

looser@looserbox:~$

Test ping with autorized user:

looser@looserbox:~$ ansible all -m ping -u looser
192.168.56.102 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
looser@looserbox:~$

Now we create a list of tasks for being executed on "webserver" group:

looser@looserbox:~$ cat webserver.yml
---
- hosts: webserver
  user: root
  sudo: no

  tasks:
    ##
    # Instalación de paquetes necesarios.
    ##
    - name: General | Instalación de paquetes requeridos.
      action: apt pkg={{ item }} state=installed
      with_items:
        - php
        - apache2
        - mysql-server
        - mysql-client
        - php-mysql
        - php-apcu
        - php-apcu-bc
        - php-xmlrpc
        - php-soap
        - php-gd
        - unzip
        - python-mysqldb

    ##
    # Configuración de Apache2.
    ##
    - name: Apache2 | Habilitar módulos
      action: command a2enmod rewrite vhost_alias

    ##
    # Reinicio de servicios
    ##
    - name: Restart Apache
      action: service name=apache2 state=restarted
looser@looserbox:~$

And call to execute doing:

looser@looserbox:~$ ansible-playbook webserver.yml
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and make sure become_method is 'sudo' (default). This feature will be removed in version 2.6. Deprecation
warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

PLAY [webserver] *********************************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************************
ok: [192.168.56.102]

TASK [General | Instalación de paquetes requeridos.] *********************************************************************************************************************************
ok: [192.168.56.102] => (item=[u'php', u'apache2', u'mysql-server', u'mysql-client', u'php-mysql', u'php-apcu', u'php-apcu-bc', u'php-xmlrpc', u'php-soap', u'php-gd', u'unzip', u'python-mysqldb'])
[DEPRECATION WARNING]: State 'installed' is deprecated. Using state 'present' instead.. This feature will be removed in version 2.9. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

TASK [Apache2 | Habilitar módulos] ***************************************************************************************************************************************************
changed: [192.168.56.102]

TASK [Restart Apache] ****************************************************************************************************************************************************************
changed: [192.168.56.102]

PLAY RECAP ***************************************************************************************************************************************************************************
192.168.56.102             : ok=4    changed=2    unreachable=0    failed=0

looser@looserbox:~$

+

Ansible commands

Ansible example command without playbook: (- a "ad-hoc")

looser@looserbox:/etc/ansible$ ansible webserver -a "ping -c2 www.google.es"
192.168.56.102 | SUCCESS | rc=0 >>
PING www.google.es (216.58.201.131) 56(84) bytes of data.
64 bytes from mad06s25-in-f131.1e100.net (216.58.201.131): icmp_seq=1 ttl=54 time=2.28 ms
64 bytes from mad06s25-in-f131.1e100.net (216.58.201.131): icmp_seq=2 ttl=54 time=3.10 ms

--- www.google.es ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 2.284/2.696/3.109/0.415 ms

looser@looserbox:/etc/ansible$

Ansible example command without playbook: (-m "module")

looser@looserbox:~$ ansible webserver -m ping
192.168.56.102 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Ansible commands through sudo:

install:

looser@looserbox:~$ ansible webserver -b --become-user=root -K -m shell -a 'apt install gparted -y'
SUDO password:
192.168.56.102 | SUCCESS | rc=0 >>
Leyendo lista de paquetes...
Creando árbol de dependencias...
Leyendo la información de estado...
Paquetes sugeridos:
  reiser4progs jfsutils kpartx dmraid gpart
Se instalarán los siguientes paquetes NUEVOS:
  gparted
0 actualizados, 1 nuevos se instalarán, 0 para eliminar y 0 no actualizados.
Se necesita descargar 462 kB de archivos.
Se utilizarán 2.138 kB de espacio de disco adicional después de esta operación.
Des:1 http://es.archive.ubuntu.com/ubuntu bionic/main amd64 gparted amd64 0.30.0-3ubuntu1 [462 kB]
Descargados 462 kB en 0s (1.333 kB/s)
Seleccionando el paquete gparted previamente no seleccionado.
(Leyendo la base de datos ... 186576 ficheros o directorios instalados actualmente.)
Preparando para desempaquetar .../gparted_0.30.0-3ubuntu1_amd64.deb ...
Desempaquetando gparted (0.30.0-3ubuntu1) ...
Procesando disparadores para mime-support (3.60ubuntu1) ...
Procesando disparadores para desktop-file-utils (0.23-1ubuntu3.18.04.1) ...
Procesando disparadores para man-db (2.8.3-2) ...
Procesando disparadores para gnome-menus (3.13.3-11ubuntu1) ...
Configurando gparted (0.30.0-3ubuntu1) ...
Procesando disparadores para hicolor-icon-theme (0.17-2) ...
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

looser@looserbox:~$

Uninstall:

looser@looserbox:~$ ansible webserver -b --become-user=root -K -m shell -a 'apt remove gparted -y'
SUDO password:
192.168.56.102 | SUCCESS | rc=0 >>
Leyendo lista de paquetes...
Creando árbol de dependencias...
Leyendo la información de estado...
Los paquetes indicados a continuación se instalaron de forma automática y ya no son necesarios.
  libatkmm-1.6-1v5 libcairomm-1.0-1v5 libglibmm-2.4-1v5 libgtkmm-2.4-1v5
  libpangomm-1.4-1v5 libsigc++-2.0-0v5
Utilice «sudo apt autoremove» para eliminarlos.
Los siguientes paquetes se ELIMINARÁN:
  gparted
0 actualizados, 0 nuevos se instalarán, 1 para eliminar y 0 no actualizados.
Se liberarán 2.138 kB después de esta operación.
(Leyendo la base de datos ... 186680 ficheros o directorios instalados actualmente.)
Desinstalando gparted (0.30.0-3ubuntu1) ...
Procesando disparadores para mime-support (3.60ubuntu1) ...
Procesando disparadores para desktop-file-utils (0.23-1ubuntu3.18.04.1) ...
Procesando disparadores para man-db (2.8.3-2) ...
Procesando disparadores para gnome-menus (3.13.3-11ubuntu1) ...
Procesando disparadores para hicolor-icon-theme (0.17-2) ...
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

looser@looserbox:~$

Install/uninstall through module apt:

looser@looserbox:~$ ansible webserver -b --become-user=root -K -m apt -a 'name=gparted state=removed'
SUDO password:
[DEPRECATION WARNING]: State 'removed' is deprecated. Using state 'absent' instead.. This feature will be removed in version 2.9. Deprecation warnings can be
disabled by setting deprecation_warnings=False in ansible.cfg.
192.168.56.102 | SUCCESS => {
    "changed": true,
    "stderr": "",
    "stderr_lines": [],
    "stdout": "Reading package lists...\nBuilding dependency tree...\nReading state information...\nThe following packages were automatically installed and are no longer required:\n  libatkmm-1.6-1v5 libcairomm-1.0-1v5 libglibmm-2.4-1v5 libgtkmm-2.4-1v5\n  libpangomm-1.4-1v5 libsigc++-2.0-0v5\nUse 'sudo apt autoremove' to remove them.\nThe following packages will be REMOVED:\n  gparted\n0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.\nAfter this operation, 2138 kB disk space will be freed.\n(Reading database ... \r(Reading database ... 5%\r(Reading database ... 10%\r(Reading database ... 15%\r(Reading database ... 20%\r(Reading database ... 25%\r(Reading database ... 30%\r(Reading database ... 35%\r(Reading database ... 40%\r(Reading database ... 45%\r(Reading database ... 50%\r(Reading database ... 55%\r(Reading database ... 60%\r(Reading database ... 65%\r(Reading database ... 70%\r(Reading database ... 75%\r(Reading database ... 80%\r(Reading database ... 85%\r(Reading database ... 90%\r(Reading database ... 95%\r(Reading database ... 100%\r(Reading database ... 186680 files and directories currently installed.)\r\nRemoving gparted (0.30.0-3ubuntu1) ...\r\nProcessing triggers for mime-support (3.60ubuntu1) ...\r\nProcessing triggers for desktop-file-utils (0.23-1ubuntu3.18.04.1) ...\r\nProcessing triggers for man-db (2.8.3-2) ...\r\nProcessing triggers for gnome-menus (3.13.3-11ubuntu1) ...\r\nProcessing triggers for hicolor-icon-theme (0.17-2) ...\r\n",
    "stdout_lines": [
        "Reading package lists...",
        "Building dependency tree...",
        "Reading state information...",
        "The following packages were automatically installed and are no longer required:",
        "  libatkmm-1.6-1v5 libcairomm-1.0-1v5 libglibmm-2.4-1v5 libgtkmm-2.4-1v5",
        "  libpangomm-1.4-1v5 libsigc++-2.0-0v5",
        "Use 'sudo apt autoremove' to remove them.",
        "The following packages will be REMOVED:",
        "  gparted",
        "0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.",
        "After this operation, 2138 kB disk space will be freed.",
        "(Reading database ... ",
        "(Reading database ... 5%",
        "(Reading database ... 10%",
        "(Reading database ... 15%",
        "(Reading database ... 20%",
        "(Reading database ... 25%",
        "(Reading database ... 30%",
        "(Reading database ... 35%",
        "(Reading database ... 40%",
        "(Reading database ... 45%",
        "(Reading database ... 50%",
        "(Reading database ... 55%",
        "(Reading database ... 60%",
        "(Reading database ... 65%",
        "(Reading database ... 70%",
        "(Reading database ... 75%",
        "(Reading database ... 80%",
        "(Reading database ... 85%",
        "(Reading database ... 90%",
        "(Reading database ... 95%",
        "(Reading database ... 100%",
        "(Reading database ... 186680 files and directories currently installed.)",
        "Removing gparted (0.30.0-3ubuntu1) ...",
        "Processing triggers for mime-support (3.60ubuntu1) ...",
        "Processing triggers for desktop-file-utils (0.23-1ubuntu3.18.04.1) ...",
        "Processing triggers for man-db (2.8.3-2) ...",
        "Processing triggers for gnome-menus (3.13.3-11ubuntu1) ...",
        "Processing triggers for hicolor-icon-theme (0.17-2) ..."
    ]
}
looser@looserbox:~$

More cases, running sudo changes in a .yml :

ansible-playbook-sudo