首页 > 解决方案 > 连接到另一台主机时,ansible 不会读入变量

问题描述

我有一本剧本,其中读入了变量列表:

vars_files:
  - vars/myvariables.yml

 tasks:
  - name: Debug Variable List
    debug:
      msg: "An item: {{item}}"
    with_list: "{{ myvariables }}"

这会从文件 variables.yml 中打印出“myvariables”列表,其中包含:

---
myvariables:
  - variable1
  - variable2

我按预期得到以下内容。

"msg": "An item: variable1"
"msg": "An item: variable2"

但是,当我连接到另一台主机并运行相同的 Debug 语句时,它会引发错误:

vars_files:
  - vars/myvariables.yml

 tasks:
  - name: Configure instance(s)
    hosts: launched
    become: True
    remote_user: ubuntu
    port: 22
    gather_facts: False
    tasks:
      - name: Wait for SSH to come up
        delegate_to: ***
        remote_user: ubuntu
        connection: ssh
        register: item
      - name: Debug Variable List
        debug:
          msg: "An item: {{item}}"
        with_list: "{{ myvariables }}"

输出:

 "msg": "'myvariables' is undefined"

连接到非本地主机的另一台主机时如何定义变量文件?

对此的任何帮助将不胜感激。

标签: ansible

解决方案


随着“ hosts:launched ”你开始了新的剧本。将vars_files:放入本剧本的范围内(见下文)。

   - name: Configure instance(s)
     hosts: launched
     become: True
     remote_user: ubuntu
     port: 22
     gather_facts: False
     vars_files:
       - vars/myvariables.yml
     tasks:

查看范围变量


推荐阅读