简体   繁体   中英

How can I access register variable in one role in another different play role in ansible

- name: mytask1
   hosts: "{{app_name | upper}}_{{ env | upper }}_myhost1"
   vars_files:
    - "envs/{{ env|lower }}/{{app_name|lower}}_{{env|lower}}_hc.yml"
   serial: 1
   gather_facts: False
   roles:
   - role: my-task1

this is my 1st play

in my-task1/tasks/main.yaml

 - name: mytask1 in role
    shell: sometask
    with_items: "{{ path.stdout_lines }}"
    register: task_status

in the same playBook i have another 2 play

Below is the 3rd play in the playbook

 - name: mytask2
   hosts: "{{app_name | upper}}_{{ env | upper }}_myhost1"
   remote_user: "{{ tom_user }}"
   vars_files:
    - "envs/{{ env|lower }}/{{app_name|lower}}_{{env|lower}}_hc.yml"
   serial: 1
   gather_facts: False
   roles:
   - role: my-task2

I want to use the task_status variable in my my-task2 like

my-task2/tasks/main.yaml

  - name: do some activity
    command: "sh {{ item.stdout }}/task.sh"
    with_items: "{{ task_status .results }}"
    when: item.stdout != ""

I m getting below error now when im trying to use this as mentioned

fatal: [hostname]: FAILED: => { "msg": "'dict object' has no attribute 'results'" }

can i use the registred variable task_status in my second play?

thanks in advance

Q: " Can I use the registred variable task_status in my second play? "

A: Yes. You can if you use this variable for this purpose only. For example

- hosts: localhost
  tasks:
    - command: "echo {{ item }}"
      loop: [1, 2, 3]
      register: task_status

- hosts: localhost
  tasks:
    - debug:
        msg: "{{ task_status.results|json_query('[].stdout') }}"

gives

ok: [localhost] =>
  msg:
  - '1'
  - '2'
  - '3'

Such variables live in the hostvars . You can use variables from other hosts too, for example

- hosts: host_A
  tasks:
    - command: "echo {{ item }}"
      loop: [1, 2, 3]
      register: task_status

- hosts: host_B
  tasks:
    - debug:
        msg: "{{ hostvars.host_A.task_status.results|json_query('[].stdout') }}"

gives

ok: [host_B] => 
  msg:
  - '1'
  - '2'
  - '3'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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