是否可以通配 host_vars 目录?

Is it possible to wildcard a host_vars directory?

长话短说:我建立了一个家庭实验室,我在其中使用带有 VMware 动态清单插件的 Ansible。 为了区分不同的 VM,插件将 uid 添加到主机名,例如:unique-test-vm_2612e560x1284x8457e115。这让我很难创建 host_vars 目录,因为我经常需要 运行 ansible-inventory -i ... 并复制清单名称。

问题
是否可以创建“通配符”host_vars 目录而不在目录名称中包含 uid?这意味着目录的名称将是 unique-test-vm 而不是 unique-test-vm_2612e560x1284x8457e115.

无法创建“通配符”host_vars。但是,这个用例可以通过 include_vars or by group_vars. Mind the precedence of the variables. See Variable precedence: Where should I put a variable?.

来解决

include_vars(单主机)

例如,让我们有这个库存

shell> cat hosts
testX-vm_07

让我们创造host_vars

shell> cat host_vars/testX-vm/main.yml 
test_var: test var for hosts testX-vm_*

然后下面的剧本从目录 host_vars/testX-vm 中读取变量。使 inventory_hostname 的解析符合您的需要

shell> cat pb.yml
- hosts: testX-vm_07
  tasks:
    - include_vars:
        dir: "{{ 'host_vars/' ~ my_vars_dir }}"
      vars:
        my_vars_dir: "{{ inventory_hostname.split('_').0 }}"
    - debug:
        var: test_var

给予


shell> ansible-playbook -i hosts pb.yml

PLAY [testX-vm_07] ****

TASK [include_vars] ****
ok: [testX-vm_07]

TASK [debug] ****
ok: [testX-vm_07] => 
  test_var: test var for hosts testX-vm_*

group_vars(多个主机)

例如,让我们有这个库存

shell> cat hosts
testX-vm_01
testX-vm_02
testX-vm_03
testY-vm_01
testY-vm_02
testY-vm_03

让我们创建 group_vars,它将分别由主机 testX-vm_*testY-vm_* 共享

shell> cat group_vars/testX_vm/main.yml
test_var: test var for testX_vm group
shell> cat group_vars/testY_vm/main.yml
test_var: test var for testY_vm group

然后下面的剧本在第一个剧本中创建组 testX_vmtestY_vm,并在第二个和第三个剧本中使用这些组。例如,

shell> cat pb.yml
- hosts: all
  tasks:
    - block:
        - add_host:
            name: "{{ item }}"
            groups: testX_vm
          loop: "{{ ansible_play_hosts_all|
                    select('match', '^testX-vm_(.*)$')|
                    list }}"
        - add_host:
            name: "{{ item }}"
            groups: testY_vm
          loop: "{{ ansible_play_hosts_all|
                    select('match', '^testY-vm_(.*)$')|
                    list }}"
      run_once: true
  
- hosts: testX_vm
  tasks:
    - debug:
        var: test_var

- hosts: testY_vm
  tasks:
    - debug:
        var: test_var

给予

shell> ansible-playbook -i hosts pb.yml 

PLAY [all] ****
TASK [add_host] ****
changed: [testX-vm_01] => (item=testX-vm_01)
changed: [testX-vm_01] => (item=testX-vm_02)
changed: [testX-vm_01] => (item=testX-vm_03)

TASK [add_host] ****
changed: [testX-vm_01] => (item=testY-vm_01)
changed: [testX-vm_01] => (item=testY-vm_02)
changed: [testX-vm_01] => (item=testY-vm_03)

PLAY [testX_vm] ****
ok: [testX-vm_01] => 
  test_var: test var for testX_vm group
ok: [testX-vm_02] => 
  test_var: test var for testX_vm group
ok: [testX-vm_03] => 
  test_var: test var for testX_vm group

PLAY [testY_vm] ****
ok: [testY-vm_01] => 
  test_var: test var for testY_vm group
ok: [testY-vm_02] => 
  test_var: test var for testY_vm group
ok: [testY-vm_03] => 
  test_var: test var for testY_vm group