【Ansible】JSON形式のファイルを読み込む方法
【結論】
【目次】
はじめに
自称プログラマーがAnsibleのソースを理解するための備忘録です。
よって、Pythonの基礎文法については解説しません。
ファイル構成
今回は外部の.json
ファイルを読み込むため、ファイル構成も載せます。
pwd /home/vagrant/share/playbock (venv) [vagrant@localhost playbock]$ ls -l total 28 -rw-r--r--. 1 vagrant vagrant 797 7月 13 05:55 profile.json -rw-r--r--. 1 vagrant vagrant 201 7月 13 05:46 sample_003.py -rw-r--r--. 1 vagrant vagrant 441 7月 13 05:48 sample_003.yml
JSONファイルの中身
読み込むJSONファイルの中身は以下になります。
profile.json
{ "profile": [ { "name": "Java", "birthday": "1995" },{ "name": "Python", "birthday": "1991" },{ "name": "Ruby", "birthday": "1995" },{ "name": "C", "birthday": "1972" } ] }
Pythonで書いた場合
ソースのコメントがAnsibleのタスクと紐づいています。
ソース(.py)
#!/usr/bin/python # coding: utf-8 import json # jsonファイルの読み込み with open("profile.json", "r") as f: # jsonファイルの解析 json_parsed = json.load(f) # jsonファイルの出力 for item in json_parsed["profile"]: print(f"{item['birthday']} {item['name']}")
実行結果
$ python sample_003.py 1995 Java 1991 Python 1995 Ruby 1972 C
Ansibleで書いた場合
.json
ファイルを解析しているjson_string.stdout | from_json
はson_string.stdoutの中身をfrom_jsonに渡すことで解析しています。
このようにAnsibleでは、|
を使っての結果の受け渡しが可能です。
プレイブック(.yml形式)
--- - hosts: localhost # 自分自身に接続する tasks: # 以降がPythonソースに該当する部分 - name: jsonファイル読み込み command: "cat profile.json" register: json_string - name: jsonファイルの解析 set_fact: json_parsed: "{{ json_string.stdout | from_json }}" - debug: msg: "{{item.birthday}} {{item.name}}" with_items: "{{ json_parsed.profile }}"
実行結果
※ワーニングが出ている理由、hosts
でインベントリファイルのグループを指定せずにlocalhost
(自分自身に接続するためのIPアドレスが格納された変数)を指定しているためです。
参考情報
Filters — Ansible Documentation
さいごに
最近のブログは、PythonとAnsibleのコードを書くだけなので楽でいいや😊