ansible的template模块
template模块
测试facts变量
- 新建一个index.html文件
# 将变量写在文件中
welcome to {{ ansible_hostname }} on {{ ansible_ztuzex7lqa.ipv4.address }}
- 编写剧本
---
- name: template模块演示
hosts: all
tasks:
- name: 将index.html文件复制到节点,并将其中的变量替换为对应的值
template:
src: ~/play/template/index.html
dest: /var/www/html/index.html
- 剧本执行结果
[c8 root /var/www/html]# cat index.html
welcome to c8 on 10.147.17.65
[rhel7-gjb root /var/www/html]# cat index.html
welcome to rhel7-gjb on 10.147.17.40
Jinja2模板
简称j2模板
j2模板创建的时候,以.j2后缀结尾。
touch demo1.j2
ansible_manage变量作用
Ansible-managed 是一个字符串.可以插入到Ansible配置模版系统生成的文件中.如果你使用以下的自字符:
参考链接: https://ansible-tran.readthedocs.io/en/latest/docs/intro_configuration.html#ansible-managed
在ansible配置文件中添加ansible_manage变量
# 修改ansible.cfg
vim ansible.cfg
# 在[default]下添加ansible_managed = Ansible managed
ansible_managed = Ansible managed
在Jinja2模板中添加一行变量,当推送到远程主机上时就会有对应的注释信息
{{ ansible_managed }}
默认设置可以哪个用户修改和修改时间:
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
这个设置可以告知用户,Ansible修改了一个文件,并且手动写入的内容可能已经被覆盖.
需要注意的是,如果使用这一特性,这个字符串中将包含一个日期注释,如果日期更新,模版系统将会在每一次报告文件修改.
# 运行效果
[root@servera tmp]# cat j2.conf
Ansible managed: /home/student/control-flow/./j2.j2 modified on 2021-11-04 07:22:25 by student on workstation.lab.example.com
172.25.250.10 servera
Jinja2模板中如何使用变量
j2模板中使用变量,不需要“{{ 变量名 }}“,使用{{ 变量名 }}即可
j2模板中如果要在注释中使用变量,需要使用{# {{ 变量名 }} #}
Jinja2模板调用剧本中定义的变量
推送j2模板必须使用template模块,j2模板的变量值才会生效
- 先创建一个源文件
# 创建j2文件
touch source.j2
# 源文件中使用变量
{{ ansible_facts.default_ipv4.address }} {{ ansible_hostname }}
- 剧本
---
- name: 使用j2模板
hosts: all
tasks:
- name:
template:
src: ./j2.j2
dest: /tmp/j2
- 执行结果
[student@servera tmp]$ cat j2
172.25.250.10 servera
j2模板的for循环
格式是固定的
{% for user in users %}
{% endfor %}
示例1:
{# for循环示例加if判断}
{% for user in users if user == "root" %}
当前是循环第{{ loop.index }}次, -用户是 {{ user }}
{% endfor %}
示例2:批量添加hosts
列出主机清单组中的所有主机名称
j2模板的for循环结合magic变量
j2模板示例
{% for myhost in groups['myhosts'] %}
{{ myhosts}}
{% endif %}
playbook
- name: 更新所有node的hosts
hosts: all
gather_gacts: yes
tasks:
- name: 部署hosts
template:
src: template/hosts.j2
dest: /etc/hosts
j2模板的条件判断
基本语法格式
{% if finished %} # finished可以是个变量,不需要扩起来
{{ result }} # 要做的事
{{% else %}}
{{ result }}
{{% endif %}}
第九题:生成主机清单
hosts.j2模板文件
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_default_ipv4']['addresss'] }} {{ hostvars[host]['ansible_fqdn'] }} {{ hostvars[host]['ansible_hostname'] }}
{{% endfor %}}
playbook剧本
---
- name: copy myhosts
hosts: all
tasks:
- name: copy hosts
template:
src: hosts.j2
dest: /etc/myhosts
when: inventory_hostname in groups.dev