How do I print the current hostname of a host in ansible

I wrote a role to edit the motd when user log into the machine, but I want to personalize the motd to print the hostname of the machine

What variable do I use? or how do I do this? template? how? I used the copy module for the motd file

So for example I want to be able to say "welcome to $hostname" so how do I parse this hostname using ansible?


Solution 1:

You have to use the template-module for this.

Here's an example task:

- name: Create motd
  template:
    src: "motd.j2"
    dest: "/etc/motd"

The file motd.j2 (placed in the templates-subdirectory of your role) could then look like this:

Welcome to host {{ansible_hostname}}!

{{ansible_hostname}} will then be replaced with the hostname.

Be sure to "gather facts" in your role, or else the variable will be empty.