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:
all:
children:
some_machine_group_name:
hosts:
some.machine.you.have: # possibly 'xxx.xxx.xxx.xxx'
os_partition_size_gb: 128
drive_paths:
- /dev/nvme0n1
- /dev/nvme1n1
another_machine_group_name:
hosts:
the.second.machine.you.have: # possibly 'xxx.xxx.xxx.xxx'
os_partition_size_gb: 128
drive_paths:
- /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.

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.