1

I'm trying to use Ansible to automate a variable in a configuration file. I have a template config file that contains this line "config_version={{osVersion}}" This playbook gets ran against RHEL 7 and 8 machines, ideally, I'd like ansible to get the version and major release of the hosts it is running the playbook on then populate that {{osVersion}} with each machine version.

I've tried finding about this specific use case and nothing seems to be coming up for me. On how to accomplish this.

to summarize the template contains this "config_version={{osVersion}}" I'd like to have that template be on the machine, check the machine for its version, then write the version to the config file for one or many hosts.

1 Answers1

1

You have to connect to a remote host to learn about the OS. To connect a remote host a play must read the inventory first. When you take a look at the variable precedence you'll see that ansible_distribution_version (and other host facts) might be available from precedence 12. play vars upwards. By default, the fact-gathering is enabled (implicit). See DEFAULT_GATHERING

  • For example, the play
shell> cat pb.yml
- hosts: test_24
  vars:
    test: "{{ ansible_distribution_version }}"
  tasks:
    - debug:
        var: test

gives (abridged)

shell> ANSIBLE_GATHERING=implicit ansible-playbook pb.yml

  test: '8.4'

Then, you can write the file

    - copy:
        dest: /tmp/test.conf
        content: |
          config_version={{ ansible_distribution_version }}

gives

shell> ssh admin@test_24 cat /tmp/test.conf
config_version=8.4
  • The variable ansible_distribution_version won't be defined if you don't gather facts
shell> ANSIBLE_GATHERING=explicit ansible-playbook pb.yml

  test: VARIABLE IS NOT DEFINED!

You can gather or update the facts anytime in a play by using the module setup.

See:

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63