Ansible - delete all partitions on a given list of disks
I'm having serious trouble to do something that seems very trivial, I guess I'm probably going on the wrong way.
The scenario is quite simple, I have a host_group in which I have a list of disks like:
disks: "['sdb', 'sdc']"
Then on a task I have:
#Read device information (always use unit when probing)
- parted: device=/dev/{{ item }} unit=MiB register: "{{ item }}_info" with_items:
- "{{ disks }}"
This will read the information of the disks and store it in 2 variables: sdb_info and sdc_info
The problem starts when I try to delete all the partitions on the given disks, the normal task to do this is:
# Remove all partitions from disk
- parted:
device: /dev/sdc
number: "{{ item.num }}"
state: absent with_items:
- "{{ sdc_info.partitions }}"
That works fine but I cannot adapt it to support the list of disks.
I'm doing something like:
# Remove all partitions from disk
- parted:
device: /dev/{{ item[0] }}
number: "{{ item[1].num }}"
state: absent with_nested:
- "{{ disks }}"
- "{{ {{ disks }}_info.partitions }}"
The issue seems to be "{{ {{ disks }}_info.partitions }}" because I cannot loop over a loop. I'm probably choosing a very dum approach.... any help will be much appreciated.
Solution 1:
Register to single variable info.
- parted:
device=/dev/{{ item }}
unit=MiB
register: info
loop: "{{ disks }}"
Use subelements to iterate the disks and partitions. For example
- hosts: localhost
vars:
disks:
- sda
- sdc
tasks:
- parted:
device: "/dev/{{ item }}"
unit: MiB
register: info
loop: "{{ disks }}"
- debug:
msg: "{{ item.0.disk.dev }} {{ item.1.num }}"
loop: "{{ info.results|subelements('partitions') }}"
gives
"msg": "/dev/sda 1"
"msg": "/dev/sda 2"
"msg": "/dev/sda 3"
"msg": "/dev/sda 5"
"msg": "/dev/sdc 1"