You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible剧本中引用包含角色调用的YAML文件?

解决方案:复用Ansible角色调用配置

你的需求完全可行,以下是两种常用的实现方案:

方案一:将角色列表定义为变量并引用

这种方法能让共享角色在同一个Play的上下文内执行,保持变量、权限状态一致。

  1. 创建共享角色变量文件(比如shared_roles.yml),把需要复用的角色调用定义为列表变量:
shared_roles:
  ## My custom role 2
  - role: custom_role_2
    vars:
      variable1: '10.0.0.1'
      variable2: 'template1.j2'
      variable3: 'template2.j2'
      variable4:
        - 'value1'
        - 'value2'
        - 'value3'
  ## My custom role 3
  - role: custom_role_3
    vars:
      variable_a: '8.8.8.8'
      variable_b: 'value_X'
      variable_c: 'value_Y'
      variable_d: 'value_Z'
  1. 修改主剧本,加载变量文件并在roles中展开列表:
- name: Finalize the configuration
  hosts: test_hosts
  become: true
  gather_facts: true

  vars_files:
    - vault/credentials.yml
    - shared_roles.yml  # 加载共享角色列表变量

  pre_tasks:
    - name: Set a custom variable
      set_fact:
        custom_var: "{{ hostvars['localhost']['my_custom_var'] }}"

  roles:
    ## My custom role 1
    - role: custom_role_1
    ## 展开共享角色列表
    - "{{ shared_roles }}"

方案二:拆分剧本为独立Play并导入

如果允许将共享角色放到单独的Play中执行,这种方法更直观,适合角色组逻辑独立的场景。

  1. 创建独立的共享角色剧本(比如shared_roles_playbook.yml):
- name: Execute shared roles
  hosts: test_hosts
  become: true
  gather_facts: false  # 主剧本已收集过事实,可跳过

  vars_files:
    - vault/credentials.yml

  roles:
    ## My custom role 2
    - role: custom_role_2
      vars:
        variable1: '10.0.0.1'
        variable2: 'template1.j2'
        variable3: 'template2.j2'
        variable4:
          - 'value1'
          - 'value2'
          - 'value3'
    ## My custom role 3
    - role: custom_role_3
      vars:
        variable_a: '8.8.8.8'
        variable_b: 'value_X'
        variable_c: 'value_Y'
        variable_d: 'value_Z'
  1. 修改主剧本,通过import_playbook导入该文件:
- name: Finalize the configuration
  hosts: test_hosts
  become: true
  gather_facts: true

  vars_files:
    - vault/credentials.yml

  pre_tasks:
    - name: Set a custom variable
      set_fact:
        custom_var: "{{ hostvars['localhost']['my_custom_var'] }}"

  roles:
    ## My custom role 1
    - role: custom_role_1

# 导入共享角色剧本
- import_playbook: shared_roles_playbook.yml

方案选择建议

  • 如果需要共享角色继承主Play的所有上下文(比如custom_var这类自定义变量、权限状态),优先选方案一。
  • 如果共享角色的逻辑相对独立,不需要和主Play的变量强绑定,方案二的可读性更好。

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:33:28