如何将任务文件中的信息/变量返回到父进程?

问题描述 投票:0回答:1

我有一个在数组变量上循环单个任务文件的任务:

- ansible.builtin.include_tasks: my_task.yml
  loop: "{{ my_list }}"
- debug:
    var: my_var

我想在

my_var
中创建/更新
my_task.yml
变量,然后在父游戏中使用它:

my_task.yml

- set_fact:
    my_var: "{{ my_var | default([]) + ["new value"] }}"

在父游戏中调试时

my_var
,它是空的。

如何让

my_task.yml
中定义的变量在父游戏中可用?我已经尝试过 set_fact 和 set_stats 。

ansible ansible-facts
1个回答
0
投票

问:如何让

my_task.yml
中定义的变量在父游戏中可用?

一个最小的示例手册

main.yml

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    my_list: "{{ range(0, 3) | list }}"

  tasks:

    - name: Loop directly
      debug:
        msg: "{{ item }}"
      loop: "{{ my_list }}"

    - name: Loop included
      include_tasks:
        file: my_task.yml
      loop: "{{ my_list }}"
      loop_control:
        extended: true

    - debug:
        var: my_var

和任务文件

my_task.yml

  - name: Loop included {{ item }}
    set_fact:
      my_var: "{{ my_var | default([]) + [ 'Loop index #' ~ ansible_loop.index0 ] }}"

将产生

的输出
TASK [Loop directly] **************************************************
ok: [localhost] => (item=0) =>
  msg: 0
ok: [localhost] => (item=1) =>
  msg: 1
ok: [localhost] => (item=2) =>
  msg: 2

TASK [Loop included] **************************************************
included: /home/ansible-user/test/my_task.yml for localhost
included: /home/ansible-user/test/my_task.yml for localhost => (item=1)
included: /home/ansible-user/test/my_task.yml for localhost => (item=2)

TASK [Loop included 0] ************************************************
ok: [localhost]

TASK [Loop included 1] ************************************************
ok: [localhost]

TASK [Loop included 2] ************************************************
ok: [localhost]

TASK [debug] **********************************************************
ok: [localhost] =>
  my_var:
  - 'Loop index #0'
  - 'Loop index #1'
  - 'Loop index #2'

=======================================================================
debug ----------------------------------------------------------- 0.07s
Loop included --------------------------------------------------- 0.06s
Loop directly --------------------------------------------------- 0.06s
Loop included 0 ------------------------------------------------- 0.05s
Loop included 1 ------------------------------------------------- 0.05s
Loop included 2 ------------------------------------------------- 0.05s
© www.soinside.com 2019 - 2024. All rights reserved.