4
votes

I have seen how to register variables within tasks in an ansible playbook and then use those variables elsewhere in the same playbook, but can you register a variable in an included playbook and then access those variables back in the original playbook?

Here is what I am trying to accomplish:

This is my main 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

I'd like to be able to access the jenkins_artifacts results back in main_playbook if possible. I know you can access it from other hosts in the same playbook like this: "{{ hostvars['localhost']['jenkins_artifacts'].stdout_lines }}"

Is it the same idea for sharing across playbooks?

2

2 Answers

3
votes

I'm confused what this question is about. Just use the variable name jenkins_artifacts:

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

- hosts: localhost
  debug:
    var: jenkins_artifacts
0
votes

This might seem complicated but I love doing this in my Playbooks:

rc defines the name of the variable which contains the return value

ar gives the arguments to the include tasks

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 }}" } 

...

I can now use the isos_present variable anywhere in the master.yml to access the returned value.