2 ploybook使用

参考 Ansible之Playbook详解、案例_51CTO博客_ansible playbook详解

一  常用功能介绍

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 playbook循环

循环创建目录
---
- 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更改配置文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值