Roberto
Roberto

Reputation: 178

Ansible: How can I access a variable of other host?

How can I access a variable of other host? I'd like to access the slack_token varaiable of my localhost on the working_host.

- hosts: localhost
  vars:
    slack_token: 123123123
  tasks:
    - block:
      - name: test
        debug: msg="{{ slack_token }}"

- hosts: "{{ working_host }}"
  vars:
    slack_token: "{{ hostvars['localhost']['slack_token'] }}"                                                                                    
  tasks:
    - block:
      - name: test2
        debug: msg={{ slack_token }}

The error message:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: {{ hostvars['localhost']['slack_token'] }}: 'dict object' has no attribute 'slack_token'

Any idea?

Upvotes: 1

Views: 2550

Answers (2)

Kevin C
Kevin C

Reputation: 5740

Just answered a somewhat same question in my previous post.

Here's what I used:

 set_fact:
    myVar: "{{ hostvars[groups['all'][0]]['slack_token'] | default(False) }}"

But you're using two plays in a playbook. You can also try to copy a file to a machine stating the fact.

Upvotes: 2

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

To access slack_token from everywhere, either:

  • pass it as extra variable with -e slack_token=zzzz
  • define it in your inventory under all group

Upvotes: 1

Related Questions