繁体   English   中英

如何在 Ansible 中使用 set_stats 在不同的剧本/任务中重用变量

[英]how to reuse variables across different playbook/tasks using set_stats in Ansible

我正在尝试重用testing_todelete_stat.yml中的test_stat变量。 我在文件testing_todelete_task.yml中将此变量定义为set_stats ,但在运行调试任务时收到以下错误消息

我究竟做错了什么?

Output:

FAILED! => {"msg": "The task includes an option with an undefined variable. 
 The error was: 'test_stat' is undefined\n\nThe error appears to be in ****/testing_todelete_stat.yml': line 7, column 7
PLAY RECAP *****************************************************************************************************************************************************************localhost                  : ok=5    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

testing_todelete_task.yml

- name: check google
 uri:
   url: http://www.google.com
   return_content: yes
 register: this

- set_fact:  
   this_local: "{{ this.url }}"   

- set_stats:
   data:
     test_stat: "{{ this_local }}"  

testing_todelete_stat.yml

- name: PLaybook to check set_stats
  hosts: localhost
  gather_facts: false
  tasks: 
    - name: include task
      include_tasks: testing_todelete_task.yml
    - name: content of set_stats
      debug:
        msg: "{{ test_stat }}"    

@Krishna Reddy的回答对我有用: hostvars['localhost']['this_local']

要添加有关set_stats的更多信息,您可以使用 Ansible Tower/AWX 中的工作流直接获取这些变量的值。 这些信息通过所谓的Artifacts从一个 playbook 获取到另一个 playbook。

使用工作流修改初始示例如下:

剧本1:

    - name: PLaybook to generate set_stats
      hosts: localhost
      gather_facts: true
      tasks:
        - name: check google
          uri:
            url: http://www.google.com
            return_content: yes
          register: this

        - set_fact:  
            this_local: "{{ this.url }}"   

        - set_stats:
            data:
              test_stat: "{{ this_local }}"

        - name: debug set fact
          debug:
            msg: "{{ this.url}}"

剧本2:

    - name: PLaybook to check set_stats
      hosts: localhost
      gather_facts: true
      tasks:   
        - name: content of set_stats
          debug:
            msg: "{{ test_stat }}"  

结果:

PLAY [PLaybook to check set_stats] *********************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [content of set_stats] ****************************************************
ok: [localhost] => {
    "msg": "http://www.google.com"
}
PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM