1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Ansible】動的にリストを作成したい

1
Last updated at Posted at 2021-04-23

はじめに

<バージョン>
ansible 2.9.7
 かなり限定的な使い方になってしまうのですが、以下のように特定のリストと変換した結果の
組み合わせを作成するのに苦労したのでメモしておきます。
ネットワーク系のコマンドはスペースが入っているので、ファイル名にコマンドを入れる場合は
いちいち置換する必要があるので面倒ですね。

入力
---
sample_commands:
  - show version
  - show route
  - show running-config
出力
---
file_list:
  - cmd: show version           # 変換前
    filename: show_version.log  # 変換後
  - cmd: show route
    filename: show_route.log
  - cmd: show running-config
    filename: show_running-config.log

playbook紹介

 ループの1週目にリストが存在せずエラーにならないように、default([])と記載します。

create_list.yml
---
- name: create list
  hosts: localhost
  gather_facts: no
  vars:
    sample_commands:
      - "show version"
      - "show route"
      - "show running-config"
  tasks:    
    - name: set fact
      set_fact:
        file_list: >
          {{ file_list | default([]) + [{
          'cmd': item,
          'filename': filename
          }] }}
      loop: "{{ sample_commands }}"
      vars:
        filename: "{{ '%s.log' | format( item | replace(' ', '_')) }}"

    - name: debug
      debug:
        var: file_list

実行結果

 想定通りの結果を得ることが出来ました。

ログ
[ec2-user@ip-<ip-addr> ansible]$ ansible-playbook create_list.yml 

PLAY [create list] *****************************************************************************************************

TASK [set fact] ********************************************************************************************************
ok: [localhost] => (item=show version)
ok: [localhost] => (item=show route)
ok: [localhost] => (item=show running-config)

TASK [debug] ***********************************************************************************************************
ok: [localhost] => 
  file_list:
  - cmd: show version
    filename: show_version.log
  - cmd: show route
    filename: show_route.log
  - cmd: show running-config
    filename: show_running-config.log

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

参考記事

dictionary - Ansible Playbookでホストグループから辞書のリストを作成する

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?