XMLモジュールお試ししたい
NW機器は何かとXMLを使うことがあります (ACIやPaloaltoなど)
お勉強がてらにAnsibleでXMLを操作を試してみます
xmlのファイルから対象の情報を抜き取ることがゴールです。
下準備
collectionのダウンロード
community.general 2.4.0
pythonライブラリのダウンロード
lxml==4.6.3
サンプルPlaybook
下記XPathの紹介ページからコピペしてきた、XMLをxml_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
に格納します
実行
実行してみます
成功しました
community.general.xml
の実行結果はmatches
に含まれるようでしたのでPlaybook微修正して余計な出力を減らします
- name: debug ansible.builtin.debug: msg: "{{ hits.matches }}"
再度実行してみます
想定通りに動きました。