Ansible - using with_items and when conditional to

前端 未结 2 678
轮回少年
轮回少年 2021-02-01 02:10

I have a bunch of servers that have four physical drives on them (/dev/sda, sdb, sdc, and sdd). sda has the OS installed on it.

I need to format each drive except sda. I

相关标签:
2条回答
  • Your tasks can be as simple as this...

    - stat:
        path: /dev/{{item}}1
      with_items: ansible_devices.keys()
      when: item != 'sda'
      register: stats
    - command: /sbin/parted -s /dev/{{item.item}} mklabel gpt
      with_items: stats.results
      when: item.stat | default(false) and item.stat.exists
    
    0 讨论(0)
  • 2021-02-01 02:39

    You do not need to register your result with the item salt. When you register the result of a loop (e.g. with_items) the registered value will contain a key results which holds a list of all results of the loop. (See docs)

    Instead of looping over your original device list, you can loop over the registered results of the first task then:

    - name: Check if the disk is partitioned and also ignore sda
      stat: path=/dev/{{item}}1
      with_items: disk_var
      when: item != 'sda'
      register: device_stat
    
    - name: Create GPT partition table
      command: /sbin/parted -s /dev/{{ item.item }} mklabel gpt
      with_items: "{{ device_stat.results }}"
      when:
        - not item | skipped
        - item.stat.exists == false
    

    The condition not item | skipped takes care of that elements which have been filtered in the original loop (sda) will not be processed.

    While that might be a solution to your problem, your question is very interesting. There seems to be no eval feature in Jinja2. While you can concatenate strings you can not use that string as a variable name to get to its value...

    0 讨论(0)
提交回复
热议问题