ansible - 在 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
。但不幸的是,这些命令不能用于特定任务。
解决方案
由于似乎没有通用解决方案,因此我寻找至少涵盖此用例的替代方案。
方法 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'
推荐阅读
- python - ValueError:形状 1 和 2 不兼容
- java - 使用 JFreeChart 从堆积条形图中删除网格线
- sql - 更改现有表与创建新表哪种方法是野兽
- dataweave - 将十进制转换为整数 mule 4
- amazon-web-services - TCP 套接字服务器的 AWS API 网关配置
- python - 在 Python 中使用 glob 时如何选择具有最新版本号的路径?
- c# - HttpRequest on Azure Function doesn't work with https
- web-scraping - 如何为表格中的表格进行网络抓取 google-sheet通过 importxml 或 importhtml?
- python - 导出到 excel 文件时如何抑制 pandas DF 中的科学记数法?
- random - 生成和调用许多随机数的最佳方法?