包括在剧本的第一次播放中生成的变量



我有一个剧本,它由两个剧本组成: 1:在本地主机上创建库存文件和变量文件 2:在生成的清单上使用命令中的变量

示例剧本:

---
- name: Generating inventory and variables
hosts: localhost
vars_files:
-  variables.yml  #variables file used for automating
tasks:
- name: Creating inventory template
template:
src: hosts.j2
dest: "./inventories/{{location}}/hosts"
mode: 0777
force: yes
ignore_errors: yes
run_once: true
- meta: refresh_inventory
- name: Creating predefined variables from a template
template:
src: predefined-vars.yml.j2
dest: "./variables/predefined-vars.yml"
- name: Setting vlan to network devices
remote_user: Ansible
hosts: all
vars_files:
-  variables.yml  #variables file used for automating.
-  variables/predefined-vars.yml 
tasks:
- name: configure Junos ROUTER for vlan
include_tasks: ./roles/juniper/tasks/add_vlan_rt.yml
when:
- inventory_hostname in groups['junos_routers']
- groups['junos_routers'] | length == 1
- location == inventory_name

这会产生未定义的变量错误(对于在第一次播放中创建的变量)。

有没有办法做到这一点?我用它来生成router_port_name等变量 - 变量取决于位置和专用服务器,这些在 variables.yml 中定义

任何帮助真的非常感谢。

谢谢

编辑:但是,我注意到这个剧本:


---
- hosts: localhost
gather_facts: false
name: 1
vars_files:
- variables.yml
tasks:
- name: Creating predefined variables from a template
template:
src: predefined-vars.yml.j2
dest: "./variables/predefined-vars.yml"
- name: Generate hosts file
hosts: all
vars_files:
- variables.yml
- ./variables/predefined-vars.yml
tasks:
- name: test
debug: msg="{{ router_interface_name }}"

显示在第一次重播中创建的变量。

我看到的区别在于,第一个剧本读取第一部剧本开始时(生成库存和创建可变文件)时在剧本中使用的所有变量文件(甚至是第一次播放时创建的预定义的 vars.yml <,在另一个播放中使用),而第二个剧本在第一次播放中读取变量.yml,并且仅在第二次播放开始时读取预定义的 vars.yml。

任何想法如何使第一个剧本以相同的方式运行?

因此,我根据其他人的文档和建议找到了问题的解决方案。

我对这个问题的理解:

剧本会将提供的所有变量(所有播放)读取到缓存中以供以后使用,因此,如果我将我预定义的 vars.yml 包含在vars_files中,那么在第一次播放中更改它后,这些更改将不会被以后的播放使用,因为它们将使用缓存。

因此,我不得不在第二次播放中创建另一个任务,该任务将读取(加载到缓存中)我新生成的文件(用于该播放):


- name: Include predefined vars
include_vars: ./variables/predefined-vars.yml
run_once: true

希望对您有所帮助! 仍然不知道为什么第二场播放会显示变量...

最新更新