2

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.

João Pereira
  • 39
  • 3
  • 7

2 Answers2

4

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"
Vladimir Botka
  • 5,138
  • 8
  • 20
0

The following could be used to wipe out all of the existing partitions in a single task:

- command: wipefs -a {{ selected_device_id_path }}

Aside from it being a single command, the advantage here is that the partition removal process is not fragile to failures while calling parted info on devices that might have been (intentionally) altered in a way that parted did not expect. One such case of this is if passing through a device (via virtio-blk) to a VM and setting its block size to its native value, which may not be the same as QEMU's default (512bytes).

spaceman spiff
  • 201
  • 2
  • 5