How to configure Ansible with least-privilege Azure credentials for secure automation
0 reputation · 22 Dec 2023, 02:24 UTC
0 reputation · 22 Dec 2023, 02:24 UTC
Could you explain how to create a service principal with only the permissions needed for specific Azure resources, where to store its credentials safely (e.g., environment variables, Azure Key Vault, or restricted file permissions), how to configure Ansible to avoid logging secrets, and how to enforce least privilege on the control node itself? Please include considerations for using ansible.cfg to disable logging of variable values, setting file permissions on credential files, and limiting the Azure role assignments to the minimum required.
26525 reputation · 22 Dec 2023, 05:55 UTC
az ad sp create-for-app --name "Ansible-Automation" --show-service-authaz role assignment create --role "Virtual Machine Contributor" --spn --scope /subscriptions//resourcegroups/AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID on the control node. Ansible Azure modules automatically pick these up.chmod 600 ~/.azure/servicecredentials.json chown ansible:ansible ~/.azure/servicecredentials.json
azure.azcollection.keyvault collection to fetch secrets at runtime, keeping them off the disk.ansible.cfg file.
[defaults] tansible_logging = False ansible_stdout_callback = minimal
Note: While ansible_logging = False stops local log files, use the no_log: true attribute on specific tasks that handle secrets to prevent them from appearing in the console output.
- name: Deploy VM azure.azcollection.azure_rm_vm: no_log: true
sudo privileges.Are you running these tasks from a persistent VM or within an ephemeral CI/CD runner like GitHub Actions or GitLab Runner?
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 22 Dec 2023, 14:24 UTC
One option worth adding to the credential-storage discussion: if your Ansible control node is itself an Azure VM (or runs in Azure-hosted CI), skip the service principal secret entirely and use a managed identity. The azure.azcollection modules authenticate through the Azure SDK for Python, so MSI auth works without any stored secret to rotate, expire, or accidentally commit.
Two practical gotchas to verify:
Microsoft.Authorization/roleAssignments when attaching identities). Run the full playbook with --check first, then deliberately attempt an out-of-scope action and confirm it fails with AuthorizationFailed.Also note that ansible.cfg logging settings don't protect against -vvv output in shared CI logs — keep no_log: true on secret-handling tasks regardless.