roles可以根據層次型結構自動裝載變量文件、task以及handlers等。簡單來說,roles就是經過分別將變量、文件、任務、模塊及處理器放置於單獨的目錄中,並能夠便捷地include它們,roles通常用於基於主機構建服務的場景中,但也能夠用於構建守護進程等場景中。php
[root@rabbitmq01 roles]# mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,valts,meta} -p #建立httpd服務所須要的目錄 [root@rabbitmq01 roles]# ls httpd [root@rabbitmq01 roles]# cd httpd/ [root@rabbitmq01 httpd]# ls defaults files handlers meta tasks templates vars
[root@rabbitmq01 httpd]# mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p
#建立mysql服務所須要的目錄mysql
[root@rabbitmq01 httpd]# mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p
#建立php服務所須要的目錄web
#### 建立main.yml文件
[root@rabbitmq01 httpd]# touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
[root@rabbitmq01 httpd]# touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
[root@rabbitmq01 httpd]# touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.ymlsql
#### 編寫httpd服務模塊
[root@rabbitmq01 httpd]# vim tasks/main.yml apache
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/httpd/vars/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
#定義變量:能夠定義在全局變量中,也能夠定義在roles角色變量中,通常定義在角色變量中vim
#### 編寫mysql服務模塊
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/mysql/tasks/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/mysql/tasks/main.yml centos
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/mysql/vars/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/mysql/vars/main.yml
pkg: mariadb*架構
#### 編寫php服務模塊
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/php/tasks/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/php/tasks/main.ymlssh
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/php/vars/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/php/vars/main.yml
pkg: phpide
#### 編寫role文件
[root@rabbitmq01 httpd]# vim /etc/ansible/site.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/site.yml
#### 運行文件
[root@rabbitmq01 ansible]# ansible-playbook site.yml --syntax-check
playbook: site.yml
[root@rabbitmq01 ansible]# ansible-playbook site.yml
PLAY [webserver] ****
TASK [Gathering Facts] **
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.58.132]
TASK [httpd : ensure apache is at the latest version] ***
ok: [192.168.58.132]
TASK [mysql : ensure mysql is at the latest version] ****
ok: [192.168.58.132]
TASK [php : ensure php is at the latest version] ****
changed: [192.168.58.132]
PLAY RECAP **
192.168.58.132 : ok=4 changed=1 unreachable=0 failed=0
[root@rabbitmq02 ~]# rpm -q httpdhttpd-2.4.6-80.el7.centos.1.x86_64[root@rabbitmq02 ~]# rpm -q mariadbmariadb-5.5.56-2.el7.x86_64[root@rabbitmq02 ~]# rpm -q phpphp-5.4.16-45.el7.x86_64#能夠看到安裝成功