allocate largest partition with ansible when parition name varies

Viewed 99

I'm using ansible to configure some AWS servers. All the servers have a 1024 GB, or larger, partition. I want to allocate this partition and assign it to /data.

I have an ansible script that does this on my test machine. However, when I tried running it against all my AWS machines it failed on some, complaining /dev/nvme1n1 device doesn't exist. The problem is that some of the servers had a 20 GB root partition separate from the larger partition, and some don't. That means sometimes the partition I care about is nvme1n1 and sometimes it's nvm0n1.

I don't want to place a variable in the hosts file, since that file is being dynamically loaded from AWS anyways. Given that what is the easiest way to look up the largest device and get it's name in ansible so I can correctly tell ansible to allocate whichever device is largest?

1 Answers

I assume, when you talk, about "partitions", you mean "disks", as a partition will have a name like nvme0n1p1, while the disk would be called nvme0n1.

That said, I have not found an "ansible-way" to do that, so I usually parse lsblk and do some grep-magic. In your case this is what you need to run:

- name: find largest disk
  shell: |
    set -euo pipefail
    lsblk -bl -o SIZE,NAME | grep -P 'nvme\dn\d$' | sort -nr | awk '{print $2}' | head -n1
  args:
    executable: /bin/bash
  register: largest_disk

- name: print name of largest disk
  debug:
    msg: "{{ largest_disk.stdout }}"

You can use the name of the disk in the parted-module to do whatever you need with it.
Apart from that, you should add some checks before formatting your disks, so you don't overwrite something (e.g. if your playbook ran on a host before, the disk might already be formatted and contain data, and in that case, you would not format it again, because you would overwrite the existing data).

Explanation:

  • lsblk -bl -o SIZE,NAME prints the size and names of all block-devices
  • grep -P 'nvme\dn\d$' greps out all disks (partitions have some pXX in the end, remember?)
  • sort -nr sorts the output numerically by the first column (so you get the largest on top)
  • awk '{print $2}' prints only the second column (the name that is)
  • head -n1 returns the first line (containing the name of the largest disk)
Related