LoginSignup
0
1

More than 5 years have passed since last update.

Ansibleにてネストするディクショナリをループできない

Last updated at Posted at 2017-06-20

概要

Ansibleでネストするディクショナリをいい感じにループできないので対応方法を備忘としてメモ。
誰か知っている人がいたら教えて下さい。

環境情報

$ ansible --version
ansible 2.3.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
  python version = 2.7.12 (default, Sep  1 2016, 22:14:00) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)]

やりたいこと

例えばini_fileモジュールを利用する場合など、下記のようなネストしたディクショナリ変数をループさせたいと思いますよね。

inifile_entries:
  section1:
    file: /var/log/messages
    format: "%b %d %H:%M:%S"
    initial_position: start_of_file
    buffer_duration: 5000
    group_name: system
    stream_name: stream1
  section2:
    file: /var/log/audit/audit.log
    initial_position: start_of_file
    buffer_duration: 5000
    group_name: audit
    stream_name: stream2
- name: configure ini file
  ini_file:
    dest: /destfile
    section: "{{ item.key }}"
    option: "ここにネストしたディクショナリのキーを設定したい"
    value: "ここにネストしたディクショナリのバリューを設定したい"
  with_dict: "{{ inifile_entries }}"

ところが、これを実現する方法がありません。

どうするか

変数をディクショナリではなくリストで定義してwith_subelementsを利用する形になります。
うーん格好悪い。

inifile_entries:
  - section: section1
    params:
      - option: file
        value: /var/log/messages
      - option: format
        value: "%b %d %H:%M:%S"
      - option: initial_position
        value: start_of_file
      - option: group_name
        value: system
      - option: stream_name
        value: stream1
  - section: section2
    params:
      - option: file
        value: /var/log/audit/audit.log
      - option: initial_position
        value: start_of_file
      - option: group_name
        value: audit
      - option: stream_name
        value: stream2
- name: configure ini file
  ini_file:
    dest: /destfile
    section: "{{ item.0.section }}"
    option: "{{ item.1.option }}"
    value: "{{ item.1.value }}"
    backup: yes
  with_subelements:
    - "{{ inifile_entries }}"
    - params
0
1
4

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
0
1