大网数据广告活动
服务器运维问答

Ansible variables across plays without group/host vars

· 52CE 我爱测

I have a variable that is very specific to a playbook, not necessarily tied to a host or host group. I would like to declare this variable in the playbook itself, and have it shared between plays without having to redeclare. Exam…

问题原文

原帖链接 · Rino Bino · CC BY-SA 4.0

I have a variable that is very specific to a playbook, not necessarily tied to a host or host group.

I would like to declare this variable in the playbook itself, and have it shared between plays without having to redeclare.

Example below is a simple 2 play actions in a playbook. The variable "foo" isn't really related to the host or the host group, it's specific to the playbook internally, so I would like that var to stay local to the playbook.

- name: "Test1"
  hosts: localhost
  vars:
    foo: bar
  tasks:
    - name: "Debug1"
      ansible.builtin.debug:
        msg: " {{ foo }} "


- name: "Test2 - this will fail"
  hosts: localhost
  tasks:
    - name: "Debug2"
      ansible.builtin.debug:
        msg: "{{ foo }}"

I realize this example doesn't make logical sense to build like this split across plays for a single host. It's an ultra-simplified version of the actual problem I'm facing to demonstrate what I would like to do.

My question is this: Without creating new group_vars/host_vars files for "localhost", combining tasks to the single play, and without re-declaring the foo variable for each play, is there a way to make these plays share the foo variable?

已采纳解答

原帖链接 · Rino Bino · CC BY-SA 4.0

Figured this out a few minutes after asking of course!

This works, using set_fact to make the variables persistent. This will only work if each play has a matching hosts: value

- name: "Test1"
  hosts: localhost
  vars:
    foo: bar
    zoo: zar
  tasks:
    - name: "Make host play variables persistent"
      ansible.builtin.set_fact:
        foo: "{{ foo }}"
        zoo: "{{ zoo }}"

- name: "Test2 - variables now exist in this play"
  hosts: localhost
  tasks:
    - name: "DebugFoo"
      ansible.builtin.debug:
        msg: "{{ foo }}"
    - name: "DebugZoo"
      ansible.builtin.debug:
        msg: "{{ zoo }}"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-09-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。