模版文件是放在控制节点上的,是根据 JINJIA2 语法规则写的一个文本文件。
在剧本中使用 template 模块将模版文件分发到受控主机,方法跟 copy 类似,有 src 和 dest。
Ansible 会将模版文件内容解析后复制到各被管理节点。
模版文件可以放到剧本所在目录或其下 templates 目录中,此时可以直接调用模版文件名,否则使用绝对路径。

注意:template 模块比较特殊,只能在 playbook 中使用,不能通过 ansible 命令调用。

JINJIA2 语法

  1. {# 注释 #}
  2. {{ 变量 }}
  3. for 循环
  4. if 判断

JINJIA2 变量示例

假如我们希望在各受控节点上生成 /etc/motd 文件,内容示例如下:

This is the system servera.lab.example.com.
This is a RedHat system, version 8.0.
Only use this system with permission.
You can request access from admin@xuwang.online.

书写剧本:

# cat demo.yml 
---
- hosts: web
  vars:
    system_owner: admin@xuwang.online
  tasks:
    - name: deploy the motd file to managed hosts
      template:
        src: motd.j2
        dest: /etc/motd

书写模版文件:

# cat templates/motd.j2 
{# This is a demo #}
This is the system {{ ansible_facts['fqdn'] }}.
This is a {{ ansible_facts['distribution'] }} system, version {{ ansible_facts['distribution_version'] }}.
Only use this system with permission.
You can request access from {{ system_owner }}.

JINJIA2 for 循环示例

书写剧本:

# cat demo.yml 
---
- hosts: allhosts
  vars:
    users:
      - root
      - schwann
      - cfop
  tasks:
    - name: A demo of JINJIA2 for
      template:
        src: users.j2
        dest: /root/users

书写模版文件:

# cat templates/users.j2 
{% for myuser in users if myuser != "root" %}
user number {{ loop.index }} - {{ myuser }}
{% endfor %}

上面的比较简单,就是把变量的取值全部以单值列表的方法罗列出来,我们还可以以键值对的方法写得更灵活。

书写剧本:

# cat demo.yml 
---
- hosts: allhosts
  remote_user: root
  vars:
    shares:
      - sharename: sales
        public: yes
        write: no
      - sharename: finance
        public: no
        write: yes      
  tasks:
    - name: samba config
      template: src=smb.conf.j2 dest=/root/smb.conf

书写模版文件:

# cat templates/smb.conf.j2 
{% for item in shares %}
[{{ item.sharename }}]
    public={{ item.public }}
    writable={{ item.write }}
{% endfor %}

JINJIA2 if 循环示例

需求:172.25.250.10 不清理 messages 日志文件,其它主机既清理 messages 文件,又清理 maillog 文件。

书写剧本:

# cat demo.yml 
---
- hosts: allhosts
  remote_user: root
  tasks:
    - name: deploy shell script used for deleting logs
      template: src=delete_log.j2 dest=/root/delete_log.sh

书写模版文件:

# cat templates/delete_log.j2 
{% if ansible_facts['default_ipv4']['address'] != "172.25.250.10" %}
> /var/log/messages
{% endif %}
> /var/log/maillog
-- By 许望(RHCA、OCM、VCP)
最后修改:2020 年 04 月 28 日 10 : 33 AM
如果觉得我的文章对你有用,请随意赞赏