首先. ./.env_file_name语法是shell语法,不能和command module一起使用,需要使用shell module。
其次,每个任务都会重置 shell 环境上下文,因为每个任务都是一个 ssh 命令往返(因此是一个新的 shell 会话),并且在一个任务中加载环境变量不会使它们可用于下一个任务。
根据您的上下文,您有一些选择:
1。清点环境变量
最好的选择是通过group_vars/host_vars 将库存端的环境放在一个变量中,每个组/主机具有不同的值,然后将其用于environment keyword
# host_vars/my_host.yml
---
env_vars:
VAR1: key1
VAR2: key2
- hosts: my_host
tasks:
- name: Display environment variables
command: env
environment: "{{ env_vars }}"
优点:
- 完整的 ansible 解决方案
- 适用于每个模块的环境
缺点:
2。为每个任务加载环境变量
如果你的任务都是shell/command(我不建议这样做,因为最好尽可能使用适当的ansible module),你可以简单地每次使用shell模块加载env文件
- hosts: my_host
tasks:
- name: Display environment variables
shell: |
. ./.env_file_name && env
- name: Do another action
shell: |
. ./.env_file_name && do_something_else
优点:
缺点:
3。将 env_file 中的环境变量加载到 ansible fact 中
此选项是一劳永逸地解析 env 文件并将其加载到 ansible fact 中以与 environment 关键字一起使用。
- hosts: my_host
tasks:
- name: Get env file content
slurp:
src: ./.env_file_name
register: env_file_content
- name: Parse environment
set_fact:
env_vars: "{{ ('{' + (env_file_content.content | b64decode).split('\n') | select | map('regex_replace', '([^=]*)=(.*)', '\"\\1\": \"\\2\"') | join(',') + '}') | from_json }}"
- name: Display environment variables
command: env
environment: "{{ env_vars }}"
或者,如果需要执行env文件而不是直接解析:
- hosts: my_host
tasks:
- name: Get env file content
shell: . ./.env_file_name && env
register: env_file_result
- name: Parse environment
set_fact:
env_vars: "{{ ('{' + env_file_result.stdout_lines | map('regex_replace', '([^=]*)=(.*)', '\"\\1\": \"\\2\"') | join(',') + '}') | from_json }}"
- name: Display environment variables
command: env
environment: "{{ env_vars }}"
优点:
- 适用于每个模块的环境
- 无需知道ansible端的环境变量
缺点: