AZ CLI : Bash script to fetch all azure resources containing pattern or name

Veeresh Kumar
3 min readNov 20, 2021

I needed to get the list of all azure resources containing the pattern or name frequently. Hence, thought of automating it via AZ CLI.

The script basically takes the pattern names as input and searches for resources containing pattern and creates the pattern.log file for each patterns and failed_patterns.log for failed one’s.

The pattern.log contains:

  • ResourceName
  • ResourceType
  • ResourceId

Usage:

get_resources_contains_pattern.sh -n <patterns> -s <true/false> -u <spnid/username> -p <secret/password> -i<subscription_id> -t <tenant_id>

Pre-Requisites:

  • Az CLI Version ≥ 2.18
  • Service Principal Name(SPN) and Secret or Username and Password to login to Azure
  • SPN/Username should have Administrator or Owner or Custom privileges to read resources on the subscription
  • Azure Subscription Id
  • Azure Tenant Id

Follow below steps to execute the script and see the results:

  • Copy & Paste the below code to file and save it as get_resources_contains_pattern.sh
  • Now make the created file executable by running the below command:
make script executable
  • Now go to created file path and execute the file by passing the below arguments.

get_resources_contains_pattern.sh -n ‘chef,vnet’ -s true -u spnid -p secret -i ‘subscriptionId’ -t ‘tenant_id’

Note: Here am using SPN login, hence passed -s argument as true. If you are using false, kindly pass Username and Password.

script execution with arguments
  • Once the script execution is successful, you will see the each pattern log files created and verify the content.
Command output

Pattern log file list:

pattern log files

Pattern: chef log file.

Pattern :Vnet log file

Failed pattern Log file content:

failed_pattern log file
  • If any of the arguments are missing the below usage message will be displayed:

Here if you notice there are no arguments passed to script and Usage is displayed.

Hope it helps…!! Happy Scripting …!!

--

--

Veeresh Kumar

He is a Sr. DevOps Engineer loves to automate cloud infrastructure and App deployments. #Terraform #Azure #Jenkins #Ansible #Chef #Bash #PowerShell #AWS #GCP