Commandline tricks: Switching between Azure Subscriptions

One of the subjects I wanted to touch on this blog is my journey in my new job. And with my new job a new cloud adventure started. In my previous job I was primarily focussed on IBM Cloud, AWS and a bit of Google Cloud. Although all clouds are in some way the same, there are also a lot of difficulties, hick-ups and new ideas marching around the corner.

Switching subscriptions

Because of our work for different clients, my first bash script I wrote was a script to switch subscriptions, saz or switch_azure_subscription:

#!/usr/bin/env bash

unset options i
while IFS= read -r -d $'\n' f; do
  options[i++]="$f"
done < <(az account list -o tsv | cut -f 4,2 )
tLen=${#options[@]}
select opt in "${options[@]}" "Stop the script"; do
  if [ "$REPLY" -le "$tLen" ]; 
  then
    subscriptionid=`echo $opt | cut -f 1 -d " "`
    echo -e "--> Set Subscription: az account set -s ${subscriptionid}\n"
    az account set -s $subscriptionid
    
    echo "--> Subscription is:"
    az account show -o table
    break
  elif [ "$REPLY" -eq "$(($tLen+1))" ];
  then
    echo "--> Stopped the script"
    break
  else
    echo "Ho ho ho. Something went wrong. ${REPLY} is no good a selector"
    break
  fi
done

For the people who are like me (lazy and not born from the bash shell): add this to your ~/.bashrc or ~/.zshrc after cloning my azure scripts repo:

alias saz='~/$GIT_REPO_CLONED_HERE/azure-scripts/switch_azure_subscription.sh'

To be honest, I use this every day a few times a day. In the future it will probably change a bit due to the level of automation I’m planning to bring into the organisation, but for now it works like a charm.

comments powered by Disqus