Salima Farhat
Salima Farhat

Reputation: 11

Ansible playbook to outputs a role variable and information about your operating system

using ansible 2.8 or newer to:

I need to render a template to my Desktop that outputs a role variable and information about my operating system

I need the variable to have a default value in the role and be overridden by the playbook

Running the playbook should look something like this as outpout

localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

$ cat ~/Desktop/my-template.txt

My custom variable is test1234

My operating system in Darwin localhost 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64

Any help will be much appreciated I am still learning , Thank in advanced.

This is what I have so far

My jinja2 file is : my-template.j2

<center>
   <h1> My custom variable is {{ test_file }}</h1>
   <h3> My operating system in {{ uname_a }}</h3>
</center>
</html>


I need to render a template to my Desktop that outputs a role variable and information about my operating system

I need the variable to have a default value in the role and be overridden by the playbook

My playbook look like this:

Upvotes: 1

Views: 1680

Answers (1)

seshadri_c
seshadri_c

Reputation: 7340

To get the value of the kernel version in the template dynamically you should use the output of uname -a command instead of setting it as a variable.

Example template my-template.txt.j2:

My custom variable is {{ test_file }}
My operating system is {{ uname_a }}

Though you mentioned about a role, I don't see it being used in the playbook you have shown...

So example playbook:

- hosts: localhost
  connection: local
  vars:
    test_file: 'test1234'

  tasks:
  - name: get kernel version
    command: 'uname -a'
    register: uname_result
  - name: save to variable
    set_fact:
      uname_a: '{{ uname_result.stdout }}'
  - name: write os details to file
    template:
      src: 'my-template.txt.j2'
      dest: '/tmp/my-template.txt'

Renders the below contents in /tmp/my-template.txt (I am using a Linux box):

My custom variable is test1234
My operating system is Linux linux-2hyj 3.4.6-2.10-desktop #1

That said, you should prefer use of automatic variables provided by Ansible when possible. Possible facts you could use are:

  • ansible_os_family
  • ansible_distribution
  • ansible_kernel

Upvotes: 2

Related Questions