Fresh Startup/SaaS ideas in your inbox, every week
Launched 🚀🧑‍🚀

Ansible tip: Variables from inventory file

Ansible logo

While growing my Kubernetes cluster and working on some Ansible scripts for my infrastructure I recently realized that I’ve been under-utilizing one of the staples of ansible code, tying node-specific information to nodes in the inventory file! It was harder than I thought to use so this a quick writeup on how to do it:

Given an inventory file like this:

      hosts: # possibly ''
          os_partition_size_gb: 128
            - /dev/nvme0n1
            - /dev/nvme1n1

      hosts: # possibly ''
          os_partition_size_gb: 128
            - /dev/sda
            - /dev/sdb

Q: Why not just write your provisioning scripts flexibly enough so that they can deal with all the disparate drive paths you expect?

A: This is a very good point.

You can use the path in a template like this:

# Set up drives as provided by inventory YAML
{% for path in hostvars[inventory_hostname]['drive_paths'] %}
DRIVE{{loop.index}} {{ path }}
{% endfor %}

From a regular ansible task you can use it like so:

    - name: Drive preparation
      tags: [ "drive-partition-prep" ]
      include_tasks: process_drive.yaml
      loop: "{{ hostvars[inventory_hostname]['drive_paths'] }}"

Obviously I’m not as good at ansible as I thought because it took way more than the required amount of searching and reading docs to figure it out, so hopefully this finds someone before they search too much.

Like what you're reading? Get it in your inbox