MortenSickel
MortenSickel

Reputation: 2200

How do I set a variable from an external command in ansible

As a part of an ansible playbook, I am writing a logfile on the machines that have been manipulated by the script. Since the ansible files is in a git repository, it is relevant to know which version was checked out during the run. At the moment I add on the command line

--extra-vars "git_version=$(git rev-parse --short HEAD)" 

this gives me the information I want to use, but it also means this has to be manually added on any run of the playbook. I tried using the shell: command as a task,

- name: Read git commit  
  shell: /usr/bin/git rev-parse --short HEAD
  register: git_version

but that of course failed spectaculary as it was executed on the clients, not the server. So, how can I run the git command (or any other command) on the server to store the informatioion in an ansible variable?

Upvotes: 1

Views: 69

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

delegate_to: localhost and run_once: true is what you're looking for. For example,

- hosts: all
  tasks:
    - command: git rev-parse --short HEAD
      register: git_version
      delegate_to: localhost
      run_once: true
    - debug:
        var: git_version.stdout
      run_once: true

See:

Note: " ... with run_once, the results are applied to all the hosts." As a result, the variable git_version registered in the first task will be available to all hosts in the play.

Upvotes: 2

Related Questions