ansible之创建可复用playbook,ansibleplaybook


为了避免playbook过于冗长,也同时为了可以重复利用和组织管理playbook,ansible有三种方法来实现这些功能:includes, imports, roles.

incloud和import允许用户把大的playbook分散为小的文件,其可以用在多个父playbook之上,也可以在同一个playbook中多次使用。

roles不仅能把taskas融合在一起,甚至是变量,handlers,模块,和插件。角色也可以通过Ansible Galaxy上传和共享,不同于include和导import。

最佳的组织方法就是role。

production                # inventory file for production servers 关于生产环境服务器的清单文件
stage                     # inventory file for stage environment 关于 stage 环境的清单文件

group_vars/
   group1                 # here we assign variables to particular groups 这里我们给特定的组赋值
   group2                 # ""
host_vars/
   hostname1              # if systems need specific variables, put them here 如果系统需要特定的变量,把它们放置在这里.
   hostname2              # ""

library/                  # if any custom modules, put them here (optional) 如果有自定义的模块,放在这里(可选)
filter_plugins/           # if any custom filter plugins, put them here (optional) 如果有自定义的过滤插件,放在这里(可选)

site.yml                  # master playbook 主 playbook
webservers.yml            # playbook for webserver tier Web 服务器的 playbook
dbservers.yml             # playbook for dbserver tier 数据库服务器的 playbook

roles/
    common/               # this hierarchy represents a "role" 这里的结构代表了一个 "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

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

我们在前文分享了我们基础的组织结构.

那这种结构适用于何种应用场景? 很多!若我想重新配置整个基础设施,如此即可:

ansible-playbook -i hosts site.yml

那只重新配置所有的 NTP 呢?太容易了:

ansible-playbook -i hosts site.yml --tags ntp

只重新配置我的 Web 服务器呢?:

ansible-playbook -i hosts webservers.yml

只重新配置我在波士顿的 Web服务器呢?:

ansible-playbook -i hosts webservers.yml --limit boston

个人写的playbook已经托管至GitHub

https://github.com/lyjason/ansible

查看评论

相关内容

    暂无相关文章