参考 https://blog.51cto.com/13630803/2154192
一 常用功能介绍
Tasks:任务,由模板定义的操作列表
Variables:变量
Templates:模板,即使用模板语法的文件
Handlers:处理器 ,当某条件满足时,触发执行的操作
Roles:角色
meta:此目录应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系。
1.1 最简单的一个例子:
[yx@localhost playbook]$ cat a.ymal
---
- hosts: 192.168.6.220
remote_user: yx
tasks:
- name: create file
command: 'touch /home/yx/hnf.txt'
```
```bash
ansible-playbook a.yml --syntax-check #检查yaml文件的语法是否正确
ansible-playbook a.ymal # 执行
#有警告
[WARNING]: Consider using the file module with state=touch rather than running 'touch'. If you need to use command because file is
insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
#解决办法
sudo vim /etc/ansible/ansible.cfg
command_warnings = False #这行的注释去掉即可
1.2 ploybook循环
循环创建目录
---
- hosts: 192.168.10.227
user: root
tasks:
- name: change mod for file
file: path=/tmp/{{item}} state=directory
with_items:
- a
- b
- c
循环更改文件权限
首先创建三个文件
cat file.yml
- hosts: testhost
user: root
tasks:
- name: touch files
shell: touch /tmp/{1.txt,2.txt,3,txt}
然后更改文件权限
- hosts: testhost
user: root
tasks:
- name: change mod for file
file: path=/tmp/{{item}} mode=600
with_items:
- 1.txt
- 2.txt
- 3.txt
1.3 条件判断
- hosts: testhosts
user: root
gather_facts: True
tasks:
- name: use when
shell: touch /tmp/when.txt
when: facter_ipaddress == "172.7.15.106"
最后执行 ansible-playbook a.yml
这个文件的意思是:当facter_ipaddress == "172.7.15.106" 时,在这台机器上touch /tmp/when.txt
1.4 handers介绍
handlers的用处:一般是当修改某个配置文件的时候,通过handlers来执行某个任务。
例子:
- name: handlers test
hosts: web10(或者写ip)
user: root
tasks:
- name: copy file
copy: src=/etc/passwd dest=/tmp/aaa.txt
notify: test handlers
handlers:
- name: test handlers
shell: echo "111111" >> /tmp/aaa.txt
说明,只有copy模块真正执行后,才会去调用下面的handlers相关的操作。也就是说如果cpoy没看没有执行,是不会去执行handlers里面的shell相关命令。 这种比较适合配置文件发生更改后,重启服务的操作
实例2 更改配置文件,重启服务
---
- hosts: 192.168.6.220
remote_user: root
tasks:
- lineinfile:
path: /home/yx/server/nginx/config/vhost/vhost.conf
regexp: 'listen(.*)81(.*)'
line: 'listen 80;'
notify:
- reload nginx
handlers:
- name: reload nginx
service:
name: sudo /home/yx/server/nginx/sbin/nginx -s reload
post_tasks:
# 检查网页内容。
- name: review http state
command: "curl -s http://192.168.6.220:81"
register: web_context
#lineinfile更改配置文件