using a variable from one task in the next

I have a 2 tasks in a playbook and from task1 I have a variable collected from the register output as below.

  • name: Playbook to collect the actual hostname
    hosts: server1
    become: yes
    tasks:

  • name: collect the actual hostname
    shell: ‘hostname’
    register: short_name

  • name: collect the hostname for the next task
    set_fact:
    reg_name: “{{ short_name.stdout_lines[-1].split(‘.’)[1] }}”

  • name: Playbook to test the new hostname collections
    hosts: 127.0.0.1
    become: yes
    tasks:

  • name: print the collected hostname
    debug:
    msg: {{reg_name }}

collecting the host’s shortname using set_fact is working . However the data stored using set_fact in reg_name is not carry to the next task.

Is there an option/module available to have the variable from one task to be made available to the next?

Works for me …

% ansible --version

ansible [core 2.15.4]

% cat foo.yml

If you gather facts you can reference inventory_hostname_short vs running a shell command.

https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html#term-inventory_hostname_short

Walter

Your first play is targeting server1, while your second play is targeting a different host.

If the reg_name is available in the second task, you would need to retrieve it relative to server1:

    **msg: "{{ hostvars['server1']['reg_name'] }}"**

You should look at and contrast the values of ansible_hostname, inventory_hostname, and ansible_fqdn.

You are confusing scopes, `set_fact` is PER HOST, not a global. So you
defined the variable on server1 but are trying to read it from
127.0.0.1.

So to access in the 2nd play you need to go through hostvars:
{{hostvasr['server1']['reg_name']

yes. Exactly …
I did set_fact on a remote_host and try to re-call the value of the variable in the localhost.

So to access in the 2nd play you need to go through hostvars:
{{hostvasr[‘server1’][‘reg_name’]

Do you mean I have to use like below?

  • name: print the collected hostname
    debug:
    msg: “{{hostvars[‘server1’][‘reg_name’] }}”

Brian / Todd … good eyes!

Walter

Hi ,

I am re-opening this thread as I get a new question on above the existing one.
Sorry for that…(not lazy to open another)

Is there a way to use the output of play1 , which is a list(of variables) to be passed variable to the second play2
The playbook for illustration only .

in play2 just use `hostvars['localhost']['server_list']`