ansible學(xué)習(xí)筆記-Jinja2模板

一、背景介紹

配置文件不肯能在每個(gè)服務(wù)器上都是一樣的,目前很多配置文件需要根據(jù)自己宿主機(jī)的環(huán)境去定制相應(yīng)的配置,所以導(dǎo)致每個(gè)服務(wù)器的配置文件都不一樣,使用copy模塊去做管理肯定不現(xiàn)實(shí),此時(shí)使用Ansible提供的另一個(gè)模板template功能,它可以幫助我們完美的解決問題。

二、Jinja2模板

想學(xué)ansible的template必須先學(xué)會(huì)Jinja2模板

1、Jinja2是什么

Jinja2是基于Python書寫的模板引擎。功能比較類似于PHP的smarty模板

2、Jinja2必知必會(huì)

1.jinja2文件以.j2為后綴,也可以不寫后綴
2.jinja2中存在三種定界符

  • 注釋 {{# 注釋內(nèi)容 #}}
  • 變量引用 {{ var }}
  • 邏輯表達(dá){% %}

三、如何使用模板

一個(gè)基于Facts的Jinja2實(shí)例
root@zsh-virtual-machine:~# cat jinja.yaml
- name: jinja2 test
  hosts: all
  remote_user: root
  tasks:
    - name: update jinjia2 config
      template:
        src: /root/config.j2
        dest: /root/config.conf
root@zsh-virtual-machine:~# cat config.j2
{# check system #}
{{ ansible_date_time.date }}
hostname:{{ ansible_hostname }}
os:{{ansible_os_family}}
ip:{{ ansible_default_ipv4.address }}
{% for m in ansible_mounts if m['mount'] != "/" %}
mount:{{ m['mount'] }} total size:{{ m['size_total'] }} free_size:{{ 'size_available' }}
{% endfor %}
memory_total:{{ ansible_memory_mb.real.total }} memory_free:{{ ansible_memory_mb.real.free }}
{% if ansible_processor_vcpus > 1 %}
system cpu core more than one core
{% endif %}
root@zsh:~# cat config.conf
2020-11-05
hostname:zsh
os:Debian
ip:192.168.100.128
mount:/boot total size:1023303680 free_size:size_available
memory_total:1905 memory_free:275
system cpu core more than one core

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容