Home > Blockchain >  Rendering a specific Config file Template within Ansible Roles
Rendering a specific Config file Template within Ansible Roles

Time:06-16

I'm new to Ansible. I have many router config templates to generate but want to specify in the playbook which specific template should be generated. I'm showing only two template files here to keep things simple. I'm able to generate configs based on my setup, all works well. However, I don't know how to execute a single template file within roles in the site.yaml playbook. Here's my directory structure:

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

Here's how site.yaml playbook is constructed:

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

  roles:
    -  router

Here's the main.yaml in the tasks folder:

---
- 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 }}"

When I run the playbook it generates all config templates. I want to be able to specify which config template to render, for example: routers_4331 or routers_881.

How can I specify this in the playbook?

CodePudding user response:

i suppose you have a link between list of hostnames and file.j2 (same number for example)

    - 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 }}"

the first task selects files j2 from folder templates (following the regex pattern)

the second task add the corresponding path of file j2 to the file containing the hostnames

  • Related