ansible学习笔记-Jinja2模板

一、背景介绍

配置文件不肯能在每个服务器上都是一样的,目前很多配置文件需要根据自己宿主机的环境去定制相应的配置,所以导致每个服务器的配置文件都不一样,使用copy模块去做管理肯定不现实,此时使用Ansible提供的另一个模板template功能,它可以帮助我们完美的解决问题。

二、Jinja2模板

想学ansible的template必须先学会Jinja2模板

1、Jinja2是什么

Jinja2是基于Python书写的模板引擎。功能比较类似于PHP的smarty模板

2、Jinja2必知必会

1.jinja2文件以.j2为后缀,也可以不写后缀
2.jinja2中存在三种定界符

  • 注释 {{# 注释内容 #}}
  • 变量引用 {{ var }}
  • 逻辑表达{% %}

三、如何使用模板

一个基于Facts的Jinja2实例
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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。