Search code examples
ansiblehashicorp-vault

Ansible playbooks - Adding a secret with Boolean value to HashiCorp vault


I am using the Ansible playbook to add a secret to the HashiCorp vault, if the secret does not exist. the problem is, that is adding {"active": "false"}, instead of {"active": false}

Code:

- name: Check if secret already exists in Vault
  shell: "vault kv get secret/proxy_servers"
  environment:
    VAULT_TOKEN: "{{ vault_token.stdout }}"
  register: secret_output
  ignore_errors: true

- name: Add proxy details secret to vault if it does not exist
  shell: "vault kv put secret/proxy_servers active=false"
  environment:
    VAULT_TOKEN: "{{ vault_token.stdout }}"
  when: secret_output.rc != 0

Solution

  • When you're using the key=value syntax on the vault kv write command line, there's no way for the CLI to know that you mean the boolean value false instead of the string value false. You can only specify string values using this syntax. If you want to write other values, feed vault kv put a JSON document on stdin like this:

    vault kv put secret/proxy_servers - <<EOF
    {"active": false}
    EOF
    

    In your playbook, this might look like:

    - hosts: localhost
      gather_facts: false
      tasks:
        - name: Check if secret already exists in Vault
          command: "vault kv get secret/proxy_servers"
          register: secret_output
          ignore_errors: true
    
        - name: Add proxy details secret to vault if it does not exist
          command: "vault kv put secret/proxy_servers -"
          args:
            stdin: |
              {"active": false}
          when: secret_output.rc != 0
    
    

    Or you could use the vault_read and vault_write modules from the community.hashi_vault collection:

    - hosts: localhost
      gather_facts: false
      collections:
        - community.hashi_vault
      tasks:
        - name: Check if secret already exists in Vault
          vault_read:
            path: secret/data/proxy_servers
          register: proxy_servers
          ignore_errors: true
    
        - name: Add proxy details secret to vault if it does not exist
          when: proxy_servers is failed
          vault_write:
            path: secret/data/proxy_servers
            data:
              data:
                active: false