五:Ansible Roles

五:Ansible Roles

一:Ansible Roles目录结构

1. 官方推荐最佳实践目录结构定义方式

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
            
            
#不常用
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
             library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

2. roles目录结构使用galaxy创建

[ ~]# cd /etc/ansible/roles/

[ roles]# tree wordpress/
nfs/                #项目名称
├── defaults        #低优先级变量
├── files           #存放文件
├── handlers        #触发器文件
├── meta            #依赖关系文件
├── tasks           #工作任务文件
├── templates       #jinja2模板文件
├── tests           #测试文件
└── vars            #变量文件

备注:只需要这些目录,ansible的roles会自动识别里面的main.yml

二:Ansible Roles依赖关系

roles允许你在使用roles时自动引入其他的roles。role依赖关系存储在roles目录中meta/main.yml文件中。

例如:推送wordpress并解压,前提条件,必须要安装nginx和php,把服务跑起来,才能运行wordpress的页面,此时我们就可以在wordpress的roles中定义依赖nginx和php的roles

[ roles]# vim /etc/ansible/roles/wordpress/meta/main.yml
dependencies:
  - { role: nginx }
  - { role: php }

如果编写了meta目录下的main.yml文件,那么Ansible会自动先执行meta目录中main.yml文件中的dependencies文件,如上所示,就会先执行nginx和php的安装。

如果安装wordpress,main.yml里有nginx和php
流程:
1.当你执行worepress的playbook,会先在meta的main.yml里找nginx
2.找到后,会在roles目录里找nginx,再去nginx目录的meta找依赖,如果无,会在tasks目录里找到安装、配置、启动等
3.装完nginx后再同理执行php
4.最后再执行wordpress的tasks

三:Ansible Roles创建目录

ansible-galaxy init 服务名 roles
[ ~]# cd /etc/ansible/roles/
[ /etc/ansible/roles]# ansible-galaxy init rsync roles

- rsync was created successfully
  [ /etc/ansible/roles]# tree 
  .
  └── rsync
    ├── defaults
    │   └── main.yml
    ├── files
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── main.yml
    ├── README.md
    ├── tasks
    │   └── main.yml
    ├── templates
    ├── tests
    │   ├── inventory
    │   └── test.yml
    └── vars
        └── main.yml

9 directories, 8 files

相关推荐