LoginSignup
3
6

More than 5 years have passed since last update.

Ansibleでリモート上のJSONを読ませてwith_itemsで色々とする方法

Posted at

概要

クローンしてきたリポジトリ内のpackage.jsonとかを読んで色々させるみたいな事をしたくなったら、思ったよりめんどくさかったので書き残しておく。

catして結果をfrom_jsonに食わせる

実は公式ドキュメントにちらっと書いてあった。

tasks:
  - shell: cat /some/path/to/file.json
    register: result

  - set_fact: myvar="{{ result.stdout | from_json }}"

Filters#Filters For Formatting Data — Ansible Documentation

無理矢理だなって感じが否めないけど、まぁ読めるレベルなコマンド芸なので許容するかーって気分。

例: files という項目に記載されたファイルを移動する

input.json

{
  "files": [
    "hoge.js",
    "fuga.html"
  ]
}

Ansible

- name: read json
  command: "cat /tmp/hoge/input.json"
  register: json_string

- name: parse json
  set_fact:
    json_parsed: "{{ json_string.stdout | from_json }}"

- name: move object file
  command: "mv -f /tmp/hoge/{{ item }} /etc/deployed/{{ item }}"
  ignore_errors: true
  with_items: "{{ json_parsed['files'] }}"

余談: ローカル上のJSONを読ませたい

ローカル上のJSONを読ませたい場合は lookup('file', 'var.json') | from_json みたいに書くと良いらしい。

reading json like variable in ansible - Stack Overflow

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6