Christian Klemm
Christian Klemm

Reputation: 1505

Unable to obtain azure key vault secret in ansible

I try to get a secret from azure key vault in my ansible 4 playbook using azcollection 1.9.0.

- name: Get secret value
  azure_rm_keyvaultsecret_info:
    vault_uri: https://my-vault.vault.azure.net/
  register: kvSecret

According to the docs the result should contain a list of secrets with a property called secret containing the secret value.

However, this property is not present on the result set. This is the result I get:

{
    "changed": False,
    "secrets": [
        {
            "sid": "https: //my-vault.vault.azure.net/secrets/ssh-user-username",
            "version": "",
            "tags": {},
            "attributes": {
                "enabled": True,
                "not_before": None,
                "expires": None,
                "created": "2021-09-05T14:32:10+00:00",
                "updated": "2021-09-05T14:32:10+00:00",
                "recovery_level": "Recoverable+Purgeable"
            }
        }
    ],
    "failed": False
}

If I try to get this exact secret using the name option I get an empty result set.

My vault contains this secret, it has a value and the service principal has access to my key vault through IAM with the roles Key Vault Reader and Key Vault Secrets User.

Upvotes: 2

Views: 3236

Answers (2)

Christian Klemm
Christian Klemm

Reputation: 1505

Turns out that this was an issue with the authentication. Ansible is connecting to my remote machine via ssh and therefore I needed to set the authentication for azure. I was doing this with environment variables in my ansible playbook but it turns out that they are not set when the playbook runs it's tasks. Passing them explicitly to the command does the trick.

Upvotes: 1

Ansuman Bal
Ansuman Bal

Reputation: 11411

I tested it on my environment and my service principal is having Key vault reader and Key vault secrets user with the below yml code.

---
- hosts: localhost
  connection: local
  collections:
    - azure.azcollection

  vars:
    vault_name: Testansumankeyvault01
    secret_name: adminPassword

  tasks:

  - name: Get Key Vault by name
    azure_rm_keyvault_info:
      resource_group: test-rg
      name: "{{ vault_name }}"
    register: keyvault

  - name: Set key vault URI fact
    set_fact: keyvaulturi="{{ keyvault['keyvaults'][0]['vault_uri'] }}"

  - name: Get secret value
    azure_rm_keyvaultsecret_info:
      vault_uri: "{{ keyvaulturi }}"
      name: "{{ secret_name }}"
    register: kvSecret

  - name: set secret fact
    set_fact: secretValue="{{ kvSecret['secrets'][0]['secret'] }}"

  - name: Output key vault secret
    debug: 
      msg="{{ secretValue }}"

Reference:

Azure built-in roles - Azure RBAC | Microsoft Docs

Use Azure Key Vault to store VM secrets with Ansible | Microsoft Docs

Upvotes: 2

Related Questions