Ansible使用任务在变量模板中返回变量

RMS*_*e17 4 ansible ansible-playbook

我正在尝试制作一个环境变量列表,以用于由于版本差异而在每个主机上可能具有略微不同路径的任务.

例如, /some/common/path/v_123/rest/of/path

我在variables.yml文件中创建了这些变量的列表,这些变量通过角色导入.

roles/somerole/varables/main.yml 包含以下内容

somename:
  somevar: 'coolvar'
  env:
    SOME_LIB_PATH:  /some/common/path/{{ unique_part.stdout }}/rest/of/path
Run Code Online (Sandbox Code Playgroud)

然后我有一个运行类似的任务

- name:  Get unique path part
  shell:  'ls /some/common/path/'
  register: unique_part
  tags:  workflow

- name:  Perform some actions that need some paths
  shell:  'binary argument argument'
  environment: somename.env
Run Code Online (Sandbox Code Playgroud)

但我得到一些关于未定义变量的Ansible错误.

或者我试图预定义unique_part.stdout寄存器覆盖预定义变量,但后来我得到其他ansible错误 - 模板失败.

是否有其他方法可以根据命令返回来制作这些变量?

ant*_*t31 7

您还可以使用以下事实:http: //docs.ansible.com/set_fact_module.html

# Prepare unique variables 
- hosts: myservers
  tasks: 
    - name:  Get unique path part
      shell:  'ls /some/common/path/'
      register: unique_part
      tags:  workflow

    - name: Add as Fact per for each hosts
      set_fact:
         library_path: "{{ unique_part.stdout }}"

# launch roles that use those unique variables
- hosts: myservers
  roles: 
   - somerole
Run Code Online (Sandbox Code Playgroud)

这样,您可以在使用变量之前动态地向主机添加变量.