LoginSignup
3
2

More than 3 years have passed since last update.

【Ansible】辞書型から任意の値を取り出してリストを作成する

Last updated at Posted at 2019-12-21

はじめに

以下のymlのように、辞書型のデータから特定の値を取り出してリストを取り出せるようにします。
例)vars_promptで「ac」と入力してrouter1とrouter3という文字列を取り出してリストを作成する。
<2019/12/31:追記>
※input_dicでリストの中に辞書が入っているのは、リストにrouter3→router1と逆の順番で
 格納されるのを避けるためです。

select_test.yml
---
- name: prompt TEST
  hosts: junos
  gather_facts: no
  vars:
    ansible_python_interpreter: /usr/bin/python3
    input_dic: [
      { type: a ,name: router1 },
      { type: b ,name: router2 },
      { type: c ,name: router3 }
      ]
  vars_prompt:
    - name: "usr_input"
      prompt: "input type a to c \n"
      private: no
  tasks:
    - name: 'make list'
      set_fact:
        output_list: >-
          {%- set tmplist = [] -%}
          {%- for i in range(input_dic|length) -%}
          {%-   if input_dic[i].type in usr_input -%}
          {%-     set _ = tmplist.append(input_dic[i].name) -%}
          {%-   endif -%}
          {%- endfor -%}
          {{ tmplist }}
    - name: 'debug'
      debug:
        msg: '{{ output_list }}'

実行結果

想定通り、「ac」と入力されるとrouter1とrouter3がリストに入ります。

[ec2-user@ip-<ip addr> ansible]$ ansible-playbook -i hosts select_test.yml
input type a to c
: ac

PLAY [prompt TEST] **************************************************************************************************************************************************************************

TASK [make list] ****************************************************************************************************************************************************************************
ok: [junos_router_1]

TASK [debug] ********************************************************************************************************************************************************************************
ok: [junos_router_1] => {
    "msg": [
        "router1",
        "router3"
    ]
}

PLAY RECAP **********************************************************************************************************************************************************************************
junos_router_1             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

関連記事

<2019/12/31:追記>
ssato様による別解
https://gist.github.com/ssato/6701565f4977828e25db4962457194d6
<2020/02/08:追記>
【Ansible】外部の変数ファイルから変数の一部を読み込む(selectattr,map)

3
2
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
2