Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch Azure RM storage account keys in Ansible?

Tags:

ansible

azure

I am creating an Azure RM Storage Account with Ansible and I would like to fetch the value of the access keys for later usage in templates. These values are generated on the Azure side. I can get them, for example, with the PowerShell Get-AzureStorageKey cmdlet.

However, neither the return values of the azure_rm_storageaccount module nor the facts gathered with the azure_rm_storageaccount_facts module contain those keys.

I guess I could fetch them using a REST API call (per this answer), but I would have to create an OAuth2 token just for this task. With REST API there is likely no way to use the set of credentials defined for Ansible (i.e. environment variables AZURE_CLIENT_ID, AZURE_SECRET, AZURE_SUBSCRIPTION_ID, AZURE_TENANT).

Is there any way to fetch these keys (using the credentials already provided to Ansible)?


In fact, Ansible libraries seem to include the code for fetching these keys, but it also seems they are used only internally.


My playbook:

---
- hosts: localhost
  connection: local

  vars:
    resource_group_name: fetchtest01
    resource_group_location: southcentralus
    storage_account: fdsahf343u2s
    storage_account_type: Standard_LRS

  tasks:
    - name: Ensure resource group "{{ resource_group_name }}" exists
      azure_rm_resourcegroup:
        name: "{{ resource_group_name }}"
        location: "{{ resource_group_location }}"

    - name: Ensure storage account "{{ storage_account }}" exists in "{{ resource_group_name }}" resource group
      azure_rm_storageaccount:
        resource_group: "{{ resource_group_name }}"
        name: "{{ storage_account }}"
        account_type: "{{ storage_account_type }}"

   - name: Fetch storage account keys
     # fetch storage_account_keys

   - name: Use the storage_account_keys.primary in a template 
     template:
       # ...
like image 460
techraf Avatar asked Feb 04 '23 19:02

techraf


1 Answers

Wrap Azure Cli within a task,

  tasks:
    - name: Retrieve storage access key
      shell: az storage account keys list --account-name {{ storage_account.name }} --resource-group {{ azure.resource_group }} --query "[0].value" --output tsv
      register: storage_access_key

Now, storage_access_key will contain desired result.

like image 187
user3362908 Avatar answered Feb 12 '23 07:02

user3362908