When hostnames have hyphens in them

Hi all,

I’ve come across an issue which might be a showstopper for me; either way I wouldn’t mind some advice.

My aim is to lookup in a vaulted file the name of a variable that is based around the hostname of the server. My servers have hyphens in the hostname.

I have got something like this:

  • name: Copy private key
    copy:
    content: “{{ ansible_hostname }}_private_key”
    dest: /root/.ssh/id_rsa

And in my vaulted vars file a variable called “server-name_private_key”.

Now since variables cannot have hyphens in them, but my server hostname does, how can I lookup the variable dynamically based on which host the task is running on?

I could always have a separate task for each host and explicitly define the variable but keeping it short is my goal.

Thanks
Richard

variables cannot have hyphens but hash/dictionary keys can

for example, this would work: private_keys['host-name'] or
private_keys[ansible_hostname]