Home > database >  using Jinja2 template to copy content in a file with Anisible
using Jinja2 template to copy content in a file with Anisible

Time:08-18

I would jinja2 template to copy some contents in a file depending on the distribution_major_version. So i am using if statement to achieve the goal. I have this file /mytemplates/foo.j2 Could you please confirm if this is the best practice to write the conditional statement or not?


{% if ansible_facts['distribution_major_version'] == "6" %}
    line1
    line2
    line3

{% elif ansible_facts['distribution_major_version'] == "7" or ansible_facts['distribution_major_version'] == "8"%}
    
    line1 
    line4
    line6

{% endif %}

CodePudding user response:

Put the data into a dictionary. For example,

    lines:
      '6': |
        line1
        line2
        line3
      '7': |

        line1
        line4
        line6
      '8': |

        line1
        line4
        line6

Then, the template is trivial

shell> cat templates/lines.txt.j2
{{ lines[ansible_distribution_major_version] }}

Example of a complete playbook for testing

shell> cat pb.yml
- hosts: localhost
  vars:
    lines:
      '6': |
        line1
        line2
        line3
      '7': |

        line1
        line4
        line6
      '20': |

        line1
        line4
        line20
  tasks:
    - debug:
        var: ansible_distribution_major_version
    - template:
        src: lines.txt.j2
        dest: lines.txt

gives

shell> ansible-playbook pb.yml

PLAY [localhost] *****************************************************************************

TASK [Gathering Facts] ***********************************************************************
ok: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => 
  ansible_distribution_major_version: '20'

TASK [template] ******************************************************************************
changed: [localhost]

PLAY RECAP ***********************************************************************************
localhost: ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
shell> cat lines.txt 

line1
line4
line20

Notes

  • You can use
ansible_distribution_major_version

instead of

ansible_facts['distribution_major_version']
  • You don't need the bracket notation. You can reference the attribute in dot notation
ansible_facts.distribution_major_version
  • Related