首页 > 解决方案 > 在 Ansible 中共享或包含特定任务的变量

问题描述

我有以下剧本:

# Some tasks which uses the default user specified in group_vars/all

- name: Check if installer exists
  win_stat:
    path: \\path_to_installer\installer.exe
  vars:
    # TODO Reuse variables
    ansible_become: yes
    ansible_become_method: runas
    ansible_become_user: "{{ network_share_user }}"
    ansible_become_password: "{{ network_share_user_pw }}"
    ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only
  register: installer_info

- name: Run installation
  win_package:
    path: \\path_to_installer\installer.exe
    product_id: '...'
    arguments: '/q'
  vars:
    # TODO Reuse variables
    ansible_become: yes
    ansible_become_method: runas
    ansible_become_user: "{{ network_share_user }}"
    ansible_become_password: "{{ network_share_user_pw }}"
    ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only
  when: installer_info.stat.exists == True

# Some other tasks

通常任务的用户在 中定义group_vars/all,但如果我需要访问网络共享,我必须使用通用用户(参见上面的剧本变量)。

我怎样才能为那些特定的“网络驱动器”任务共享这个变量块?不影响剧本中的其他任务。

最好将变量放在一个单独的文件中,并将它们包含在诸如 withinclude_vars或之类的任务中vars_files。但不幸的是,这些命令不能用于特定任务。

标签: ansible

解决方案


由于似乎没有通用解决方案,因此我寻找至少涵盖此用例的替代方案。

方法 1: 使用一个并为整个块定义变量:

- block:
  - name: Check if installer exists
    win_stat:
      path: \\path_to_installer\installer.exe
    register: installer_info

  - name: Run installation
    win_package:
      path: \\path_to_installer\installer.exe
      product_id: '...'
      arguments: '/q'
    when: installer_info.stat.exists == True
  vars:
      ansible_become: yes
      ansible_become_method: runas
      ansible_become_user: "{{ network_share_user }}"
      ansible_become_password: "{{ network_share_user_pw }}"
      ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only

方法 2:更进一步(如果您有多个相似的块)。使用单独的文件并包含它:

文件install_software.yml

- block:
  - name: Check if installer exists
    win_stat:
      path: "{{ path }}"
    register: installer_info

  - name: Run installation
    win_package:
      path: "{{ path }}"
      product_id: "{{ product_id }}"
      arguments: "{{ arguments }}"
    when: installer_info.stat.exists == True
  vars:
      ansible_become: yes
      ansible_become_method: runas
      ansible_become_user: "{{ network_share_user }}"
      ansible_become_password: "{{ network_share_user_pw }}"
      ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only

主要剧本:

- import_tasks: install_software.yml
  vars:
    path: \\path_to_installer\installer1.exe
    product_id: '...'
    arguments: '/q'

- import_tasks: install_software.yml
  vars:
    path: \\path_to_installer\installer2.exe
    product_id: '...'
    arguments: '/q'

推荐阅读