Ansibleで、xmlのタグを指定して内容を取得する。

はじめに

環境

ansible 2.9.6
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /ansible/py3-venv/lib64/python3.6/site-packages/ansible
  executable location = /ansible/py3-venv/bin/ansible
  python version = 3.6.8 (default, Aug  7 2019, 17:28:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]

xmlファイル

xmlモジュールのExamplesにあったものを持ってきました。

# cat TastyBeverage.xml
<business type="bar">
  <name>Tasty Beverage Co.</name>
    <beers>
      <beer>Rochefort 10</beer>
      <beer>St. Bernardus Abbot 12</beer>
      <beer>Schlitz</beer>
   </beers>
  <rating subjective="true">10</rating>
  <website>
    <mobilefriendly/>
    <address>http://tastybeverageco.com</address>
  </website>
</business>

やりたいこと

上記xmlRochefort 10を取得します。 xmlモジュールを利用するため、lxmlをインストールしておく必要があります。

pip install lxml

Playbook

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    xml_path: /ansible/TastyBeverage.xml
    xml_xpath: /business/beers/beer
  tasks:

  - name: get content
    xml:
      path: "{{ xml_path }}"
      xpath: "{{ xml_xpath }}"
      content: text
    register: register_content

  - name: debug matches
    debug:
      var: register_content

  - name: print "Rochefort 10"
    debug:
      var: register_content.matches[0].beer

実行結果

# ansible-playbook xml.yml 
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost
does not match 'all'

PLAY [localhost] ****************************************************************************************

TASK [get content] **************************************************************************************
ok: [localhost]

TASK [debug matches] ************************************************************************************
ok: [localhost] => {
    "register_content": {
        "actions": {
            "namespaces": {},
            "state": "present",
            "xpath": "/business/beers/beer"
        },
        "changed": false,
        "count": 3,
        "failed": false,
        "matches": [
            {
                "beer": "Rochefort 10"
            },
            {
                "beer": "St. Bernardus Abbot 12"
            },
            {
                "beer": "Schlitz"
            }
        ],
        "msg": 3
    }
}

TASK [print "Rochefort 10"] *****************************************************************************
ok: [localhost] => {
    "register_content.matches[0].beer": "Rochefort 10"
}

PLAY RECAP **********************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

参考

docs.ansible.com