Ansible register result of multiple commands

后端 未结 4 1738
醉话见心
醉话见心 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 19:49

    A slightly different situation, which took a while to figure out. If you want to use the results of multiple items, but for changed_when, then the register variable will not have a var.results! Instead, changed_when, is evaluated for each item, and you can just directly use the register var.

    Simple example, which will result in changed: false:

    - action: command echo {{item}}
      register: out
      changed_when: "'z' in out.stdout"
      with_items:
        - hello
        - foo
        - bye
    

    Another example:

    - name: Create fulltext index for faster text searches.
      mysql_db: name={{SO_database}} state=import target=/tmp/fulltext-{{item.tableName}}-{{item.columnName}}.sql
      with_items: 
        - {tableName: Posts,  columnName: Title}
        - {tableName: Posts,  columnName: Body}
        - {tableName: Posts,  columnName: Tags}
        - {tableName: Comments, columnName: Text}
      register: createfulltextcmd
      changed_when: createindexcmd.msg.find('already exists') == -1
    

    Finally, when you do want to loop through results in other contexts, it does seem a bit tricky to programmatically access the index as that is not exposed. I did find this one example that might be promising:

    - name: add hosts to known_hosts
    shell: 'ssh-keyscan -H {{item.host}}>> /home/testuser/known_hosts'
    with_items:
      - { index: 0, host: testhost1.test.dom }
      - { index: 1, host: testhost2.test.dom }
      - { index: 2, host: 192.168.202.100 }
    when: ssh_known_hosts.results[{{item.index}}].rc == 1
    

提交回复
热议问题