Ansible:覆盖角色默认值

我的目录布局如下

inventories/
   group_vars/     # common variables production and staging
      all
   production/
      hosts              
      group_vars/     
         all      # common to all production 
         groupN.yml
      host_vars/
         all     # common to all production 
         hostnameN.yml

   staging/
      hosts               
      group_vars/     
         all      # common to all staging 
         groupN.yml
      host_vars/
         all     # common to all staging 
         hostnameN.yml      

site.yml
production.yml
staging.yml

roles/
    docker/
         defaults
             # let's assume there defaults contain default_docker_version=a.b.c
         tasks
         ...
    webtier/
  • 我的问题是:

-如何使用主机特定的值覆盖role / common / default中的值?

也就是说,我想要具有特定于环境的角色的默认值。

示例我希望生产主机具有x.y.z的docker版本,并且暂存具有a.b.c的docker_version

我尝试将变量添加到host_vars中-但是ansible仍然找不到它。


-可以进行的结构布局有改进吗?

ddoo88 回答:Ansible:覆盖角色默认值

您可以在清单中具有特定于环境的docker版本的值。然后,在剧本中调用角色时,您需要传递值以覆盖角色中的默认值。

以下是通过覆盖值从剧本中调用角色的代码段

 roles:
   - { role: roles/common,docker_version: "{{ docker_version }}" }

docker_version是变量,该变量传递给角色以覆盖该值及其值,该值及其值来自剧本清单。

  

请参考here来检查ansible中变量的优先级,这非常有帮助。

,
  

Q:“如何使用主机特定的值覆盖角色/普通/默认值?”

A:对于 staging ,将变量放入目录

inventories/staging/host_vars

对于生产,将变量放入目录

inventories/production/host_vars

例如

$ cat inventories/production/hosts
prod-001
prod-002
prod-003

$ cat inventories/production/hosts/host_vars/prod-001
docker_version: "x.y.z"

$ cat inventories/production/hosts/host_vars/prod-002
docker_version: "x.y.z"

$ cat inventories/production/hosts/host_vars/prod-003
docker_version: "x.y.z"

使用特定于组的值会更有效。例如

$ cat inventories/production/hosts
[group_01]
prod-001
prod-002
prod-003

$ cat inventories/production/group_vars/group_01
docker_version: "x.y.z"

全部。例如

$ cat inventories/production/group_vars/all
docker_version: "x.y.z"
  

Q:“结构布局中是否可以进行改进?”

A:您的案例是Alternative Directory Layout,其中生产登台库存在单独的目录中。 configure inventory是必要的。例如

ansible-playbook -i inventories/staging/hosts site.yml

在这种情况下,将使用目录 staging / hosts / host_vars staging / hosts / group_vars 中的清单变量。可以测试

ansible-inventory -i inventories/staging/hosts --list

根据您的用例,还有其他options而不是改进。


注释

  • 库存/ group_vars / all 没用
  • 库存/生产/ host_vars / all 是没用的(分期相同)
本文链接:https://www.f2er.com/3141011.html

大家都在问