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

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.

Leave a Comment