0

Folks,

I have the script below that i am using to create a list of all the block devices on my Linux machine, which have no partitions on them and later run the parted module to partition them. I am trying to save the value of item.key into a variable that could later be used by the parted module. Any help, how can i save the value of msg into a var.

- name: Print disk result

become: true

  debug:

        msg: "/dev/{{item.key}}"
  when:

     - not item.value.partitions
     - item.value.model == "VBOX HARDDISK"

  with_dict: "{{ ansible_devices }}"
MikeKim
  • 11
  • 1
  • 3

2 Answers2

0

There is no such thing as "saving a debug msg to a variable," there is only "creating a variable from the same syntax you would use in msg". Also, a debug: with become: true is a nonsensical state of affairs

- name: set vbox device fact
  set_fact:
    vbox_device_path: /dev/{{ item.key }}
  when:
  - not item.value.partitions
  - item.value.model == 'VBOX HARDDISK'
  with_dict: '{{ ansible_devices }}'

- debug:
   var: vbox_device_path
mdaniel
  • 31,240
  • 5
  • 55
  • 58
0
  # Assuming what your 'ansible_devices' looks like
  vars:
    ansible_devices:
      # model is valid, partitions are empty
      device_a:
        model: VBOX HARDDISK
        partitions: []
      # model is valid, partitions are not empty
      device_b:
        model: VBOX HARDDISK
        partitions:
          - 1_partition
          - 2_partition
      # model is not valid, partitions are empty
      device_c:
        model: BEATBOX HARDDISK
        partitions:
          - 1_partition
          - 2_partition
  tasks:
    - name: Make the variable with devices with no partitions
      # Create a variable using set_fact
      # Use json_query to filter and assign without explicitly looping ansible_devices
      set_fact:
         no_partition_list: "{{ ansible_devices | dict2items | json_query('[?(value.model==`VBOX HARDDISK`)]|[?!(value.partitions)]') }}"

    - debug:
        var: no_partition_list

What am I doing?

  • Convert the dictionary to an array
  • Apply a json query on the converted array
    • filter for value.model equal to required model name
    • then, pipe the result using |
    • then, apply another filter to find which objects don't have 'value.partitions'
      • value.partitions returns true if not empty
      • !(value.partitions) returns true if empty
    • Print the value of variable no_partition_list
Uttam
  • 576
  • 5
  • 17