How to iterate all subscriptions came from "az account subscription list" Azure CL command?

zylker 0 Reputation points
2023-07-17T14:24:14.4833333+00:00

I have to provide role to service principal across all subscriptions. for that I have to fetch all subscriptions and provide a "Reader" access for an application to subscription.

Tried powershell as shown below, but it got failed in ARM template. so that similar workaround in Azure CLI will be helpful.

  foreach ($subscription in Get-AzSubscription)
          {
              New-AzRoleAssignment -ObjectId $principalId -RoleDefinitionName "Reader" -Scope "/subscriptions/$subscription"
          }
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,328 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,629 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,121 Reputation points
    2023-07-18T15:52:14.4333333+00:00
    Hello there,
    
    To iterate through all subscriptions obtained from the "az account subscription list" command in Azure CLI, you can use a scripting language like Bash or PowerShell. Here are examples for both:
    
    #!/bin/bash
    
    # Get the list of subscriptions in JSON format
    subscriptions=$(az account subscription list --query "[].{Name:name, ID:id}" --output json)
    
    # Iterate through each subscription
    for row in $(echo "${subscriptions}" | jq -r '.[] | @base64'); do
        subscription=$(echo "${row}" | base64 --decode)
        subscription_name=$(echo "${subscription}" | jq -r '.Name')
        subscription_id=$(echo "${subscription}" | jq -r '.ID')
    
        echo "Subscription Name: ${subscription_name}"
        echo "Subscription ID: ${subscription_id}"
        echo "---------------------"
    done
    
    I used AI provided by ChatGPT to formulate part of this response. I have verified that the information is accurate before sharing it with you.
    
    Hope this resolves your Query !!
    
    --If the reply is helpful, please Upvote and Accept it as an answer--