Search code examples
ansibleyamljinja2hashicorp-vault

sending data to hashicorp vault dynamically using ansible


I want to write/store data in Hasicorp vault using Ansible. I have the working code for that. But the problem is I have to store creds in the Hasicorp vault in a dynamic way. Depending on the service sometimes we have to store 1 secret, sometimes 2 secrets, or sometimes 3 using the same ansible script.

Eg: For Cassandra 3 secrets: keyspace password username

For RdsPostgreSql for 2 secrets: host port

For SSHConfig 1 secrets: ssh-key

My ansible code:

- name: Get secrets from Vault
  hosts: localhost
  tasks:
  - name: Write a value to the cubbyhole via the remote host with userpass auth
    community.hashi_vault.vault_kv2_write:
      url: http://127.0.0.1:8200
      path: "{{ path_to_secret }}"
      data:
        "{{ secret_key_1 }}": "{{ secret_val_1 }}"
        "{{ secret_key_2 }}":  "{{ secret_val_2 }}"
      auth_method: token
      token:  "{{ auth_token }}"
    register: result

  - name: Echo the secret_data
    ansible.builtin.debug:
      msg: "{{ result }}"

So in this code how do I make the key/value pairs that I am sending under data dynamic? Like sending one or more dictionary depending on service. I have to send the key/value pairs at run time using --extra-vars


Solution

  • Why don't you send the full dict directly as a var?

      - name: Write a value to the cubbyhole via the remote host with userpass auth
        community.hashi_vault.vault_kv2_write:
          url: http://127.0.0.1:8200
          path: "{{ path_to_secret }}"
          data: "{{ my_data_dict }}"
          auth_method: token
          token:  "{{ auth_token }}"
        register: result
    

    You can then call this with an extra var from the command line:

    ansible-playbook -e '{"my_data_dict": {"key1": "value1", "key2": "value2"}}' \
      my_playbook.yml
    

    To ease your life a bit (since writing json inline like above is somewhat error prone), you can set the given dictionary in a separate yaml file, e.g. my_data_dict.yml

    ---
    my_data_dict:
      toto: earth
      pipo: wind
      bingo: fire
    

    and send the vars declared in that file as extra vars from the command line:

    ansible-playbook -e @my_data_dict.yml my_playbook.yml