LoginSignup
4
1

More than 3 years have passed since last update.

【Ansible×NW自動化】templateモジュールでNW機器の設定を作りたい

Last updated at Posted at 2020-06-20

はじめに

<バージョン>
ansible 2.9.1

templateモジュールでは、jinja2というテンプレートエンジンを用いてファイルを生成出来ます。
今回は、このモジュールを使ってjunos機器の設定ファイルを作成します。

必要なファイル

(1) 変数ファイル(yml)

sample.yml
---
hostname: router1
intfs:
  - name: et-0/0/0
    vlan: 10
    address: 10.0.0.1
    mask: 30
  - name: et-0/0/2
    vlan: 20
    address: 10.0.0.5
    mask: 30
static:
  route: 10.1.1.0/24
  next_hop: 172.16.0.254

(2)templateファイル(j2)

sample.j2
set system host-name {{ hostname }}
{% for intf in intfs %}
set interfaces {{ intf.name }} vlan-tagging
set interfaces {{ intf.name }} unit 0 vlan-id {{ intf.vlan }}
set interfaces {{ intf.name }} unit 0 family inet address {{ intf.address }}/{{ intf.mask }}
{% endfor %}
set routing-options static route {{ static.route }} next-hop {{ static.next_hop }}

<注意>
{%- for intf in intfs -%}のように、{}の中にハイフンを入れることを出来ますが、
このように書くと、行同士が繋がってしまうので注意してください。
参考記事 - 【Ansible】ハイフンの位置による改行の変化~templateモジュール編~

(3)Playbook
実際は、読み込む変数ファイル(sample.yml)を機器ごとに用意した方がいいと思いますが
今回は省略しています。

template_test.yml
---
- name: template TEST
  hosts: localhost
  gather_facts: no
  tasks:
    - name: 'include vars'      # task1 - 変数ファイルを読み込む
      include_vars: sample.yml  # 機器ごとに用意するなら、{{ inventory_hostname }}.ymlとかにする

    - name: 'template'          # task2 - 変数ファイルを元に設定ファイルを作成する
      template:
        src: sample.j2   # j2はなるべ複数の機器で共通にした方管理がしやすい
        dest: result.txt # 機器ごとに作成するなら、{{ inventory_hostname }}.confとかにする

実行結果

モジュールを使って作成しているので、記載ミスが起きないのが便利な所ですね。

出力1
set system host-name router1
set interfaces et-0/0/0 vlan-tagging
set interfaces et-0/0/0 unit 0 vlan-id 10
set interfaces et-0/0/0 unit 0 family inet address 10.0.0.1/30
set interfaces et-0/0/2 vlan-tagging
set interfaces et-0/0/2 unit 0 vlan-id 20
set interfaces et-0/0/2 unit 0 family inet address 10.0.0.5/30
set routing-options static route 10.1.1.0/24 next-hop 172.16.0.254

設定内容の修正があった場合の差分比較

「(1)変数ファイル(yml)で差分比較した場合」と「(2)設定ファイルで差分比較した場合」で、
WinMergeの結果を載せませた。
修正があった際に、(1)では修正が2か所で済むのですが、(2)をそのまま修正しようとすると
4か所修正が必要になります。修正箇所の差は、設定内容が複雑に(多く)なるほど広がっていくので
(1)の良さが伝わると思います。

・(1)変数ファイル(yml)で差分比較した場合
差分1.PNG

・(2)設定ファイルファイルで差分比較した場合
interfaceの変更(et-0/0/2 → et-0/0/3)の変更は3行に渡って必要なので、修正ミスが発生しやすい。
差分2.PNG

まとめ

templateモジュールでNW機器のconfigを設定するメリットとしては以下のようなものがあります
・NW機器の設定を知らなくても設定ファイルを作成することが出来る
・変数ファイルがyml形式なので変更時の差分比較がしやすい
・設定が変更になった場合、変数ファイル(yml)やtemplateファイル(j2)だけを変更すれば
 いいので記載ミスが減る & 変更に時間が掛からない
・変数ファイル(yml)やtemplateファイル(j2)が同じならば、毎回同じ結果が得られる

関連記事

【Ansible】ハイフンの位置による改行の変化~templateモジュール編~

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