A-Playbook-template

时间:2023-02-23 13:00:33

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

template文件必须存放于templates目录下,且命名为 .j2 结尾

yaml/yml 文件需和templates目录平级,目录结构如下

./
├── temnginx.yml
└── templates
└── nginx.conf.j2

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

准备templates/nginx.conf.j2文件

vim temnginx.yml
- hosts: websrvs
remote_user: root
tasks:
- name: template config to remote hosts
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

Playbook中template变更替换

修改文件nginx.conf.j2 下面行为

worker_processes {{ ansible_processor_vcpus }};  

Playbook中template算术运算

worker_processes {{ ansible_processor_vcpus**2 }};
worker_processes {{ ansible_processor_vcpus+2 }};

迭代: with_items

迭代:当有需要重复性执行的任务时,可以使用迭代机制 对迭代项的引用,固定变量名为” item“ 要在task中使用with_items给定要迭代的元素列表 列表格式: 字符串 字典

- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2

上面语句的功能等同于下面的语句

- name: add user testuser1
user: name=testuser1 state=present groups=wheel
- name: add user testuser2
user: name=testuser2 state=present groups=wheel

将多个文件进行copy到被控端

---
- hosts: testsrv
remote_user: root
tasks
- name: Create rsyncd config
copy: src={{ item }} dest=/etc/{{ item }}
with_items:
- rsyncd.secrets
- rsyncd.conf
- hosts: websrvs
remote_user: root
tasks:
- name: copy file
copy: src={{ item }} dest=/tmp/{{ item }}
with_items:
- file1
- file2
- file3
- name: yum install httpd
yum: name={{ item }} state=present
ith_items:
- apr
- apr-util
- httpd
- hosts: websrvs
remote_user: root
tasks:
- name: install some packages
yum: name={{ item }} state=present
with_items:
- nginx
- memcached
- php-fpm

迭代嵌套子变量

- hosts: websrvs
remote_user: root
tasks:
- name: add some groups
group: name={{ item }} state=present
with_items:
- group1
- group2
- group3
- name: add some users
user: name={{ item.name }} group={{ item.group }} state=present
with_items:
- { name: 'user1', group: 'group1' }
- { name: 'user2', group: 'group2' }
- { name: 'user3', group: 'group3' }