One place for hosting & domains

      April 2021

      How To Use Loops in Ansible Playbooks



      Part of the Series:
      How To Write Ansible Playbooks

      Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

      When automating server setup, sometimes you’ll need to repeat the execution of the same task using different values. For instance, you may need to change permissions of multiple files, or create multiple users. To avoid repeating the task several times in your playbook file, it’s better to use loops instead.

      In programming, a loop allows you to repeat instructions, typically until a certain condition is met. Ansible offers different looping methods, with the loop keyword being the most recommended option for longer term compatibility.

      The following example creates three different files on the /tmp location. It uses the file module within a task that implements a loop using three different values.

      Create a new file called playbook-06.yml in your ansible-practice directory:

      • nano ~/ansible-practice/playbook-06.yml

      Then add the following lines to the new playbook file:

      ~/ansible-practice/playbook-06.yml

      ---
      - hosts: all
        tasks:
          - name: creates users files
            file:
              path: /tmp/ansible-{{ item }}
              state: touch
            loop:
              - sammy
              - erika
              - brian
      

      Save and close the file when you’re done.

      Then, run ansible-playbook with the same connection arguments from the previous examples. Again, we’re using an inventory file named inventory and a user named sammy, but you should change these values accordingly:

      • ansible-playbook -i inventory playbook-06.yml -u sammy

      You’ll get output like this, showing each individual item value that was used within the loop:

      Output

      ... TASK [creates users files] ****************************************************************************** changed: [203.0.113.10] => (item=sammy) changed: [203.0.113.10] => (item=erika) changed: [203.0.113.10] => (item=brian) ...

      For more detailed information on how to use loops when writing Ansible playbooks, please refer to the official documentation.



      Source link

      How To Install and Manage System Packages in Ansible Playbooks



      Part of the Series:
      How To Write Ansible Playbooks

      Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

      Automating the installation of required system packages is a common operational task in Ansible playbooks, since a typical application stack requires software from different sources.

      The apt module manages system packages on Debian-based operating systems such as Ubuntu, the distribution we’re using on remote nodes throughout this guide. The following playbook will update the apt cache and then make sure Vim is installed on remote nodes.

      Create a new file called playbook-09.yml in your ansible-practice directory:

      • nano ~/ansible-practice/playbook-09.yml

      Then add the following lines to the new playbook file:

      ~/ansible-practice/playbook-09.yml

      ---
      - hosts: all
        become: yes
        tasks:
          - name: Update apt cache and make sure Vim is installed
            apt:
              name: vim
              update_cache: yes
      

      Save and close the file when you’re done.

      Notice that we’ve included the become directive in the beginning of the play. This is required since installing packages requires administrative system permissions.

      Removing a package is done in a similar way, the only change is that you have to define the package state to absent. The state directive has a default value of present, which will make sure that the package is installed on the system, regardless of the version. The package will be installed if not present. To assure you have the latest version of a package, you can use latest instead. This will cause apt to update the requested package if that is not on their latest version.

      Remember to provide the -K option when running this playbook, since it requires sudo permissions:

      • ansible-playbook -i inventory playbook-09.yml -u sammy -K

      Output

      BECOME password: PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.10] TASK [Update apt cache and make sure Vim is installed] ************************************************** ok: [203.0.113.10] PLAY RECAP ********************************************************************************************** 203.0.113.10 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      When installing multiple packages, you can use a loop and provide an array containing the names of the packages you want to install. The following playbook will make sure the packages vim, unzip, and curl are installed and in their latest version.

      Create a new file called playbook-10.yml in your ansible-practice directory, on your Ansible control node:

      • nano ~/ansible-practice/playbook-10.yml

      Add the following content to the new playbook file:

      ~/ansible-practice/playbook-10.yml

      ---
      - hosts: all
        become: yes
        tasks:
          - name: Update apt cache and make sure Vim, Curl and Unzip are installed
            apt:
              name: "{{ item }}"
              update_cache: yes
            loop:
              - vim
              - curl
              - unzip
      

      Save and close the file when you have finished.

      Then, run ansible-playbook with the same connection arguments from the previous examples, and don’t forget to include the -K option since this playbook requires administrative privileges:

      • ansible-playbook -i inventory playbook-09.yml -u sammy -K

      You’ll see output like this, indicating that the same task run through three iterations using the different values we have provided: vim, curl, and unzip:

      Output

      BECOME password: PLAY [all] *************************************************************************************************************************************** TASK [Gathering Facts] *************************************************************************************************************************** ok: [203.0.113.10] TASK [Update apt cache and make sure Vim, Curl and Unzip are installed] ************************************************************************** ok: [203.0.113.10] => (item=vim) ok: [203.0.113.10] => (item=curl) changed: [203.0.113.10] => (item=unzip) PLAY RECAP *************************************************************************************************************************************** 203.0.113.10 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      For more details on how to manage system packages, including how to remove packages and how to use advanced apt options, you can refer to the official documentation.



      Source link

      How To Create and Use Templates in Ansible Playbooks



      Part of the Series:
      How To Write Ansible Playbooks

      Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

      Templates allow you to create new files on the nodes using predefined models based on the Jinja2 templating system. Ansible templates are typically saved as .tpl files and support the use of variables, loops, and conditional expressions.

      Templates are commonly used to configure services based on variable values that can be set up on the playbook itself, in included variable files, or obtained via facts. This enables you to create more versatile setups that adapt behavior based on dynamic information.

      To try it out this feature with a practical example, create a new directory to hold non-playbook files inside your ansible-practice directory:

      • mkdir ~/ansible-practice/files

      Next, create a new template file for an HTML landing page. Later on, we’ll set up a playbook which will configure your remote nodes to serve the landing page with Nginx:

      • nano ~/ansible-practice/files/landing-page.html.j2

      Add the following content to the template file:

      ~/ansible-practice/files/landing-page.html.j2

      <!doctype html>
      <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>{{ page_title }}</title>
        <meta name="description" content="Created with Ansible">
      </head>
      <body>
          <h1>{{ page_title }}</h1>
          <p>{{ page_description }}</p>
      </body>
      </html>
      

      Save and close the file when you’re done.

      This template uses two variables that must be provided whenever the template is applied in a playbook: page_title and page_description.

      The following playbook sets up the required variables, installs Nginx, and then applies the specified template to replace the existing, default Nginx landing page located at /var/www/html/index.nginx-debian.html. The last task uses the ufw module to enable tcp access on port 80, in case you have your firewall enabled as recommended in our initial server setup guide.

      Create a new file called playbook-11.yml in your ansible-practice directory:

      • nano ~/ansible-practice/playbook-11.yml

      Add the following content to the new playbook file:

      ~/ansible-practice/playbook-11.yml

      ---
      - hosts: all
        become: yes
        vars:
          page_title: My Landing Page
          page_description: This is my landing page description.
        tasks:
          - name: Install Nginx
            apt:
              name: nginx
              state: latest
      
          - name: Apply Page Template
            template:
              src: files/landing-page.html.j2
              dest: /var/www/html/index.nginx-debian.html
      
          - name: Allow all access to tcp port 80
            ufw:
              rule: allow
              port: '80'
              proto: tcp    
      

      Remember to provide the -K option if you run this playbook, since it requires sudo permissions:

      • ansible-playbook -i inventory playbook-11.yml -u sammy -K

      Output

      BECOME password: PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.10] TASK [Install Nginx] ************************************************************************************ changed: [203.0.113.10] TASK [Apply Page Template] ****************************************************************************** changed: [203.0.113.10] TASK [Allow all access to tcp port 80] ****************************************************************** changed: [203.0.113.10] PLAY RECAP ********************************************************************************************** 203.0.113.10 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      When the play has finished, you can access the web server’s public IP address from your browser. You’ll see a page like this:

      Screenshot showing custom landing page

      That means your playbook worked as expected, and the default Nginx page was replaced by the template you have created.



      Source link