【问题标题】:Ansible Debug msg to variableAnsible 调试消息到变量
【发布时间】:2020-07-09 12:37:07
【问题描述】:

伙计们,

我有下面的脚本,用于在我的 Linux 机器上创建所有块设备的列表,这些块设备上没有分区,然后运行 ​​parted 模块对它们进行分区。 我正在尝试将 item.key 的值保存到一个变量中,该变量以后可以由 parted 模块使用。 任何帮助,我怎样才能将 msg 的值保存到 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 }}"

【问题讨论】:

    标签: ansible ansible-facts ansible-role


    【解决方案1】:

    没有“将调试消息保存到变量”之类的东西,只有“使用与 msg 相同的语法创建变量”。此外,debug:become: true 是一种荒谬的事态

    - 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
    

    【讨论】:

      【解决方案2】:
        # 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
      

      我在做什么?

      • 将字典转换为数组
      • 对转换后的数组应用 json 查询
        • 过滤 value.model 等于所需的模型名称
        • 然后,使用 | 管道传输结果
        • 然后,应用另一个过滤器来查找哪些对象没有“value.partitions”
          • value.partitions 如果不为空则返回 true
          • !(value.partitions) 如果为空则返回 true
        • 打印变量 no_partition_list 的值

      【讨论】:

        猜你喜欢
        • 2022-07-29
        • 1970-01-01
        • 2013-04-24
        • 1970-01-01
        • 2023-01-11
        • 1970-01-01
        • 2020-10-01
        • 2022-01-26
        • 1970-01-01
        相关资源
        最近更新 更多