Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Ansible authenticate to Microsoft Azure using credential profiles Part 1

My earlier article Quickstart How to authenticate Ansible with Microsoft Azure was for basic and foundation for authentication to azure using Ansible. But I have scenarios with multiple subscriptions to automate multiple azure clouds using Ansible, in that case I will make use of multiple credentials profiles for those subscriptions.

The file ~/.azure/credentials will contain all the subscriptions service principal. First I will gather information of subscription id, tenant id and client (app registrations) (service principal) ids using below Azure CLI commands from subscriptions. (For client secret at the moment there is no command which will show the secret value, when you create a new secret for first time, you will have to note it down and keep it safe for later use or simply create new secret whenever it is requirement, you can check my step by step article Create an Azure App registrations in Azure Active Directory using PowerShell & AzureCLI for the same). 

$ az account show
{
  "environmentName": "AzureCloud",
  "homeTenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "id": "9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "isDefault": true,
  "managedByTenants": [],
  "name": "Sponsership-by-Microsoft",
  "state": "Enabled",
  "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "user": {
    "name": "[email protected]",
    "type": "user"
  }
}

$ az ad app list --display-name Logginapp
[
  {
    "addIns": [],
    "api": {
      "acceptMappedClaims": null,
      "knownClientApplications": [],
      "oauth2PermissionScopes": [],
      "preAuthorizedApplications": [],
      "requestedAccessTokenVersion": null
    },
    "appId": "61e492e8-cbc2-48e4-880a-ec39187567a5",
    "appRoles": [],
    "applicationTemplateId": null,
    "certification": null,
    "createdDateTime": "2021-04-11T08:58:08Z",
    "defaultRedirectUri": null,
    "deletedDateTime": null,
    "description": null,
    "disabledByMicrosoftStatus": null,
    "displayName": "LogginApp",
    "groupMembershipClaims": null,
    "id": "009d685e-3d1c-48d4-8175-dbe319c2684e",

My folder ~/.azure/credentials files content looks like below in the screenshot (It is An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties). I have 3 environments. Unless I mention profiles inside ansible yaml code or while deploying ansible script, It will always by default authenticate with credentials mentioned under default profile.

Check this out: 
Ansible authenticate to Microsoft Azure using credential profiles Part 2
Ansible authenticate to Microsoft Azure using credential inside yaml file

Microsoft Azure ubuntu ansible redhat .azure credentials authentication prod dev default subscription client secret tenant AZURE_PROFILE resource group azure collection password ad service principal app registrations.png

Here is my Ansible yaml code and I haven't mentioned any profile inside the yaml script. Credentials are taken from  ~/.azure/credentials automatically.

#Ansible variable yaml file - rginfo_var.yml
---
name: vcloud-lab.com
tags:
  - orgnization:vcloud-lab.com
  - owner

#Ansible Task yaml file - rginfo.yaml
---
- name: Get Azure resource group information
  hosts: localhost
  connection: local
  gather_facts: false

  collections:
    - azure.azcollection

  tasks:
  - name: Include variable file
    ansible.builtin.include_vars:
      file: rginfo_var.yml
      name: rginfo

  - name: Get Azure resource group information
    azure_rm_resourcegroup_info:
      name: "{{ rginfo.name }}"
      tags: "{{ rginfo.tags }}"
      #list_resources: yes
    register: resource_groups

  - name: Show/Print resource group information
    debug:
      var: resource_groups

To use the dev profile while running the ansible playbook I will use automatic variable AZURE_PROFILE=dev in front of ansible-playbook rginfo.yaml command to use dev credentials as highlighted in the script below.

Download this ansible azure profile script here or it is also available on github.com/janviudapi.

ubuntu@ansible:~/.azure$ cd /home/ubuntu/Documents/Azure_Ansible/rginfo
ubuntu@ansible:~/Documents/Azure_Ansible/rginfo$ ls
rginfo_var.yml  rginfo.yaml
ubuntu@ansible:~/Documents/Azure_Ansible/rginfo$ AZURE_PROFILE=dev ansible-playbook rginfo.yaml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [Get Azure resource group information] ************************************************************************************************************************

TASK [Include variable file] ***************************************************************************************************************************************
ok: [localhost]

TASK [Get Azure resource group information] ************************************************************************************************************************
ok: [localhost]

TASK [Show/Print resource group information] ***********************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "changed": false,
        "failed": false,
        "resourcegroups": [
            {
                "id": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vCloud-lab.com",
                "location": "eastus",
                "name": "vCloud-lab.com",
                "properties": {
                    "provisioningState": "Succeeded"
                },
                "tags": {
                    "orgnization": "vcloud-lab.com",
                    "owner": "vjanvi"
                }
            }
        ]
    }
}

PLAY RECAP *********************************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

ubuntu@ansible:~/Documents/Azure_Ansible/rginfo$

These are the results after using and running script under dev environment credentials.

Microsoft Azure resource group redhat ansible ansible-playbook AZURE_PROFILE tags location variable recap print azure_rm_resourcegroup_info azure_collections module plugin subscription credentials authentication.png

If you don't want to type variable every time you can add environment variable using command command export AZURE_PROFILE=dev. Additionally you can also add entries in /etc/environment or ~/.bashrc file. 

TIP: To view existing environment variable run command env or printenv. To remove environment variable run command unset AZURE_PROFILE.

Useful Articles
Deploy create Virtual Network vNET in Azure cloud using Ansible
Create an Azure App registrations in Azure Active Directory using PowerShell & AzureCLI
Deploy create Virtual Network vNET in Azure cloud using Ansible
How to install and configure Ansible on Ubuntu
Get Started: Configure Ansible for Azure Cloud Infrastructure
Install the Microsoft Azure CLI on Ubuntu Linux

Go Back

Comment

Blog Search

Page Views

12056460

Follow me on Blogarama