标签:条件 remote 全局变量 cat host for 根据 def mkdir
Ansibel之roles的使用roles能够根据层次型结构自动装载变量文件、task以及handlers等。简单来讲,roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中,并可以便捷地include它们,roles一般用于基于主机构建服务的场景中,但也可以用于构建守护进程等场景中。
[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服务所需要的目录
[root@rabbitmq01 httpd]# mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p
#创建php服务所需要的目录
#### 创建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.yml
#### 编写httpd服务模块
[root@rabbitmq01 httpd]# vim tasks/main.yml
[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角色变量中,一般定义在角色变量中
#### 编写mysql服务模块
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/mysql/tasks/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/mysql/tasks/main.yml
[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.yml
[root@rabbitmq01 httpd]# vim /etc/ansible/roles/php/vars/main.yml
[root@rabbitmq01 httpd]# cat /etc/ansible/roles/php/vars/main.yml
pkg: php
#### 编写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 httpd
httpd-2.4.6-80.el7.centos.1.x86_64
[root@rabbitmq02 ~]# rpm -q mariadb
mariadb-5.5.56-2.el7.x86_64
[root@rabbitmq02 ~]# rpm -q php
php-5.4.16-45.el7.x86_64
#可以看到安装成功
标签:条件 remote 全局变量 cat host for 根据 def mkdir
原文地址:http://blog.51cto.com/10693404/2155331