Azure Cloud Series: This lesson is part of our comprehensive Complete Microsoft Azure Tutorial: Learn Azure from Beginner to Advanced.
KODESTREE TECHNOLOGIES
AZURE SEO CONTENT HUB
Pillar cluster: Azure DevOps, Infrastructure as Code & Automation
Primary search intent: How to manage Azure resources using Azure CLI, Azure PowerShell and software development kits.
Azure CLI, Azure PowerShell and Azure SDKs are three complementary ways to work with Microsoft Azure without relying on manual portal actions for every task. They expose Azure management and service capabilities through commands, scripts and application code. Choosing the right interface helps teams make changes repeatable, reviewable and easier to troubleshoot.
Azure CLI is a cross-platform command-line tool especially convenient for interactive terminal work and shell automation. Azure PowerShell provides cmdlets that fit naturally into PowerShell workflows, including structured object processing. Azure SDKs let application code interact with Azure services through language-specific libraries. The tools overlap, but they are not interchangeable for every job.
This tutorial explains how to choose among them, authenticate safely, select a subscription, run repeatable operations, manage errors and integrate automation into a responsible cloud workflow. Examples are illustrative; validate command parameters, permissions and service availability against current Microsoft Learn documentation before using them in production.
What You Will Learn
- Distinguish Azure CLI, Azure PowerShell and Azure SDKs by purpose.
- Confirm the active account, tenant and subscription before operating on resources.
- Use safe discovery commands before changing Azure resources.
- Authenticate scripts and applications with appropriate identities and least privilege.
- Handle output, errors, retries, logging and configuration in repeatable workflows.
- Choose the right interface for administration, automation or application integration.
- Build a small practice workflow and document validation and cleanup.
Quick Reference: Core Concepts
| Concept | Purpose |
|---|---|
| Azure CLI | Cross-platform `az` commands for terminal work and shell scripts. |
| Azure PowerShell | Az module cmdlets that work with PowerShell objects and pipeline composition. |
| Azure SDK | Language-specific packages for application code to call Azure APIs and services. |
| Control plane | Operations that create, update, inspect or delete Azure resources. |
| Data plane | Operations against service data, such as reading a blob or publishing a message. |
| Managed identity | Azure-managed identity used by supported workloads without embedded credentials. |
1. What Are Azure CLI, PowerShell and SDKs?
Azure CLI is a command-line interface for managing Azure from Windows, Linux, macOS, Cloud Shell or supported containers. Its `az` command tree groups operations by service, including resource groups, virtual machines, storage and networking. Azure PowerShell is built around the Az module: cmdlets return structured PowerShell objects that can be filtered, transformed and passed to other commands. Azure SDKs are client libraries for languages such as .NET, Python, Java and JavaScript.
These tools provide different interaction styles over Azure APIs. A platform engineer might use CLI commands to inspect a deployment, PowerShell to process a resource inventory, and an SDK inside an application that uploads files to Blob Storage. Choose the interface that matches the task, execution environment and team skills rather than forcing every task into one tool.
2. Why Do These Tools Matter?
A portal workflow is useful for learning and one-time inspection, but repeated manual operations are difficult to audit and easy to perform inconsistently. Scripts make steps visible, versionable and repeatable. A validated command can become a runbook; a tested PowerShell function can apply a check to a resource inventory; an SDK client can integrate a service call into an application workflow.
Automation also reduces uncertainty during incident response. If a runbook consistently collects resource metadata, checks deployments and queries service state, engineers can follow a similar diagnostic path each time. This does not mean scripts should execute destructive changes blindly. Useful automation includes explicit scope, input validation, least privilege, error handling, logs and a documented stop or recovery path.
3. Key Concepts and Terminology
A tenant is the Microsoft Entra directory in which identities and application registrations are managed. A subscription is a billing and management boundary for Azure resources. A resource group is a logical container for resources with a shared lifecycle or management purpose. The signed-in identity, current tenant, selected subscription and assigned role determine what commands can see and change.
Control-plane and data-plane operations are different. A command that reads a resource group inspects a management resource, while an SDK call that reads a blob operates on service data. Required permissions may differ. A successful CLI login therefore does not prove that the caller has permission to access every service or data item.
4. How Authentication and Context Work
For interactive local work, Azure CLI commonly uses `az login`; PowerShell uses `Connect-AzAccount`. The user completes sign-in using a supported method. In automated workflows, use a supported non-interactive identity such as workload identity federation, a managed identity or a service principal where appropriate. The choice must fit the execution environment and target service.
After sign-in, explicitly check the context. CLI workflows can inspect subscriptions with `az account list` and select one using `az account set –subscription <subscription-id>`. PowerShell can use `Get-AzContext` and `Set-AzContext`. These checks matter when an operator has access to several environments: an incorrect default subscription can make a valid command change the wrong resource group.
5. Core Components of a Reliable Tooling Setup
A reliable setup includes the CLI executable or SDK package, a supported runtime if required, credentials, role assignments, configuration values, output conventions and a way to record execution. Keep tools reasonably current and align versions across team environments when reproducibility matters. For build agents, select supported images and avoid depending on undocumented tools that happen to be preinstalled.
Separate code from environment-specific values. Subscription IDs, resource group names, locations, endpoint URLs and feature flags should be configuration rather than scattered literals. Never place passwords, client secrets or access tokens in source code, terminal transcripts or committed settings. Store sensitive values in an approved secret system or use federation and managed identities when supported.
6. Planning Before Running Commands
Before provisioning resources, clarify the task, target scope, permissions, expected result and rollback path. Identify whether the operation is a harmless read, a reversible update or a destructive action. Check quotas, regional support and naming constraints when they could block the workflow. For production changes, follow the approved change process and ensure the caller has only the permissions necessary for the task.
Plan for environments explicitly. A development script may create temporary resources with non-production data, while a production workflow should use reviewed inputs, protected credentials, approvals and logs. Do not select a subscription only because it was used last time. Resolve the environment from an intentional input and fail early when context does not match the expected tenant or subscription.
7. A Practical Azure CLI Workflow
Start with read-only discovery. `az account show` displays the current account context, `az group list –output table` lists resource groups, and `az resource list –resource-group <group-name> –output table` displays resources in a known group. Use `az –help` and the service command reference to confirm syntax and supported options. Replace placeholders only after checking the target scope.
A controlled script checks prerequisites before changes, captures exit status and prints enough information for a reviewer to understand the action. CLI commands commonly support structured JSON as well as human-readable tables. Prefer structured output when another process consumes results. Avoid parsing a presentation table with brittle text matching when the command can return JSON.
8. A Practical Azure PowerShell Workflow
Azure PowerShell is useful when a task is naturally expressed as a sequence of object operations. `Get-AzContext` reveals the active context, while resource cmdlets return objects that can be filtered with `Where-Object`, selected with `Select-Object` or exported for review. Use the official module documentation to choose the relevant Az command and keep the execution host on a supported version.
The object pipeline is an advantage with resource collections. A runbook might retrieve virtual machines, select those matching a naming convention and produce a report of location and power state. Keep reporting separate from changing resources, and review the target set before an update or deletion. This creates a natural review point and limits accidental bulk changes.
9. Using SDKs in Application Code
An SDK is usually appropriate when an application itself must call an Azure service. A typical flow installs a service client package, configures authentication, creates a client and invokes a typed operation. The SDK often manages request construction and exposes language-native models, exceptions and asynchronous methods. Use service-specific documentation instead of guessing class names or assuming one package covers every API.
Management SDKs and service client SDKs may serve different purposes. Management libraries create or configure Azure resources; data libraries interact with service data. An application that reads a secret from Key Vault or uploads a blob generally needs the relevant service client and corresponding permissions, not broad subscription administration rights. Keep application identity separate from developer sign-in so deployed behavior remains consistent.
10. Security and Least Privilege
Treat a tool as an execution path for permissions, not as a security boundary by itself. A command or SDK operation succeeds only if the identity has the required authorization. Grant access at the narrowest practical scope, prefer appropriate built-in roles and separate read access from operations that change or delete resources. For automation, prefer managed identities or federated workload credentials over long-lived secrets when supported.
Avoid granting broad permissions just to make an example work. A workflow that reads a specific storage account should not receive Owner rights over a subscription. Keep credentials out of command history and logs, restrict who can change privileged scripts, and protect pipeline service connections. Periodically review access and remove identities, role assignments and credentials that are no longer needed.
11. Handling Output, Errors and Retries
A workflow should distinguish an empty result from a failed request. Capture exit codes, use explicit error handling and write actionable diagnostics. CLI commands commonly return a non-zero status on failure; PowerShell scripts may need terminating-error behavior when a failure must stop execution. SDKs often raise exceptions that should be handled where the application can retry, report the problem or safely abandon the operation.
Retries should be limited to transient failures and respect service guidance. Repeating a read request is often safe, while retrying a create, update or purchase operation may have side effects if the operation is not idempotent. Use SDK retry policies where appropriate, avoid tight retry loops and include timeouts and cancellation. Record the target and correlation details without logging secrets or sensitive payloads.
12. Logging and Operational Diagnostics
Logs should answer who ran an operation, which environment it targeted, what action was attempted, whether it completed and where to investigate a failure. Scripts can capture timestamps, outcomes, exit codes and sanitized diagnostic output. SDK applications should use appropriate application and SDK logging while avoiding tokens, connection strings, customer data and secret values. Correlate workflow logs with Azure Activity Log or service diagnostics when relevant.
Verbose logs are useful during troubleshooting, but diagnostic verbosity should not remain enabled blindly in production. Excessive logging can expose sensitive content, increase cost and obscure useful signals. Define log levels, retention and access policies. During an investigation, note the time, resource ID, operation name and request or correlation ID when available; these details help connect local logs with platform records.
13. Performance and Scale
Command-line tools are often used for administration, while SDKs commonly support application operations at higher volume. Large inventory scripts should avoid making one network request per resource when a list or batch operation can satisfy the same need. Use paging correctly, respect continuation tokens and service limits, and avoid running large numbers of concurrent updates without a control plan.
Performance problems may arise from throttling, network latency, authentication renewal, inefficient filtering or excessive calls. Filter close to the service, reuse client objects where recommended and avoid creating a new client for every operation without reason. For bulk changes, use bounded concurrency, progressive rollout and a clear stop condition rather than maximizing parallelism at any cost.
14. Cost and Change Governance
The CLI or SDK call is rarely the main cost driver; the Azure resources it creates or modifies can incur charges. A script that provisions a VM, public IP, storage account or database must account for runtime, storage, transfer and related components. Use naming conventions and resource tags where supported so owners and environments remain visible. For exercises, document cleanup and verify dependent billable resources are removed.
Guardrails matter when automation can provision at scale. Validate parameters, reject unexpected environment names, use budgets and policy controls where appropriate, and separate preview or reporting modes from apply modes. Require review for high-risk changes. Change logs should retain enough detail to reconstruct what happened without becoming a repository of credentials or personal information.
15. Integration with Other Azure Services
CLI and PowerShell can support deployment workflows, while SDKs connect application logic to services such as Storage, Key Vault, Event Hubs and databases. Scripts can prepare infrastructure and assign workload identity permissions; application code then uses that identity to perform its task. Keep these responsibilities clear so application deployment does not require permanent subscription-wide administrator access.
The same workflow may span control-plane and data-plane steps. A pipeline may deploy storage infrastructure, enable diagnostics, assign a role and then deploy an application that uses a storage SDK. Test each boundary independently: resource creation, network path, token acquisition, effective authorization and the application operation. This makes failures easier to localize.
16. Practical Scenario: A Repeatable Resource Audit
Imagine a team needs a weekly report of resource groups, locations, tags and selected properties across development and test subscriptions. A CLI script can establish account context, enumerate approved subscriptions and write JSON or CSV summaries. A PowerShell version can use Az objects to create a consolidated report. The reporting identity should have read permissions, not permissions to modify resources.
The report should identify its scope and fail if it cannot verify the expected tenant. It should handle an empty inventory, missing tags and partial subscription access without silently claiming that all resources were inspected. Save output in an approved location, limit access, retain it only as long as needed and document which properties the audit does not evaluate.
17. Common Mistakes to Avoid
Frequent mistakes include assuming successful login means the right subscription is selected, copying commands without understanding scope, hard-coding credentials, using broad roles to overcome authorization errors and relying on text output that can change between versions. SDK users may also mix management and service clients or use a credential option that works on a developer laptop but not in a hosted environment.
Another risk is turning an interactive command sequence into a production script without tests. Before scheduling it, test missing parameters, denied permissions, transient network failures and partial completion. Confirm whether rerunning the workflow is safe. Mark destructive actions clearly and make output understandable to someone other than the original author.
18. Troubleshooting Method
When a command fails, reproduce the smallest failing step and record the exact sanitized error. Confirm tool version, authentication context, tenant, subscription, role assignment, resource name and region. Determine whether the failure is authorization, an invalid parameter, a missing resource, a service limitation, a network problem or a transient response. Use official command references because defaults and parameters can evolve.
For SDK issues, check package version, credential chain, endpoint, application configuration, exception details and service diagnostics. For permission errors, identify the required action and scope instead of granting broad rights immediately. For throttling, follow service retry guidance. Once fixed, add a regression check or runbook note so another operator can recognize the failure quickly.
19. Pre-production Checklist
Before a script or SDK integration is released, confirm identity, tenant and subscription; required roles; configuration source; expected output; failure behavior; log redaction; retry policy; timeouts; and cleanup or rollback. Store code in version control and require review for changes that run with elevated permissions. Pin dependencies where appropriate and test the update process instead of leaving tool versions unmanaged.
For sensitive operations, begin with read-only validation or a preview of the target set. Use a test subscription and non-production data first. Check what happens when execution is interrupted halfway through. Document idempotency, duplicate-processing risk and evidence that proves completion. A handoff should include ownership, troubleshooting steps, credential rotation if applicable and a safe way to disable the automation.
Frequently Asked Questions
Should I learn Azure CLI or Azure PowerShell first?
Start with the tool that matches your current shell and work. Azure CLI is convenient across platforms and in shell scripts; PowerShell is excellent for administrative automation built around objects and cmdlets. Learning one well makes the second easier because the underlying Azure concepts remain the same.
Can Azure CLI run on Windows and Linux?
Yes. Azure CLI is cross-platform and can also be used through Azure Cloud Shell. Check the official installation guide for supported installation paths and the version available in your environment.
When should I use an Azure SDK instead of a CLI command?
Use an SDK when application code needs to call a service as part of normal runtime behavior. Use CLI or PowerShell for administration, deployment scripts and operator tasks unless there is a clear reason to spawn command-line processes from the application.
Why does login succeed but a command still fail?
Authentication confirms an identity; authorization and context still matter. Verify tenant, subscription, role assignments, resource scope and whether the task needs data-plane permissions.
Are service principal secrets required for automation?
Not always. Prefer managed identity or workload identity federation when the execution environment and service support them. Use securely stored credentials only when a supported alternative is not practical.
How should I keep scripts safe?
Use least privilege, validate inputs, avoid secrets in source and logs, test failure paths, review changes, make destructive operations explicit and preserve sanitized logs that are useful during diagnosis.
Conclusion
Azure CLI, Azure PowerShell and SDKs offer different ways to manage resources and connect applications to Azure. Choose each tool according to its purpose, use deliberate tenant and subscription context, authenticate with appropriate identities, and treat errors and security as part of the workflow rather than afterthoughts. Reliable automation is reviewed, repeatable, observable and designed to stop safely when assumptions are not met.
20. Security Fundamentals
Build each workflow around a trusted identity and the minimum permissions required. Separate human operators from application identities, scope role assignments narrowly and prefer short-lived or platform-managed credentials. Protect repositories and pipeline definitions because anyone who can change a privileged script may be able to exercise its permissions.
21. Additional Limitations and Operational Considerations
Command syntax, SDK packages, API versions and service support evolve. A script can fail because a runtime changed, a command was removed, a role assignment has not propagated or an API supports different features. Review dependencies, test upgrades and avoid relying on undocumented behavior.
22. Recommended Learning Path
Learn tenants, subscriptions, resource groups, resource IDs and Azure RBAC first. Practise read-only CLI commands, PowerShell context and object commands, then use one SDK client with a supported credential flow. Turn a successful exercise into a version-controlled script with parameter validation, logging and cleanup.
23. Service Selection and Architecture Thinking
Choose CLI for concise cross-platform administration, PowerShell for object-oriented administrative workflows and an SDK for application-level service calls. A mature platform may use all three. Define which layer owns resource deployment, role assignment, application operations and reporting; avoid one script silently owning every layer.
24. Scalability and Performance
At scale, reduce unnecessary requests, use paging and supported batch operations, and bound concurrency. Add retry policies that respect the operation’s safety. For large inventory or deployment tasks, progress in controlled batches and record each item’s outcome so partial failures can be recovered.
25. Reliability and Recovery
Design scripts to be rerunnable when possible and document where rerunning could create duplicates or overwrite state. Separate validation from mutation, log before and after meaningful operations, and make partial completion visible. For critical operations, test rollback or recovery instead of assuming the next run will repair every failure.
26. Hands-on Practice and Production Thinking
Create a small lab that lists a known resource group, checks context, produces a structured inventory and exits cleanly when access is denied. Repeat in CLI and PowerShell, then use an SDK client for a data operation. Add a README with prerequisites, permissions, expected output, common errors and cleanup steps.
Example: Inspect a resource group safely
Before writing a script that changes infrastructure, begin with a read-only audit. This example shows the checkpoints; replace placeholders only after verifying the target environment:
`az login`
`az account show`
`az account set --subscription <subscription-id>`
`az group show --name <resource-group>`
The purpose is to confirm the identity and context before taking action. In PowerShell, use `Connect-AzAccount`, inspect `Get-AzContext`, set the intended context, then call the relevant `Get-Az*` cmdlet. A production script should validate the expected tenant and subscription and stop if context differs.
Related Azure Topics
Continue with these related tutorials to connect this topic to the wider Azure learning path:
- Microsoft Entra ID and Azure Identity
- Azure RBAC: Roles, Assignments and Scopes
- Azure Resource Manager (ARM) Templates
- Bicep and Infrastructure as Code on Azure
- Azure Pipelines and CI/CD
References and Further Reading
Use the following Microsoft documentation as the primary technical references. Check current command syntax, product capabilities, service limits and pricing before production use:
- What is Azure CLI?
- Install Azure CLI
- Authenticate to Azure using Azure CLI
- Introducing the Az PowerShell module
- Azure SDK for .NET overview
- Authenticate .NET applications to Azure
SEO and Editorial Metadata
| Document ID | Azure-051 |
|---|---|
| Article Title | Azure CLI, PowerShell and SDKs |
| Primary Search Intent | How to manage Azure resources using Azure CLI, Azure PowerShell and software development kits |
| Suggested URL | /azure-cli-powershell-sdks/ |
| Canonical URL | https://kodestree.com/azure-cli-powershell-sdks/ |
| Pillar Page | https://kodestree.com/azure-tutorial/ |
| Content Cluster | Azure DevOps, Infrastructure as Code & Automation |
| Recommended Internal Links | Link contextually to the Azure pillar and adjacent Azure tutorials where the reader benefits. |