Is it possible to use $HOSTNAME variable in "path:/"

I’m writing a playbook and have never tried to do this particular thing I’m doing.

I have 500 host computers - all RHEL8
Using ansible version: ansible [core 2.16.3]
From a server, I’m configuring a playbook to reach out to all 500 computers and…

  1. Determine if a $HOSTNAME.key file exists
  2. if It doesn’t, it will scp the file from the server (which is a Cert Authority server)

Ultimately the goal is to check for the existence of a $HOSTNAME.key and .crt file, and if they don’t exist, create them, and copy them to the remote host. For reasons of revocation, we definitely don’t want a playbook to create certs every time, when they definitely do exist.

I tried this with just a plain file and it worked fine. I created “file1” in /tmp on the CA. I ran the playbook, it didn’t find file1 on my one host (only testing with 1 host for now), so it copied the file over to /tmp on the host.

Then I changed the playbook to the actual file I want to check for. The path statement is written like this:
tasks:

  • name: Check for $HOSTNAME.key
    stat:
    path: /tmp/$HOSTNAME.key
    register: key

  • name: Report if file exists
    debug:
    msg: “the file exists”
    when: key.stat.exists == True

The problem is that the file does exist, but it keeps reporting that it’s skipping the debug/msg portion, finding it to be False. Yet the file is in /tmp on the host and I’ve even used chmod 777 in case of a permissions issue.

I can’t see what I’m doing wrong. Any ideas anyone? Thanks!

Ansible is treating $HOSTNAME as literal $HOSTNAME, so it is probably unlikely to find a file named literally $HOSTNAME.key in /tmp. Ansible does not reference variables in this way; you’ll want to use ansible facts, in this case

{{ ansible_hostname }}

So your playbook would resemble the following:

- name: 'Playbook to detect hostname.key files'
  hosts: 'localhost'
  gather_facts: true
  tasks:
    - name: "Check for {{ ansible_hostname }}.key"
      ansible.builtin.stat:
        path: "/tmp/{{ ansible_hostname }}.key"
      register: key

    - name: "Report if file exists"
      ansible.builtin.debug:
        msg: “the file exists”
      when: key.stat.exists == True

It’s also good practice to fully qualify your module names, like ansible.builtin.debug as opposed to just debug.

2 Likes

Thank you. I just stumbled onto ansible facts and this seems to also work in the “/path” statement

path: /tmp/ {{ ansible_facts[‘hostname’] }}.domain-name.key

But what you wrote above looks more elegant I think.