0

Context

I have an Ansible template that creates a configuration file. Most variables used by this template come from some stable source, such as variables defined in the playbook. However one variable contains a secret key which somehow needs to be generated if it does not already exist.

I want Ansible to generate the key on an as-needed basis. I do not want the key to be stored on the OS running Ansible, like is done with the password module. And naturally I want idempotence.

I currently have a working solution but I'm not happy with it, hence my question here. My current solution uses an extra file which is include by the configuration file created by my template. This is possible as it is a PHP file. I have a task using the shell module that generates the secret when this extra file does not exist, and then another that then creates it using the registered variable.

- name: Generate secret key
  shell: openssl rand -hex 32
  register: secret_key_command
  when: not SecretKey.stat.exists

- name: Create SecretKey.php
  template:
    src: "SecretKey.php.j2"
    dest: "{{ some_dir }}/SecretKey.php"
  when: not SecretKey.stat.exists

Surely there is a less contrived way to do this?

Question

Is there a nice way to have a variable that gets generated only once in an Ansible template?

Jeroen De Dauw
  • 10,321
  • 15
  • 56
  • 79
  • 1
    You could try to store this in the [ansible local facts](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#local-facts-facts-d) on the server. But I'm not really sure it will meet your security requirements... – Zeitounator May 11 '20 at 07:18

1 Answers1

0

I am not sure, but I understood correctly, we want to generate your template if it doesn't already exists. So you can just do as follow:

- name: Create SecretKey.php
  template:
    src: "SecretKey.php.j2"
    dest: "{{ some_dir }}/SecretKey.php"
    force: no

force: no tells to don't overwrite a file if it already exists. No need to do extra check.

CiroRa
  • 492
  • 3
  • 13