うさラボ

お勉強と備忘録

AnsibleのXMLモジュールお試ししてみた

XMLモジュールお試ししたい

NW機器は何かとXMLを使うことがあります (ACIやPaloaltoなど)

お勉強がてらにAnsibleでXMLを操作を試してみます
xmlのファイルから対象の情報を抜き取ることがゴールです。

下準備

collectionのダウンロード

community.general 2.4.0

pythonライブラリのダウンロード

lxml==4.6.3

サンプルPlaybook

下記XPathの紹介ページからコピペしてきた、XMLxml_dataに格納しています

https://www.w3schools.com/xml/xpath_nodes.asp

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    xml_data: |
      <?xml version="1.0" encoding="UTF-8"?>
      <bookstore>
        <book>
          <title lang="en">Harry Potter</title>
          <author>J K. Rowling</author>
          <year>2005</year>
          <price>29.99</price>
        </book>
      </bookstore>

  tasks:
    - name: community.general.xml
      community.general.xml:
        xmlstring: "{{ xml_data }}"
        xpath: /bookstore/book/title
        content: text
      register: hits

    - name: debug
      ansible.builtin.debug:
        msg: "{{ hits }}"

community.general.xmlモジュールを利用します、変数でxmlを渡すときはxmlstringを利用します。
xmlファイルを直接開きたい場合はpathで対象のxmlファイルを選択します

xpathで抽出したいデータがある階層を指定し、 contentをtextにし<title></title>で囲われているTextを抜き出します。

<title lang="en">Harry Potter</title>

実行結果はhits に格納します

実行

実行してみます

f:id:usage_automate:20210414221636p:plain 成功しました
community.general.xmlの実行結果はmatchesに含まれるようでしたのでPlaybook微修正して余計な出力を減らします

    - name: debug
      ansible.builtin.debug:
        msg: "{{ hits.matches }}"

再度実行してみます

f:id:usage_automate:20210414221215p:plain

想定通りに動きました。