template(12)

template

template功能:根据模块文件动态生成对应的配置文件

template文件必须存放于templates目录下,且命名为 .j2 结尾
yaml/yml 文件需和templates目录平级,目录结构如下:
./
├── temnginx.yml
└── templates
└── nginx.conf.j2

示例
利用template 同步nginx配置文件

准备templates/nginx.conf.j2文件
vim temnginx.yml
- hosts: webserver
  remote_user: root
  
  tasks:
    - name: template config to remote hosts
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

ansible-playbook temnginx.yml

template变更替换

范例:

使用pstree查看进程需要安装 yum -y install psmisc

#修改文件nginx.conf.j2  #在这里需要自己安装一个nginx然后进行配置文件的复制,复制为j2文件
mkdir templates
vim templates/nginx.conf.j2
worker_processes {{ ansible_processor_vcpus }};

vim temnginx2.yml
---
- hosts: webserver
  remote_user: root

  tasks:
    - name: install nginx
      yum: name=nginx
    - name: template config to remote hosts
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf 
    - name: start service
      service: name=nginx state=started enabled=yes

ansible-playbook temnginx2.yml

template算术运算

范例

vim nginx.conf.j2 
worker_processes {{ ansible_processor_vcpus**2 }};    #这里是对cpu进行相关的运算
worker_processes {{ ansible_processor_vcpus+2 }}; 

范例:

[root@ansible ansible]#vim templates/nginx.conf.j2
worker_processes {{ ansible_processor_vcpus**3 }};#和上边一样,对cpu进行算数运算

[root@ansible ansible]#cat templnginx.yml
---
- hosts: webserver
  remote_user: root

  tasks:
    - name: install nginx
      yum: name=nginx
    - name: template config to remote hosts
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart nginx
    - name: start service
      service: name=nginx state=started enabled=yes

  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

ansible-playbook  templnginx.yml --limit 10.0.0.8

posted @ 2022-11-22 14:31  yutoujun  阅读(17)  评论(0编辑  收藏  举报