如何相对于主机设置 Ansible 角色的变量文件?



这是我的战术手册的细节:

行动手册树

├─ devops
|  ├─ roles
|  |  ├─ mongodb
|  |  ├─ haproxy
|  |  ├─ monit
|  |  |  ├─ vars
|  |  |  |  └─ main.yml
|  |  |  └─ ...
|  |  └─ ...
|  ├─ hosts
|  ├─ play1.yml
|  └─ play2.yml

主机

[play1]
...instructions...
[play2]
...instructions...

播放1.yml

---
- hosts: play1
  user: root
  roles:
    - haproxy
    - monit

播放2.yml

---
- hosts: play2
  user: root
  roles:
    - mongodb
    - monit

问题

我想根据主机(play1.yml或play2.yml)为monit使用不同的变量文件。我该怎么做?

非常感谢

根据http://docs.ansible.com/playbooks_best_practices.html#directory-布局建议的布局如下:

production                # inventory file for production servers
stage                     # inventory file for stage environment
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
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier
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
    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

请注意host_vars/目录。在那里,您可以包含您的角色稍后可以使用的主机特定变量。

马洛,

您应该使用"host_vars"而不是hosts_vars

 /host_vars/play1/mongodb.yml

此外,play1应与您在主机资源清册中配置的主机名称相匹配。

Ansible允许您将数据与代码分离。现在,这些数据就是您以变量的形式定义的数据。

当涉及到变量时,当你在多个地方定义了同一个变量时,就会有优先规则。建议采用

  • 在角色->默认值/目录中提供默认变量。这就是它的作用。Sane默认。

  • 从其他位置覆盖这些默认值,例如host_vars。这就是您放置主机特定vars的位置。这就是你问题的答案。

  • 但是,如果在roles->vars目录中指定相同的var,则优先级会更高。所以要小心这个。

除此之外,没有什么比这更重要的规则了。然而,ansible的创建者建议只在一个地方定义变量。我个人不会遵循这个规则,会使用正常的默认值和特定于主机/组的变量。

最新更新