Professional Documents
Culture Documents
誉天教育 www.yutianedu.com
ansible 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
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
(可选,如果遇到错误,则忽略,否则程序运行结束)
www.redhat.com.cn
handler 的使用
在 Ansible Playbook 中, handler 事实上也是个 task ,只不过这个 task 默认
并不执行,只有在被触发时才执行。
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”
www.redhat.com.cn