在Ansible Roles中呈现特定的配置文件模板



我是Ansible的新手。我有很多路由器配置模板要生成,但想在剧本中指定应该生成哪个特定的模板。为了简单起见,我在这里只展示两个模板文件。我能够根据我的设置生成配置,一切都很好。但是,我不知道如何在站点中的角色中执行单个模板文件。yaml的剧本。下面是我的目录结构:

├── roles
│   ├── router
│       ├── tasks
│       │   └── main.yaml
│       ├── templates
│       │   ├── 4331-router.j2
│       │   ├── 881-router.j2
│       │   └── base.j2
│       └── vars
│           └── main.yaml
│   
└── site.yaml

网站是这样的。构造Yaml剧本:

---
- name: Generate Router Configuration Files
hosts: localhost
roles:
-  router

这是主要的。任务文件夹中的Yaml:

---
- name: Generate 4331 configuration files
template: src=4331-router.j2 dest=~/ansible/configs/{{item.hostname}}.txt
with_items: "{{ routers_4331 }}"

- name: Generate 881 configuration files
template: src=881-router.j2 dest=~/ansible/configs/{{item.hostname}}.txt
with_items: "{{ routers_881 }}"

当我运行playbook时,它生成所有配置模板。我希望能够指定要渲染哪个配置模板,例如:routers_4331或routers_881。

我如何在剧本中指定这个?

我假设您在主机名列表和文件之间有一个链接。J2(以相同的数字为例)

- find:
path: "path of templates" # give the right folder of templates
file_type: file
patterns: '[0-9]+-.*?.j2'  #search files format xxxx-yyyy.j2
use_regex: yes
register: result

- set_fact:
hosting: "{{ hosting | d([]) + _dico }}"
loop: "{{ result.files | map(attribute='path') | list }}"
vars:
_src: "{{  item }}"
_num: "{{ (_src | basename).split('-') | first }}"
_grp: "{{ 'routers' ~ '_' ~ _num }}"
_hosts: "{{ lookup('vars', _grp)  }}"
_dico: >-
{%- set ns = namespace() -%}
{%- set ns.l = [] -%}
{%- for h in _hosts -%}
{%- if h.update({'pathj2': _src}) -%}{%- endif -%}
{%- set ns.l = ns.l + [h] -%}
{%-  endfor -%}
{{ ns.l }}
- name: Generate configuration files
template: 
src: "{{item.pathj2}}"
dest: ~/ansible/configs/{{item.hostname}}.txt
loop: "{{ hosting }}"

第一个任务从文件夹模板中选择文件j2(遵循regex模式)

第二个任务将文件j2的对应路径添加到包含主机名的文件

最新更新