包括在剧本的第一个剧本中生成的变量

时间:2019-07-17 15:15:05

标签: automation ansible

我有一部剧本,其中包含两个剧本: 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 <-,在另一个剧本上使用的其他文件)(生成库存和创建变量文件),而第二部剧本在第一部剧本中读取variables.yml,并且仅在第二部剧本开始时读取预定义的vars.yml。

Any Ideas如何使第一个剧本的行为方式相同?

1 个答案:

答案 0 :(得分:0)

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

我对该问题的了解:

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

因此,我必须在第二局中创建另一个任务,该任务将读取(为该局)我新生成的文件(加载到缓存中):


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

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