Connecting to Azure
The Azure CLI (Command-Line Interface) is a powerful tool for managing Azure resources. To begin interacting with your Azure subscription, you first need to connect to it.
Prerequisites
- Azure CLI installed on your local machine or cloud shell.
- An active Azure account.
Tip: If you don't have Azure CLI installed, visit the official Azure CLI installation guide.
Sign In to Azure
The most common way to connect is by signing in to your Azure account through the CLI. This opens a browser window for authentication.
Step 1: Open your terminal or command prompt.
Navigate to your preferred directory where you'll be working with Azure CLI commands.
Step 2: Run the login command.
Type the following command and press Enter:
az login
This command initiates the authentication process.
Step 3: Authenticate in the browser.
Your default web browser should open automatically, prompting you to sign in with your Azure credentials. Follow the on-screen instructions to complete the sign-in process.
If the browser doesn't open, the output will provide a URL to visit and a device code to enter.
If you cannot open a browser, use 'az login --use-device-code' to obtain a code to enter on a device.
Step 4: Verify your login.
Once authentication is successful, the CLI will display information about your Azure account, including your tenant ID and available subscriptions.
You can verify your active subscription using:
az account show
To see a list of all your subscriptions, use:
az account list --output table
If you have multiple Azure subscriptions, you can set a default one for your CLI sessions using: az account set --subscription <SUBSCRIPTION_ID_OR_NAME>
Service Principal Authentication
For automated scenarios, such as in CI/CD pipelines, you can use a service principal to authenticate.
Create a service principal (if you don't have one) and then use the following command:
az login --service-principal -u <app-id> -p <password-or-certificate> --tenant <tenant-id>
Replace <app-id>
, <password-or-certificate>
, and <tenant-id>
with your service principal's credentials.
Managed Identities
If you are running your code on an Azure service that supports managed identities (like Azure Virtual Machines, Azure App Services, Azure Functions), you can use them for authentication without managing credentials.
To enable managed identity for a resource, follow the specific documentation for that service. Once enabled, the Azure CLI can often automatically use it when running from that environment.
Troubleshooting
If you encounter issues, try the following:
- Ensure your Azure CLI is up to date:
az upgrade
- If prompted, clear cached credentials:
az cache purge
and then re-runaz login
. - Check your network connection and firewall settings.
For more advanced authentication methods and scenarios, refer to the official Azure CLI authentication documentation.