美文网首页
ansible playbook(1) 初学playbook

ansible playbook(1) 初学playbook

作者: xuweizhen | 来源:发表于2018-08-01 17:36 被阅读0次

初学playbook

案例

playbook只有一个play

---
- hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum: pkg=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:
    - name: restart apache
      service: name=httpd state=restarted

指定主机和用户
每一个play都可以指定主机和用户去执行task
- hosts: webservers
hosts 行的内容是一个或多个组或主机的 patterns,以逗号为分隔符
remote_user: root
执行用户名
sudo命令
sudo: yes
支持sudo命令,可以放在task内,作为一个task使用sudo命令
name
task必须要有名字,以便输出日志中区分哪一个task
moudle格式

task:
  - name: make sure apache is running
    service: name=httpd state=running

service moudle 使用 key=value 格式的参数
command和shell格式
但是command 和 shell ,它们不使用 key=value 格式的参数:

tasks:
  - name: disable selinux
    command: /sbin/setenforce 0

得到失败shell结果
如果你想要shell执行失败的结果,可以使用||

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand || /bin/true

||表示左边shell命令执行失败后才会执行右边命令
具体可了解:https://blog.csdn.net/zxk364961978/article/details/54848773

或者使用:ignore_errors: True,忽略错误

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand
    ignore_errors: True

变量
在action中可以使用变量,但需要在vars 那里先定义一个变量 :

tasks:
  - name: create a virtual host file for {{ vhost }}
    template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}

handlers发生改变后执行
当远程主机发生改动后,在每一个task完成后,执行notify,且只会执行一次
notify下面列出的就是handlers,得到notify通知后执行。且也只会执行一次

- name: template configuration file
  template: src=template.j2 dest=/etc/foo.conf
  notify:
     - restart memcached
     - restart apache
handlers:
    - name: restart memcached
      service:  name=memcached state=restarted
    - name: restart apache
      service: name=apache state=restarted

Handlers 最佳的应用场景是用来重启服务,或者触发系统重启操作.

执行一个playbook

ansible-playbook playbook.yml -f 10

-f 10: 并发数是10
查看这个playbook会影响到那些host

ansible-playbook playbook.yml --list-hosts

参考文档:

ansible playbook指南:http://www.ansible.com.cn/docs/playbooks.html

相关文章

网友评论

      本文标题:ansible playbook(1) 初学playbook

      本文链接:https://www.haomeiwen.com/subject/dgujmftx.html