Azure CLI & Cloud Shell

Azure CLI & Cloud Shell

How to control Azure with typed instructions instead of endless clicking, and how to do it from any browser without installing a thing. What each tool is, how it works inside, how to keep it safe, and when to use which.

Imagine you run a small online shop and you need to create ten identical servers, each with the same settings. You could open a website, click through a dozen screens, fill in the same boxes ten times, and hope you never make a typo. Or you could write one short instruction, tell the computer to repeat it, and go make a cup of tea. That second path is what a command-line tool gives you.

Microsoft Azure, one of the world’s largest cloud platforms, offers exactly this through two closely related tools. The Azure CLI is a program that lets you manage Azure by typing commands. Azure Cloud Shell is a ready-made terminal that opens inside your web browser, with the Azure CLI already installed and already signed in. One is the tool; the other is a place where the tool is waiting for you.

In this guide you will learn what each one is, how a single typed command travels from your keyboard to a server in a data center, how sign-in and permissions work, how to keep your account safe, and how real teams use these tools every day. No earlier experience is needed. Every new word is explained when it first appears.

1The Big Picture: Managing Azure Without Endless Clicking

Before we meet the tools, we need to see the problem they solve and the family of ways Azure can be controlled.

What is Azure, and what does “managing” it mean?

Microsoft Azure is a cloud platform, which means Microsoft owns huge data centers around the world and rents out pieces of them: virtual computers, storage space, databases, networks, and hundreds of other services. Launched publicly in 2010, it is today one of the big three cloud providers alongside Amazon Web Services and Google Cloud.

Renting is only the first step. Someone must then manage what they rented: create a server, resize it, give it a network address, back it up, switch it off at night, and delete it when the project ends. Every one of those actions is a request that you send to Azure.

Four ways to send a request

Azure accepts your requests in several ways. They all end up in the same place, but they feel very different to use.

  • The Azure portal. A website with menus, buttons, and forms. It is friendly and visual, great for exploring and learning.
  • The command line. You type short text instructions and press Enter. The Azure CLI is the best-known tool of this kind.
  • Code libraries. Developers can call Azure from inside a program written in Python, Java, JavaScript, or other languages.
  • Template files. You describe the whole setup you want in a file, and Azure builds it for you. Bicep, Microsoft’s template language, and Terraform are common examples.
Analogy

Think of ordering food. The portal is like walking into a restaurant, reading the menu, and pointing at what you want. The command line is like phoning in a precise order that you can repeat word for word every day. A template file is like handing over a full catering plan for a wedding. All three get you fed; they differ in speed, repeatability, and effort.

Where the CLI and Cloud Shell fit

The Azure CLI took shape as a modern, cross-platform tool around 2017, replacing an older one that was built on a different technology. Cloud Shell arrived about the same time, first with a Bash terminal and later with PowerShell, so that you could use the command line even from a computer where nothing was installed. Together they became the everyday toolkit for people who run Azure.

2
shell styles in Cloud Shell: Bash and PowerShell
1
command name to remember for the CLI: az
0
programs to install when you use Cloud Shell
i
Memory trick

The CLI is the tool. Cloud Shell is a room that already contains the tool. You can also carry the tool to your own laptop and use it there. Same tool, different place.

2Azure Basics You Need First

Every command you will ever type refers to a few core Azure ideas. Learn them once, and everything else becomes easier to read.

The building blocks

Top level

Tenant

Your organization’s private identity space in Microsoft Entra ID, which is where people, groups, and apps are registered. Think of it as the company itself.

Billing

Subscription

A container that holds your resources and receives the bill. A company may have many, such as one for testing and one for production.

Grouping

Resource group

A folder for related resources that share a life. Delete the folder, and everything inside goes with it.

The things

Resource

One actual item: a virtual machine, a storage account, a database, a network. Every resource lives in exactly one resource group.

Place

Region

The geographic location where a resource runs, such as Central India or West Europe. It affects speed, price, and legal rules.

Permissions

Role

A bundle of allowed actions, such as Reader, Contributor, or Owner, given to a person or program at a certain level.

Analogy

Picture a large office park. The tenant is the company that owns the park. Each subscription is a building with its own electricity meter. A resource group is a floor dedicated to one project, and each resource is a desk, a printer, or a meeting room on that floor. The region is the city where the park stands, and a role is the type of key card you carry.

The front door: Azure Resource Manager

Whichever way you send a request, it reaches a service called Azure Resource Manager, usually shortened to ARM. ARM is the front desk of Azure. It checks who you are, checks whether your role allows the action, and then passes the job to the right service behind the scenes, such as the one that creates virtual machines.

This is very good news for learners. Because the portal, the CLI, Cloud Shell, and the code libraries all talk to the same front desk, they behave consistently. Something you create with the CLI shows up in the portal a moment later, and something you change in the portal can be seen from the CLI.

i
Good to know

A REST API is a standard way for programs to ask a web service to do things. ARM exposes one. The Azure CLI is basically a friendly translator that turns your short commands into REST requests and shows you the answers in a readable form.

3The Azure CLI: Your Remote Control for Azure

The Azure CLI is a single program that understands hundreds of Azure instructions, and it works the same way on Windows, macOS, and Linux.

What it is

CLI stands for command-line interface. It is a way of talking to a computer by typing short lines of text rather than clicking. The Azure CLI is Microsoft’s official command-line tool for Azure. You start every instruction with the two letters az, then say what you want. It is open source, which means anyone can read its code and suggest improvements, and Microsoft publishes regular new versions.

It exists for three reasons. First, speed: an expert can do in one line what takes ten clicks. Second, repeatability: a typed instruction can be saved in a file and run again exactly the same way tomorrow. Third, automation: programs and pipelines cannot click buttons, but they can run commands.

Analogy

The CLI is like a TV remote control with every button labeled by words. Instead of walking to the TV and turning knobs, you press a button from your chair. Better still, you can write down a sequence of presses, such as “turn on, set volume, choose channel,” and replay it any time.

How a command is shaped

Azure CLI instructions follow a simple sentence pattern: a program name, a group that names the kind of thing, an action that says what to do with it, and some options that give the details. In plain words, it reads like “azure, virtual machine, create, with this name and this size.”

  • Group: the topic, such as group for resource groups, vm for virtual machines, storage for storage, or network for networks.
  • Action: usually a simple verb: create, list, show, update, or delete. Once you learn these five verbs, you can guess most commands.
  • Options: labeled details that start with two dashes, such as a name, a location, or a size.

Where you can get it

Windows

Installer package

A standard installer, or a package manager such as WinGet, puts the tool on your PC.

macOS

Homebrew

One line in a terminal using the popular Mac package manager installs and later updates it.

Linux

System packages

Packages for common Linux families let the normal system updater keep it fresh.

Containers

Docker image

A ready-made container image holds the tool, handy for pipelines and clean test setups.

Browser

Cloud Shell

Nothing to install. It is already there, already updated, and already signed in.

Getting help inside the tool

The CLI explains itself. Add a help option to any group or action, and it lists what is available with a short description of each option. There is also a find feature that suggests commands based on a plain-language question, and an interactive mode that shows hints and auto-completion as you type. For a learner, this built-in help is like having a manual that is always open at the right page.

4Everyday Skills with the CLI

A few small habits make the CLI feel comfortable. Here are the ones people use every day.

Signing in and choosing a subscription

Before the CLI can do anything, it needs to know who you are. The sign-in command opens a web page in your browser where you log in with your Microsoft account, usually including a second proof such as a phone approval. Once you finish, the CLI keeps a temporary pass so you do not have to log in for every command.

If your account can see several subscriptions, you pick the active one with the account commands. Doing this first is very important, because every create or delete command acts on the active subscription. Always check which one is selected before you change anything.

Output formats: choosing how answers look

By default the CLI prints answers as JSON, a structured text format that programs read easily but people find noisy. You can ask for friendlier shapes with the output option.

FormatWhat it looks likeBest for
jsonStructured, nested text, the defaultPrograms and scripts that need every detail
tableNeat rows and columnsQuick human reading
tsvPlain values separated by tabsFeeding one value into another command
yamlIndented, readable structureComparing and reading configuration
noneNo output at allSilent steps where only success matters

Filtering answers with a query

A single Azure resource can have dozens of properties, and most of the time you only want one or two. The --query option lets you pick exactly the pieces you need, using a small language called JMESPath. It works like a filter on a coffee machine: lots of water goes in, but only the part you want comes out. Combined with the table or tsv formats, it turns a wall of text into a tidy answer.

Saving defaults to type less

If you always work in the same resource group or region, you can store that as a default in the CLI’s configuration. After that you can leave the option out and the tool fills it in for you. Defaults live in a hidden folder named .azure in your home directory, together with your sign-in information and settings.

Extensions and long jobs

  • Extensions are add-on packs that teach the CLI new tricks, often for services that are new or specialized. You install one when you need it and remove it when you do not.
  • Long-running operations such as creating a large database can take several minutes. By default the CLI waits and shows nothing until done. A no-wait option returns control immediately, and a wait command lets you check back later.
  • Exit codes are small numbers a command leaves behind to say whether it worked. Zero means success, and any other number means something went wrong. Scripts use them to decide what to do next.
!
Watch out

The delete action is very quick and rarely asks “are you sure?” when told to skip the prompt. A delete on a resource group removes everything inside it. Read your command twice, and confirm the active subscription, before you press Enter.

5Azure Cloud Shell: A Terminal in Your Browser

Cloud Shell gives you a working command line in a few seconds, from any device with a web browser.

What it is

Azure Cloud Shell is a browser-based terminal that Microsoft hosts for you. You open it from the Azure portal by clicking the terminal icon, from its own web address, or from the Azure mobile app. In a few seconds, a command prompt appears. The Azure CLI is installed, a recent version is guaranteed, and you are already signed in with the same account you used for the portal.

It exists because setting up tools takes time and breaks easily. Think of the hassle: install the tool, install the right version, fix a broken update, sign in, repeat on a second computer. Cloud Shell removes all of that. It is especially handy on a borrowed computer, a tablet, a locked-down work laptop where you may not install software, or in an emergency at midnight.

Analogy

Cloud Shell is like a library computer lab with a personal locker. The machine you sit at is freshly cleaned and fully loaded with software every visit, so you never worry about setup. Anything you want to keep goes into your locker, which stays the same no matter which machine you sit at. When you leave, the machine is wiped.

Two flavors: Bash and PowerShell

When you first open Cloud Shell, you choose a style. Bash is the classic shell of Linux and Mac systems, loved for short commands and easy scripting. PowerShell comes from the Windows world and works with structured objects rather than plain text. Both can run the Azure CLI. PowerShell also has its own Azure command set, called Azure PowerShell. You can switch between the two at any time.

What is already installed

Azure

Azure CLI and Azure PowerShell

Both ready to use and kept up to date by Microsoft.

Build

Infrastructure tools

Commonly Terraform and Bicep support, so you can deploy templates right away.

Containers

Kubernetes tools

Tools such as kubectl and Helm for working with container clusters.

Code

Editors and languages

Text editors such as vim and nano, a built-in graphical editor, plus common languages like Python and Node.js.

Source

Git

For downloading and managing code from repositories.

One thing to know: Cloud Shell does not run a Docker engine, so you cannot build container images in the usual way inside it. For that, use a local machine or a build service.

Storage: your locker

The machine in Cloud Shell is temporary, but your files do not have to be. On first use, Cloud Shell offers to create a small storage account and a file share in Azure Files. A folder is saved there and mounted as your home folder every time, and a disk image of about five gigabytes keeps your files and settings. Your scripts, notes, and downloaded tools remain between sessions. A newer option lets you choose an ephemeral session with no storage at all, which is cleaner and cheaper but forgets everything when the session ends.

Sessions and limits

  • Idle timeout: at the time of writing, a session closes after about twenty minutes without typing. Your saved files remain; the running programs do not.
  • Not for very long jobs: a job that must run for hours belongs in a pipeline or on a server, not in a browser tab.
  • Handy extras: you can upload and download files through the toolbar, and a built-in editor lets you open and change a script without leaving the page.
  • Private networking: organizations with strict rules can place Cloud Shell inside their own virtual network so it can reach private resources.
i
Cost

Using Cloud Shell itself is free of charge, but the small storage account that holds your home folder is a normal Azure resource with a normal, very small, bill. Look for it in your resources so it does not surprise you.

6Side by Side: Which Tool Does What

Azure has several ways to do the same job. Knowing how they compare helps you pick the right one without second-guessing.

The tools compared

QuestionPortalAzure CLI (local)Cloud ShellTemplate files
How you use itClick in a websiteType commands on your computerType commands in a browserDescribe the end result in a file
Install needed?NoYesNoNeeds a tool to deploy them
Repeatable?HardYes, through scriptsYes, through scriptsBest of all
Learning curveGentleMediumMediumSteeper
Good forExploring, one-off tasksDaily work and automationQuick tasks from anywhereBuilding whole environments
Works offline?NoNeeds internet to reach AzureNoFiles can be edited offline

Azure CLI versus Azure PowerShell

These two are often confused. Both are official, both can do almost everything in Azure, and both work in Cloud Shell. The main difference is style. The CLI uses short commands that print text, which feels natural to people from Linux or web backgrounds. Azure PowerShell uses longer, verb-and-noun commands called cmdlets that pass around structured objects, which feels natural to Windows administrators. Neither is better. Choose the one your team already knows, and stay consistent.

How they connect

flowchart LR
    You["You"] --> Portal["Azure Portal website"]
    You --> Local["Azure CLI on your computer"]
    You --> Shell["Cloud Shell in the browser"]
    Pipe["Automation pipeline"] --> Local
    Local --> ARM["Azure Resource Manager"]
    Shell --> ARM
    Portal --> ARM
    ARM --> Auth["Sign-in and permission checks"]
    Auth --> Svc["Azure services: compute, storage, network, databases"]
    Svc --> Res["Your resources in data centers"]
Fig 1. Many doors, one front desk. Every tool sends its request to Azure Resource Manager, which checks identity and permissions before anything changes.

Read the diagram from the left. You can enter through the portal, a local CLI, or Cloud Shell, and an automation pipeline can use the CLI as well. All of those paths join at Azure Resource Manager. There the request is checked, and only then handed to the specific service that performs the work. This is why a mistake made from any tool has the same effect, and why a good permission setup protects you no matter which tool you use.

7Architecture and Components

Now let us open both tools and see what parts are inside and how they connect.

Inside the Azure CLI

The Azure CLI is written mostly in the Python language, and the installer carries its own copy of Python so you do not need to install one yourself. The program is built from layers, each with a clear job.

flowchart TB
    Cmd["Your command"] --> Launcher["az launcher"]
    Launcher --> Core["CLI core: parser, settings, help, output"]
    Core --> Mods["Command modules: vm, storage, network, and more"]
    Core --> Ext["Optional extensions"]
    Mods --> SDK["Azure SDK for Python"]
    Ext --> SDK
    Core --> Auth["Sign-in library and token cache"]
    SDK --> Auth
    SDK --> HTTPS["HTTPS requests"]
    HTTPS --> ARM["Azure Resource Manager"]
Fig 2. The layers of the Azure CLI. Only the modules you actually use are loaded, which keeps it fast.

Here is the story in words. Your command first meets the launcher, the small program that starts everything. The core reads your words, works out which command you meant, applies your saved settings, and decides how to print the answer. The core then hands the real work to a command module, a block of code that knows one area of Azure, such as virtual machines. If you installed an extension, it plugs in the same way. Modules use the Azure SDK, which is a library that knows how to build correct requests, and a sign-in library that supplies proof of your identity. The result is a secure web request that goes to Azure Resource Manager.

Inside Cloud Shell

Cloud Shell is a managed service. When you open it, Azure prepares a small Linux container, which is a lightweight, isolated computer environment, just for you. Your browser connects to it through a live two-way channel so what you type appears instantly and the output streams back.

flowchart LR
    Browser["Your browser"] --> Portal["Portal or shell.azure.com"]
    Portal --> Svc["Cloud Shell service"]
    Svc --> Box["Temporary Linux container"]
    Box --> Tools["Preinstalled tools: Azure CLI, PowerShell, Terraform, kubectl, git"]
    Box --> Tok["Token service using your identity"]
    Box --> Home["Home folder"]
    Home --> Files["Azure Files share in your storage account"]
    Tok --> ARM["Azure Resource Manager"]
    Tools --> ARM
Fig 3. Cloud Shell architecture. The container is temporary, but the home folder is backed by a file share you own.

Follow the arrows. Your browser talks to the portal or the Cloud Shell web address. The Cloud Shell service finds or creates a container for you. Inside that container are the preinstalled tools. A small token service inside the container hands out proof of your identity, so the tools never ask you to sign in again. Your home folder is not stored in the container itself; it is connected to a file share in a storage account in your own subscription. That is why your scripts survive when the container is thrown away.

i
Key idea

In both tools, the real work is never done on your keyboard or in the container. They only ask. All the heavy lifting happens inside Azure, which is why a low-powered tablet can control a huge cluster.

8How It Works Internally

A single typed line sets off a surprising chain of events. Let us walk along it.

The journey of one command

1

Read and understand

The CLI splits your line into the group, the action, and the options, and checks that the words make sense. If you made a typo, it tells you right here and suggests the closest valid word.

2

Load only what is needed

Rather than loading hundreds of command modules, the CLI uses an index to load just the one you need. This is why a command starts in about a second rather than ten.

3

Get a token

The CLI looks in its local cache for an access token, which is a short-lived digital pass that proves who you are. If the pass has expired, it uses a longer-lived refresh token to quietly get a new one.

4

Send the request

The command module builds a web request describing your wish and sends it securely over HTTPS to Azure Resource Manager, with the token attached.

5

Azure checks and acts

Resource Manager verifies the token, checks that your role allows the action at that location in your hierarchy, and forwards the job to the service responsible, called a resource provider.

6

Wait if needed

For quick actions the answer returns at once. For slow ones, such as building a server, Azure replies “accepted, check back,” and the CLI polls a status address until the job is done, unless you asked it not to wait.

7

Shape the output

The answer arrives as structured data. The CLI applies your query filter and output format, then prints the result and leaves an exit code behind.

Tokens in plain words

A token is like a wristband at a festival. You show your ticket once at the gate, and you get a wristband that lets you walk in and out for the day without showing the ticket again. Access tokens in Azure last roughly an hour and then expire, which limits the damage if one is ever stolen. The refresh token is a longer-lasting way to get a new wristband without logging in again. Both are kept in your local profile folder, so protecting that folder matters.

What Resource Manager does

Azure Resource Manager is a busy front desk. For each request it authenticates the caller, authorizes the action using role-based access control, validates the input, records the action in a log, and routes the job to a resource provider. A resource provider is the service that owns one family of resources. For example, one handles compute, another storage, another networks. Before you can use a family in a new subscription, it must be registered, which is a one-time switch. If you see an error that a provider is not registered, that is the reason, and the fix is to register it.

Rate limits and retries

Azure protects itself from overload by limiting how many requests one account can send in a period. If a script sends too many too fast, Azure answers with a “slow down” signal, known as throttling. The CLI automatically retries after a short pause in many cases, but a badly written loop can still hit the wall. Good scripts group their work and avoid asking the same question hundreds of times.

What happens inside Cloud Shell

When you press the Cloud Shell button, the service picks a data center near you, finds a free container, mounts your file share as the home folder, and arranges for the tools in the container to receive tokens for your identity. When you close the window or stay idle too long, the container is discarded. The next time you open it, you may land in a different container on a different machine, but with the same home folder. Because containers are replaced often, anything you install outside your home folder is gone next time.

9Data Flow and Lifecycle

Let us follow two stories: how data flows when you sign in and run a command, and how a Cloud Shell session lives and dies.

Sign-in and first command

sequenceDiagram
    participant U as You
    participant C as Azure CLI
    participant B as Browser
    participant E as Microsoft Entra ID
    participant M as Resource Manager
    U->>C: Run the sign-in command
    C->>B: Open the login page
    B->>E: You enter your account and second proof
    E-->>C: Access token and refresh token
    C->>C: Save tokens in local cache
    U->>C: Run a list command
    C->>M: HTTPS request with access token
    M->>E: Verify the token
    E-->>M: Token is valid
    M->>M: Check your role permissions
    M-->>C: Results as data
    C-->>U: Formatted output
Fig 4. From login to a first answer. Your password is typed into Microsoft’s login page, never into the CLI itself.

The most important detail here is who sees your password. The CLI opens a Microsoft sign-in page in your browser, and you type your credentials into that page. Microsoft Entra ID, the identity service, checks them and hands the CLI two tokens. The CLI never sees your password. After that, every command carries the access token, and Resource Manager double-checks it with Entra ID before touching anything.

The life of a Cloud Shell session

1

Open

You click the terminal icon. The service allocates a container and shows a prompt, typically within seconds.

2

Attach storage

Your file share is mounted as the home folder. On first use, Azure helps you create the storage account and share.

3

Authenticate

The tools receive tokens for your account automatically, so you can start working without logging in.

4

Work

You run commands, edit scripts, upload and download files. Saved files go to your share.

5

Idle and close

After a period without activity, the session ends. The container is discarded, but your home folder remains.

The life of a resource you create

Resources also have a life story. You create one with the CLI. Azure records the intended state, builds it step by step, and reports “succeeded” when done. You can then show it, update it, move it, tag it with labels, or lock it against deletion. Later you delete it, and Azure tears it down and stops the billing. Two practical points: some deleted items, such as certain secrets and databases, enter a soft-delete holding period before they vanish for good, and leftover disks or addresses from a deleted server may keep costing money until you remove them too.

Where your own data sits

On your local computer the CLI keeps a hidden folder in your home directory. It holds your tokens, your list of subscriptions, your saved defaults, and optional log files. In Cloud Shell the same folder exists inside the temporary container and is rebuilt as needed. Treat this folder as sensitive, because anyone who can read your tokens can act as you until they expire.

10Signing In and Permissions

There is more than one way to prove who you are to Azure. The right choice depends on whether a person or a program is asking.

Ways to sign in

MethodWho it is forHow it works
Interactive browser loginA person at a computerA login page opens in your browser, and you approve with your second proof.
Device code loginA person on a machine without a browserThe CLI shows a short code, and you enter it on another device that does have a browser.
Service principalA program or scriptAn app identity with a secret or certificate. It works, but secrets must be guarded and rotated.
Managed identityA program running inside AzureAzure itself hands the identity to the resource, so no secret exists to leak.
Federated identityA pipeline outside AzureThe pipeline proves itself with a trusted short-lived token from its own platform, with no stored secret.
Analogy

Think of an office building. A staff member swipes a personal badge, which is interactive login. A visitor gets a temporary code at the front desk, which is device code login. A cleaning contractor has a shared pass kept in a cupboard, which is a service principal with a secret: it works, but if someone copies it, you may never know. A building robot that is born inside the system with its own built-in access is a managed identity. A trusted courier company that vouches for each delivery person on the day is federation.

Who may do what: roles and scope

Signing in answers “who are you?” A different system answers “what may you do?” This is role-based access control, shortened to RBAC. You are given a role at a certain scope, and the permission applies to that scope and everything beneath it.

  • Scope is the level where the role applies: a management group, a subscription, a resource group, or a single resource.
  • Reader may look but not change anything.
  • Contributor may create and change resources, but cannot hand out permissions to others.
  • Owner may do everything, including giving other people access.
  • Specific roles exist for narrow jobs, such as only managing virtual machines or only reading storage data.

Permissions flow downward. A role given on a subscription applies to every resource group and resource inside it. This is convenient, but it is also why giving a broad role at a high level is risky.

i
In Cloud Shell

Cloud Shell does not give you extra power. It runs as you, with exactly your roles. If you are only a Reader, then Cloud Shell can only read. This is a feature, not a limit: the box in your browser cannot do anything your account could not already do in the portal.

11Security: Using Powerful Tools Safely

A command line is fast, and fast tools can cause fast damage. A few habits keep you and your cloud safe.

The main risks

Identity

Stolen or weak logins

If someone gets your account, they get everything your roles allow. Multi-factor sign-in and conditional access rules are the first line of defense, and Microsoft has been expanding required multi-factor sign-in for Azure management tools, so check its current guidance.

Secrets

Passwords in the open

Pasting a key into a script, a chat, or a public code site is a classic mistake. Automated scanners, including GitHub’s secret scanning, look for leaked cloud keys all day long.

Power

Too many permissions

An Owner role on a whole subscription turns every typo into a possible disaster and every stolen token into a catastrophe.

Mistakes

The wrong target

Running a delete command against the wrong subscription or resource group is far more common than any attack.

Local

Token files on shared machines

Signing in on a borrowed computer leaves tokens behind unless you sign out and clean up.

Storage

The Cloud Shell file share

It holds your scripts and sometimes secrets. If its storage account is open or shared, so is your home folder.

Protective habits

  • Least privilege. Give people and programs the smallest role at the smallest scope that lets them do their job.
  • Just-in-time elevation. Use Privileged Identity Management so powerful roles are switched on only when needed and switch off automatically afterwards.
  • No stored secrets. Prefer managed identities and federated sign-in. When a secret is unavoidable, keep it in Azure Key Vault, a secure safe for keys and passwords, and fetch it only at the moment of use.
  • Guard rails. Azure Policy can forbid unsafe settings, such as public storage or unapproved regions, even if someone tries them. Resource locks can block accidental deletion of important items.
  • Sign out on shared computers. Use the sign-out command, and close Cloud Shell on machines that are not yours.
  • Review the audit trail. Every change made through the CLI or Cloud Shell is recorded in the Activity Log, as we will see next.
!
Never do this

Do not copy command lines that contain passwords or keys into tickets, chat rooms, or screenshots. The shell also keeps a history of what you typed, so avoid typing secrets directly. Pass them through a secure vault or a protected variable instead.

The Cloud Shell safety net

Cloud Shell has a safety advantage. Because it is managed by Microsoft, the tools are always patched and clean, and no leftover tokens remain on your laptop. For companies with strict rules, it can run inside a private network and can be turned off for users who should not have it. These controls let security teams enjoy the convenience without giving up oversight.

12Monitoring, Logging, and Metrics

When something changes in your cloud, you want to know who did it, when, and from where. Azure keeps that diary for you.

The Activity Log: the cloud’s diary

Every change sent to Azure Resource Manager, whether it came from the portal, the CLI, Cloud Shell, or a pipeline, is recorded in the Activity Log. Each entry says who did it, what they did, which resource it touched, when, and whether it succeeded. By default the log is kept for about ninety days, and you can send a copy to a long-term store called a Log Analytics workspace for longer storage, searching, and alerts.

flowchart LR
    Act["Any change from CLI, portal or pipeline"] --> ARM["Azure Resource Manager"]
    ARM --> Log["Activity Log"]
    Log --> LA["Log Analytics workspace"]
    LA --> Alert["Alert rules"]
    Alert --> Team["Security or operations team"]
    LA --> Dash["Dashboards and reports"]
Fig 5. From a typed command to a recorded event. The tool you used does not matter; the front desk logs everything.

You can read the log in the portal or ask for it from the CLI. A security team might create an alert such as “tell us whenever someone deletes a resource group” or “tell us when a new Owner role is assigned.” Because every tool passes through the same front desk, these alerts cover everything.

Seeing what the CLI itself is doing

Detail

Verbose mode

Adds a few extra lines that describe progress. Good for slow commands.

Deep

Debug mode

Shows the raw web requests and responses. Your best friend when something fails in a strange way. Be careful sharing this output, since it may hold sensitive details.

Quiet

Only show errors

Hides warnings so scripts print only what truly matters.

Records

Log files

The CLI can write its own command logs to a file, which helps you see what happened during a script run.

Metrics and cost

The CLI is not only for building things; it can also read the health of your resources. Monitor commands fetch numbers such as processor use for a virtual machine, and query commands let you search your logs. For money, cost and budget commands let you see spending and create budgets with alerts. Scripts can use exit codes to report success or failure to a scheduler, which turns your commands into something you can monitor too.

i
A note on privacy

The Azure CLI can send anonymous usage information to Microsoft to help improve the product. This is controllable in its settings, and organizations that prefer to switch it off can do so.

13Advantages, Disadvantages, and Trade-offs

Every tool has strengths and limits. Knowing both lets you use each one where it shines.

The Azure CLI

Pros

  • Fast for people who know it
  • Easy to script and repeat
  • Same behavior on Windows, Mac, and Linux
  • Works in pipelines with no human present
  • Built-in help and filtering

Cons

  • Needs a learning period for the words and options
  • Typos can cause real damage
  • Scripts describe steps, not the end result, so they can drift
  • Updates may change behavior, so versions matter

Cloud Shell

Pros

  • Nothing to install or maintain
  • Always signed in and up to date
  • Works from any device with a browser
  • Good tool set pre-loaded
  • Files kept between sessions

Cons

  • Sessions time out when idle
  • Not suited to very long or heavy jobs
  • No Docker engine for building images
  • Needs a browser and internet access
  • Small storage cost and one more resource to secure

The main trade-offs

Trade-offLeaning toward local CLILeaning toward Cloud Shell
Setup effortInstall and update it yourselfNone
Control of versionsYou choose and pin a versionMicrosoft provides the latest
Long-running workFineLimited by idle timeout
Access from many placesOnly where installedAnywhere with a browser
Fit with automationExcellentMostly for interactive use
Local files and toolsFull access to your machineOnly what you upload or keep in the share
!
Version surprises

New CLI versions can rename options or change defaults. A script that worked last year may behave differently after an update. For important pipelines, pin the CLI to a known version and upgrade on purpose, after testing.

Scripts versus templates

The biggest trade-off is between commands and templates. A CLI script says “do step one, then step two.” A template says “make the world look like this.” Templates are better at keeping a large environment correct over time because they describe the end state and can find drift. CLI scripts are better for quick tasks, glue between systems, and one-off fixes. Mature teams use both, each where it fits.

14Design Patterns and Anti-Patterns

A pattern is a recipe that has worked many times. An anti-pattern is a mistake so common it earned a name.

Patterns that work

Safety

Check, then create

Write scripts so that running them twice causes no harm. Ask “does this already exist?” first, and only then build. Such scripts are called idempotent, which just means safe to repeat.

Order

Naming and tagging rules

Agree on a standard for names and labels, such as project, owner, and environment. Then every resource is easy to find, bill, and clean up.

Config

Variables at the top

Put names, regions, and sizes in one clear place at the start of a script, so changing one value does not mean hunting through the whole file.

Preview

Look before you leap

Use preview features such as what-if checks for template deployments, and run a list command before any delete, to see exactly what will be touched.

Split

Templates for state, CLI for glue

Let templates describe the long-lived environment, and use the CLI for quick tasks, checks, and connecting systems together.

Identity

No-secret pipelines

Let automation prove its identity with a short-lived token from its own platform, so no password is ever stored.

Analogy

A check-then-create script behaves like a careful host setting a table. Before placing a fork, the host looks to see whether a fork is already there. Run the routine ten times and the table still looks the same. A careless host would pile up ten forks at each seat.

Anti-patterns to avoid

ANTI-PATTERN 01 · CLICK-OPS SNOWFLAKEAvoid
What it looks like

A whole environment built by hand in the portal over many months, with no notes about what was done.

Why it hurts

Nobody can rebuild it after a disaster, copy it for testing, or explain why a setting is the way it is.

Better way

Capture the setup in scripts or templates stored in version control, so the environment can be recreated from the files.

ANTI-PATTERN 02 · SECRETS IN SCRIPTSAvoid
What it looks like

A password or key written directly into a script that is then saved to a shared folder or a code repository.

Why it hurts

Anyone who can read the file can use the secret. Public repositories are scanned by attackers within minutes.

Better way

Use managed identities, federated sign-in, or a vault, and let the script fetch the secret only when it needs it.

ANTI-PATTERN 03 · OWNER EVERYWHEREAvoid
What it looks like

Giving every engineer and every pipeline the Owner role on the whole subscription “to make things work.”

Why it hurts

One slip or one stolen token can delete or expose everything. It is also impossible to tell who needed what.

Better way

Use narrow roles at narrow scopes, and raise permissions only for a short time when a task truly needs it.

ANTI-PATTERN 04 · CLOUD SHELL AS A BUILD SERVERAvoid
What it looks like

Starting a job that runs for hours in a browser tab and hoping the tab stays alive.

Why it hurts

The session times out when idle or when the connection drops, and the job dies half done.

Better way

Run long or scheduled work in a pipeline, on a virtual machine, or in a managed automation service built for it.

15Best Practices and Common Mistakes

These habits separate calm Azure users from stressed ones.

Habits worth building

1

Check where you are

Before every change, confirm the active subscription and the target resource group. Make this a reflex, like checking mirrors before driving.

2

List before you delete

Run a list or show command with the same filter first. If the list is not what you expected, the delete would not be either.

3

Use a practice subscription

Learn and experiment in a separate subscription with a small budget, never in the one that runs the business.

4

Save work as files

Keep scripts in version control with clear comments, and review changes as you would review any important document.

5

Choose the output on purpose

Use table format for reading, and tsv or json with a query when feeding results to the next step.

6

Set budgets and clean up

Create budget alerts, tag everything with an owner, and delete leftover test resources at the end of each project.

7

Pin versions in automation

Fix the CLI version in pipelines, test upgrades first, and read the release notes for changes that could break scripts.

Common mistakes

  • Acting on the wrong subscription. The tool will happily obey. It cannot know you meant a different one.
  • Forgetting to register a provider. A new subscription may reject a command until the matching provider is registered.
  • Mixing up region names. Each region has a short name without spaces, such as “centralindia,” and a display name with spaces, such as “Central India.” Using the short form in scripts avoids quoting problems and typos.
  • Believing “succeeded” means “secure.” A resource can be created successfully and still be wide open to the public.
  • Leaving the storage account for Cloud Shell unmanaged. Tag it, secure it, and include it in your reviews.
  • Ignoring throttling. Looping through thousands of resources one by one can hit limits. Ask for lists in bulk instead.
  • Copying commands from the internet without reading them. A snippet that worked for someone else may delete, expose, or cost more than you expect.
!
Costs that sleep quietly

Stopping a virtual machine from inside its own operating system does not always stop the billing for its compute. Deallocating it does. Disks, public addresses, and backups also keep charging after a server is gone. After a cleanup, list what remains and confirm the bill drops.

16Real-World Examples

These tools are woven into the products and workflows of many well-known platforms. Here are some places you meet them.

GitHub Actions: deploying with no stored password

GitHub, owned by Microsoft, offers an official sign-in action for Azure. A repository can be linked to Azure through federated identity, so when a workflow runs, GitHub issues a short-lived token that Azure trusts. The workflow then runs Azure CLI steps to deploy an app. No password is saved anywhere, which is the safest pattern for pipelines.

Azure DevOps: the CLI task in pipelines

Azure DevOps, Microsoft’s build and release service, includes a ready-made task that runs Azure CLI scripts using a connection to your subscription. Teams use it to create environments, push settings, and run checks as part of each release, so the same steps run the same way every time.

Terraform: borrowing your CLI sign-in

Terraform, the widely used infrastructure tool from HashiCorp, has an Azure provider that can use your existing Azure CLI sign-in when you work on your own computer. Engineers sign in once with the CLI, and Terraform picks up the same identity. For production pipelines, teams switch to a service principal or federated identity.

Kubernetes on Azure: fetching cluster access

Teams that run containers on Azure Kubernetes Service use a CLI command to download the connection settings for a cluster into their working environment. After that, Kubernetes tools such as kubectl, which come preinstalled in Cloud Shell, can talk to the cluster. This is one of the most common reasons people open Cloud Shell.

Microsoft Learn: hands-on practice with no setup

Many training modules on Microsoft Learn offer a temporary sandbox environment together with a built-in Cloud Shell, so learners can practice real commands without paying or risking a real subscription. It is the same tool that professionals use, in a safe, disposable setting.

Everyday scenarios

The following are typical, illustrative situations rather than reports about particular companies.

  • The nightly cost saver. An online retailer’s team writes a small script that stops test servers each evening and starts them each morning, run by a scheduler. The test bill drops sharply with almost no effort.
  • The midnight fix. An on-call engineer gets an alert on a phone, opens Cloud Shell from the Azure mobile app, scales up a database, and goes back to sleep. No laptop was needed.
  • The locked-down laptop. A consultant joins a client whose laptops forbid installing software. Cloud Shell in a browser lets the consultant work from day one.
  • The audit request. A security officer asks for every storage account that allows public access. One query across all subscriptions returns the list in a table, ready to share.

A typical learning-to-production journey

A newcomer usually starts in the portal, clicking to see what exists. Then they discover Cloud Shell and run a few list commands, because it is one click away. Soon they save useful commands in a script on their file share. Next they install the CLI locally for faster work and add it to a pipeline. Finally, as the environment grows, they move the long-lived parts into templates and keep the CLI for checks and glue. Nearly everyone who works with Azure follows a version of this path.

Click to learn. Type to repeat. Describe to scale.

17Choosing the Right Tool

With so many ways to reach Azure, a simple decision path keeps you from overthinking.

flowchart TD
    Start["You need to change something in Azure"] --> Q1{"Is it a one-time look or small change?"}
    Q1 -- Yes --> Q2{"Do you prefer buttons and menus?"}
    Q2 -- Yes --> Portal["Use the Azure portal"]
    Q2 -- No --> Q3{"Is your own computer set up with the CLI?"}
    Q3 -- Yes --> Local["Use the local Azure CLI"]
    Q3 -- No --> Shell["Use Cloud Shell"]
    Q1 -- No --> Q4{"Are you building a whole environment to keep correct over time?"}
    Q4 -- Yes --> Tmpl["Use a template such as Bicep or Terraform"]
    Q4 -- No --> Pipe["Use CLI scripts, run by a pipeline or scheduler"]
Fig 6. A simple way to pick a tool. Start at the top and follow your answers.
Your situationGood fitWhy
Exploring Azure for the first timePortal, then Cloud ShellSee things first, then learn to type them.
Quick fix from a phone or borrowed laptopCloud ShellNothing to install, already signed in.
Daily work at your own deskLocal Azure CLIFast, with your own files and tools at hand.
Same task every nightCLI script in a pipelineRepeatable and needs no human.
Full environment for a productBicep or TerraformDescribes the desired end state and prevents drift.
Team that lives in Windows administrationAzure PowerShellMatches the skills and style they already have.

A simple learning path

1

Open Cloud Shell and look around

List your subscriptions and resource groups. Reading is safe and teaches you the layout.

2

Create and delete something small

Make a resource group with one inexpensive resource in a practice subscription, look at it in the portal, then remove it.

3

Learn output and query

Practice table output and the query filter until you can extract exactly the value you want.

4

Save your first script

Put the steps in a file in your home folder with variables at the top, and run it twice to prove it is safe to repeat.

5

Install locally and automate

Install the CLI on your computer, connect a pipeline using federated sign-in, and add a budget alert.

6

Move the long-term setup into templates

Learn Bicep or Terraform for the parts that must stay correct, and keep the CLI for everything else.

18Frequently Asked Questions

Quick answers to the questions people ask most.

Q1Is the Azure CLI free?
Yes. The tool itself costs nothing and is open source. You pay only for the Azure resources that your commands create.
Q2Is Cloud Shell free?
Using it is free, but the storage account that keeps your home folder is a normal Azure resource with a small cost. An option without persistent storage avoids that.
Q3What is the difference between the Azure CLI and Cloud Shell?
The CLI is the tool. Cloud Shell is a browser-based environment that comes with the CLI and other tools already installed and signed in. You can use the same CLI on your own computer as well.
Q4Should I learn the CLI or Azure PowerShell?
Pick the one that matches your background or your team’s habits. Both reach almost every Azure feature. Many people learn one well and read the other when needed.
Q5Why does my Cloud Shell session keep closing?
Sessions end after a period of inactivity, about twenty minutes at the time of writing. Your saved files remain, but running programs stop. For long tasks use a pipeline or a server.
Q6Can I use Cloud Shell on my phone?
Yes. The Azure mobile app includes Cloud Shell. Typing long commands on a small screen is awkward, but it is great for quick checks and emergencies.
Q7How do I know which subscription I am using?
Use the account commands to show the current subscription and list the others. Make it a habit to check before any create, update, or delete.
Q8What is a service principal?
It is an identity for a program rather than a person, with its own permissions. Where possible, prefer a managed identity or federated sign-in, which avoid storing a secret.
Q9What does a “provider not registered” error mean?
The subscription has not yet switched on the service family you are trying to use. Registering that provider once fixes it.
Q10How do I keep the CLI up to date?
On your own computer, use the same package manager you used to install it, or the CLI’s built-in upgrade command. In Cloud Shell, Microsoft keeps it current for you.
Q11Can I work with more than one account or tenant?
Yes. You can sign in to several accounts and tenants and switch between their subscriptions. Always check which one is active before making changes.
Q12Is it safe to practice on my real subscription?
It is better not to. Use a separate practice subscription with a budget alert, or a learning sandbox, so that a slip cannot touch anything important.

19Summary and Key Takeaways

The whole guide in a few lines.

Key Takeaways

  • Two tools, one idea. The Azure CLI is the typed-command tool, and Cloud Shell is a browser-based terminal that already contains it, signed in and up to date.
  • Everything goes through one front desk. The portal, the CLI, Cloud Shell, and pipelines all send requests to Azure Resource Manager, which checks identity and permissions.
  • Commands read like sentences. Group, action, and options. Learn the five verbs create, list, show, update, and delete, and you can guess most of the tool.
  • Cloud Shell is temporary, your home folder is not. The container is thrown away when idle, but files in your home folder are kept in a file share you own.
  • Safety is about identity and scope. Use multi-factor sign-in, narrow roles, managed or federated identities, and a vault for secrets. Always check the active subscription first.
  • Every change is recorded. The Activity Log shows who did what and when, regardless of which tool they used, and alerts can watch for risky actions.
  • Use each tool where it shines. Portal to explore, Cloud Shell for quick work anywhere, local CLI for daily work and automation, and templates for environments that must stay correct.