Ansible register result of multiple commands

后端 未结 4 1739
醉话见心
醉话见心 2021-02-01 19:33

I was given a task to verify some routing entries for all Linux server and here is how I did it using an Ansible playbook

---
  - hosts: Linux
    serial: 1

            


        
4条回答
  •  自闭症患者
    2021-02-01 20:01

    Posting because I can't comment yet

    Relating to gameweld's answer, since Ansible 2.5 there's another way to accessing the iteration index.

    From the docs:

    Tracking progress through a loop with index_var

    New in version 2.5.

    To keep track of where you are in a loop, use the index_var directive with loop_control. This directive specifies a variable name to contain the current loop index:

    - name: count our fruit
      debug:
        msg: "{{ item }} with index {{ my_idx }}"
      loop:
        - apple
        - banana
        - pear
      loop_control:
        index_var: my_idx
    

    This also allows you to gather results from an array and act later to the same array, taking into account the previous results

    - name: Ensure directories exist
      file:
        path: "{{ item }}"
        state: directory
      loop:
        - "mouse"
        - "lizard"
      register: reg
    
    - name: Do something only if directory is new
      debug:
        msg: "New dir created with name '{{ item }}'"
      loop:
       - "mouse"
       - "lizard"
      loop_control:
        index_var: index
      when: reg.results[index].changed
    

    Please note that the "mouse lizard" array should be exactly the same

提交回复
热议问题