Waaard Logo
Managed F/OSS services on Hetzner, OVH and LeaseWeb
Recently Launched 🚀🧑‍🚀
Waaard Logo
Unvalidated Ideas
3 fresh Startup/SaaS ideas in your inbox, every week.
Recently Launched 🚀🧑‍🚀

Ansible tip: Variables from inventory file


It's been a while since this was posted...

Hopefully the information in here is useful to you (if it isn't please get in touch!).
If you want to get the new stuff as soon as it's out though, sign up to the mailing list below.

Join the Mailing list
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:

        some.machine.you.have: # possibly 'xxx.xxx.xxx.xxx'
          os_partition_size_gb: 128
            - /dev/nvme0n1
            - /dev/nvme1n1

        the.second.machine.you.have: # possibly 'xxx.xxx.xxx.xxx'
          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