
ネットワーク デバイス (スイッチ、ルータ、ファイアウォール、主に Cisco) の設定ファイルの作成、展開、更新を自動化するために、パイプラインを作成する必要があります。この作業を実行する方法はいろいろ考えられますが、ためらっています。プロセスは、データ ファイルを読み取り、文字列 (例: ホスト名に "NR" が含まれる) を検索し、問題がなければ、ライブラリ内の適切なテンプレートを選択して設定ファイルを作成するというものです。
私はAnsibleを試してみましたが、私にはよく分かりませんでした。他の方法はJinjaライブラリで、私はこのようなことを試しました
#! /usr/bin/python
import sys
from jinja2 import Template
template = """ hostname {{hostname}}
no ip domain lookup
ip domain name local.lab
ip name-server {{name_server_pri}}
ip name-server {{name_server_sec}}
ntp server {{ntp_server_pri}} prefer
ntp server {{ntp_server_sec}} """
data= {
"hostname": "core-test-01",
"name_server_pri": "1.1.1.1",
"name_server_sec": "8.8.8.8",
"ntp_server_pri": "0.pool.ntp.org",
"ntp_server_sec": "1.pool.ntp.org",
}
j2_template = Template(template)
print(j2_template.render(data))
この場合、ライブラリからテンプレート ファイルを読み込むにはどうすればよいですか (また、データ ファイル内で検索したい文字列に関してはどうすればよいですか)?
答え1
質問:「データ ファイルを読み取り、文字列を検索します (例: ホスト名に "NR" が含まれる)... ライブラリ内の適切なテンプレートを選択して、構成ファイルを作成します。「
例えば、データファイル
> ssh admin@test_11 cat /tmp/hostname
hostname-NR
> ssh admin@test_12 cat /tmp/hostname
hostname-NS
> ssh admin@test_13 cat /tmp/hostname
hostname-NX
そしてテンプレート
> cat templates/nr.j2
# template nr.j2
> cat templates/ns.j2
# template ns.j2
> cat templates/nt.j2
# template nt.j2
> cat templates/default.j2
# template default.j2
下の演劇
- hosts: test_11,test_12,test_13
vars:
templates_lib:
- {contains: "{{ my_hostname is search('NR') }}", template: nr.j2}
- {contains: "{{ my_hostname is search('NS') }}", template: ns.j2}
- {contains: "{{ my_hostname is search('NT') }}", template: nt.j2}
tasks:
- command: cat /tmp/hostname
register: result
- template:
src: "{{ my_template) }}"
dest: /tmp/test.conf
vars:
my_hostname: "{{ result.stdout }}"
my_template: "{{ templates_lib|
selectattr('contains')|
map(attribute='template')|
first|default('default.j2') }}"
与える
> ssh admin@test_11 cat /tmp/test.conf
# template nr.j2
> ssh admin@test_12 cat /tmp/test.conf
# template ns.j2
> ssh admin@test_13 cat /tmp/test.conf
# template default.j2