0

I am new to ansible and got undefined variable error when try to run below playbook. The task includes an option with an undefined variable. The error was: 'variable' is undefined

---
- name: get time date
  hosts: localhost
  tasks:
    - name: get from system
      shell: "date +%Y-%m-%d"
      register: dstamp
- name: print date
  hosts: IOS
  tasks: 
    - name: print
      debug: 
        msg: "{{dstamp.stdout[0:10]}}"

If I change the host from localhost to IOS, it works. I think it is because variable is bond with each host, since I changed the hosts, I got the error. My question is if it is possible to leave the hosts as localhost and IOS, and still can pass the variable. The scenario is like if the server(localhost) is in Europe and network device(IOS) in US, I would like to keep the date consistent with Europe time.

Thank you in advance.

chun xu
  • 393
  • 1
  • 4
  • 13

2 Answers2

1
  • Your assumption is correct, when you register a variable it is a local variable just for that host. Two options to overcome this problem - delegate_to and hostvars

Ansible passing variables between host contexts

ahil kanna
  • 11
  • 1
  • 1
0

The answer at the link gives a well explained solution (but long) to your problem : https://stackoverflow.com/a/33903682/11269264

Basically, you can write

debug: var=hostvars['localhost']['dstamp']
  msg: "{{hostvars['localhost']['dstamp'].stdout[0:10]}}"

And this should retrieve the var from your other task.

You can search for Ansible hostvars feature for further details.

vincenthavinh
  • 442
  • 4
  • 12