0

I have static hosts, in my all.yml group_vars, I have some variables that I want to generate from an REST API's response. I can use uri module in task and register the variables for the play, but I think it calls the api for every host.

But I want to create the variables by calling the api only once at the start of the play, so it can be used by all hosts. How can I do that?

Riddhesh
  • 571
  • 5
  • 18
  • Seems [run_once](https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html#run-once) should help in this one by creating facts at the start of the play, but let me know if there is any other solution. – Riddhesh Sep 02 '19 at 12:56
  • What is wrong with *run_once*? What is the use-case where you need another solution? – Vladimir Botka Sep 02 '19 at 13:37
  • No problem with that :) I'm new to ansible so just wasn't sure this is the best available solution. Thanks for the help! – Riddhesh Sep 03 '19 at 05:27

1 Answers1

3

Q: I want to create the variables by calling the api only once at the start of the play, so it can be used by all hosts. How can I do that?

A: A variable registered in a task with run_once: true is available to all hosts. The playbook below

- hosts: all
  tasks:
    - command: date
      register: result
      run_once: true
    - set_fact:
        started_at: "{{ result.stdout }}"
    - debug:
        var: started_at

gives

TASK [command] **************
changed: [test_01]

TASK [set_fact] ***************
ok: [test_01]
ok: [test_02]
ok: [test_03]

TASK [debug] ************
ok: [test_01] => {
    "started_at": "Mon Sep  2 15:23:08 CEST 2019"
}
ok: [test_02] => {
    "started_at": "Mon Sep  2 15:23:08 CEST 2019"
}
ok: [test_03] => {
    "started_at": "Mon Sep  2 15:23:08 CEST 2019"
}
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63