【问题标题】:Return Variable from Included Ansible Playbook从包含的 Ansible Playbook 返回变量
【发布时间】:2017-10-07 17:53:22
【问题描述】:

我已经看到如何在 ansible playbook 中的任务中注册变量,然后在同一 playbook 的其他地方使用这些变量,但是您可以在包含的 playbook 中注册一个变量,然后在原始 playbook 中访问这些变量吗?

这是我想要完成的:

这是我的主要剧本:

- include: sub-playbook.yml job_url="http://some-jenkins-job"

- hosts: localhost
  roles:
  - some_role

sub-playbook.yml:

---
- hosts: localhost
  tasks:
  - name: Collect info from Jenkins Job
    script: whatever.py --url "{{ job_url }}"
    register: jenkins_artifacts

如果可能,我希望能够在 main_playbook 中访问 jenkins_artifacts 结果。我知道您可以像这样从同一剧本中的其他主机访问它:"{{ hostvars['localhost']['jenkins_artifacts'].stdout_lines }}"

跨剧本共享的想法是否相同?

【问题讨论】:

    标签: ansible


    【解决方案1】:

    我很困惑这个问题是关于什么的。只需使用变量名jenkins_artifacts

    - include: sub-playbook.yml job_url="http://some-jenkins-job"
    
    - hosts: localhost
      debug:
        var: jenkins_artifacts
    

    【讨论】:

      【解决方案2】:

      这可能看起来很复杂,但我喜欢在我的剧本中这样做:

      rc定义了包含返回值的变量的名称

      ar 为包含任务提供参数

      master.yml:

      - name: verify_os
        include_tasks: "verify_os/main.yml"
        vars:
          verify_os: 
            rc: "isos_present"
            ar:
              image: "{{ os.ar.to_os }}"
      

      verify_os/main.yml:

      ---
      - name: check image on device
        ios_command:
          commands:
            - "sh bootflash: | inc {{ verify_os.ar.image }}"
        register: image_check
      
      - name: check if available
        shell: "printf '{{ image_check.stdout_lines[0][0] }}\n' | grep {{ verify_os.ar.image }} | wc -l"
        register: image_available
        delegate_to: localhost
      
      - set_fact: { "{{ verify_os.rc }}": "{{ true if image_available.stdout == '1' else false }}" } 
      

      ...

      我现在可以在 master.yml 中的任何位置使用 isos_present 变量来访问返回值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-11
        • 1970-01-01
        • 1970-01-01
        • 2020-04-22
        • 1970-01-01
        相关资源
        最近更新 更多