user3292394
user3292394

Reputation: 649

Ansible set_fact local and use on remote hosts

I'm trying to get a version on local and use it as a var in other remote hosts

Using the set_fact module in ansible

On local

    - name: Set code version
      shell:  wget -O - -o /dev/null wget -O - -o /dev/null https://repo1.maven.org/maven2/org/brutusin/wava/maven-metadata.xml | grep -Po '(?<=<version>)([0-9\.]+(-SNAPSHOT)?)' | sort --version-sort -r| head -n 1
      register: shell_output

    - name: set version
      set_fact:
        code_version: "{{ shell_output.stdout }}"
        debug: var=code_version
        run_once: true

On Remote

    - name: test code version
      debug:
        msg: code version is " {{ code_version }} "

Getting the following error: The task includes an option with an undefined variable. The error was: 'code_version'

If there any way of achieving this??

Upvotes: 4

Views: 9388

Answers (3)

Danielo515
Danielo515

Reputation: 7151

What about using delegate and running all the tasks on the same playbook? I use that to join kubernetes to a cluster. I delegate a shell command to the master node, then I execute the output of that command on the other hosts of the playbook. I'm pretty sure you can do the same delegating to localhost:

hosts: all
tasks:
    - name: Set code version
      shell:  wget -O - -o /dev/null wget -O - -o /dev/null https://repo1.maven.org/maven2/org/brutusin/wava/maven-metadata.xml | grep -Po '(?<=<version>)([0-9\.]+(-SNAPSHOT)?)' | sort --version-sort -r| head -n 1
      register: shell_output
      delegate_to: localhost

    - name: set version
      set_fact:
        code_version: "{{ shell_output.stdout }}"
        cacheable: yes

    - name: test code version
      debug:
        msg: code version is " {{ code_version }} "

Upvotes: 0

Alassane Ndiaye
Alassane Ndiaye

Reputation: 4777

You can access variables defined in other hosts with the hostvars variable.

For example:

- debug:
    msg: "{{ hostvars['localhost']['code_version'] }}"

Upvotes: 5

Shubham Vaishnav
Shubham Vaishnav

Reputation: 1720

You can use the below shared method to register a variable to persist between plays in Ansible – Different Target Hosts

On local

- name: Set code version
  shell:  wget -O - -o /dev/null wget -O - -o /dev/null https://repo1.maven.org/maven2/org/brutusin/wava/maven-metadata.xml | grep -Po '(?<=<version>)([0-9\.]+(-SNAPSHOT)?)' | sort --version-sort -r| head -n 1
  register: shell_output

- name: Register dummy host with variable
  add_host:
    name: "DUMMY_HOST"
    code_version: "{{ shell_output.stdout }}"

On Remote

- name: test code version
  debug:
    msg: code version is " {{ hostvars['DUMMY_HOST']['code_version'] }} "

It works.

Upvotes: 1

Related Questions