You are on page 1of 13

Ansible playbook

誉天教育 www.yutianedu.com
ansible playbook

ansible-playbook 是一系列 ansible 命令的集合,利


用 yaml ( Yet Another Markup Language )语言
编写。 playbook 命令根据自上而下的顺序依次执行

www.redhat.com.cn
Ansible playbook 基本语法
$ vim users.yml
---
- name: create user
hosts: webservers, prod
tasks:
- name: create admin1
user:
name: admin1
state: present

$ ansible-playbook --syntax-check users.yml


$ ansible-playbook users.yml
www.redhat.com.cn
Ansible 运行结果

www.redhat.com.cn
Ansible 多个 playbook 语法
---
- name: install packages
hosts: prod
tasks:
- name: install httpd and php
yum:
name:
- httpd
- php
- mysql-server
state: present
- name: install package group
hosts: webservers
tasks:
- name: install development tools
yum:
name: "@Development tools"
state: present

- name: upgrade all package


hosts: all
tasks:
- name: upgrade all package and all hosts
yum:
name: '*'
state: latest www.redhat.com.cn
ansible 模块使用
- name: copy index.html to /var/www/html
copy:
src: index.html
dest: /var/www/html/index.html
mode: '0644'
owner: root
group: root

- name: start httpd and enable


service:
name: httpd
enabled: yes
state: started
ignore_errors: true

(可选,如果遇到错误,则忽略,否则程序运行结束)

www.redhat.com.cn
handler 的使用
在 Ansible Playbook 中, handler 事实上也是个 task ,只不过这个 task 默认
并不执行,只有在被触发时才执行。

handler 通过 notify 来监视某个或者某几个 task ,一旦 task 执行结果发生变化


,则触发 handler ,执行相应操作。

handler 会在所有的 play 都执行完毕之后才会执行,这样可以避免当 handler


监视的多个 task 执行结果都发生了变化之后而导致 handler 的重复执行
( handler 只需要在最后执行一次即可)。

www.redhat.com.cn
创建 web.conf
$ vim web.conf
<VirtualHost *:80>
DocumentRoot /var/www/web1
ServerName node3
</VirtualHost>

www.redhat.com.cn
handler 案例
$ vim web.yml
---
- name: copy file
hosts: 192.168.7.3
tasks:
- name: create /var/www/web1 directory
file:
path: /var/www/web1
state: directory
- name: copy file to web server directory
copy:
src: web.conf
dest: /etc/httpd/conf.d/web.conf
notify:
- restart service
handlers:
- name: restart service
service:
name: httpd
state: restarted
www.redhat.com.cn
-

强制运行 handler
hosts: all
force_handlers: yes
tasks:
- name: a task which always notifies its handler
command: /bin/true
notify: restart the database
- name: a task which fails because the package doesn't exist

yum:
name: notapkg
state: latest
handlers:
- name: restart the database
service:
name: mariadb
state: restarted

www.redhat.com.cn
使用循环语句
---
- name: create users
hosts: all
tasks:
- name: create jane and joe
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"

loop:
- name: jane
groups: wheel

- name: joe
groups: root

www.redhat.com.cn
使用循环语句
- name: allow http service
firewalld:
port: "{{ item }}"
permanent: yes
state: enabled
immediate: yes
loop:
- 80/tcp
- 8080/tcp

www.redhat.com.cn
使用判断语句

---
- name: install package
hosts: all
tasks:
- name: install php
yum:
name: php
state: present
when: ansible_hostname == “node2”

or when: inventory_hostname == “webservers”

www.redhat.com.cn

You might also like