https://github.com/zevolution/az-login-automation
https://github.com/zevolution/az-login-automation
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/zevolution/az-login-automation
- Owner: zevolution
- Created: 2025-09-24T08:25:53.000Z (3 months ago)
- Default Branch: main
- Last Pushed: 2025-09-24T08:37:43.000Z (3 months ago)
- Last Synced: 2025-09-24T10:32:44.515Z (3 months ago)
- Language: Shell
- Size: 3.91 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
Azure Device Code Login Automation
[](https://opensource.org/licenses/MIT)
[](https://www.gnu.org/software/bash/)
[]()
[](https://github.com/zevolution/az-login-automation/pulls)
*Streamline your Azure CLI authentication with automatic device code handling and tenant selection*
[Features](#features) β’ [Installation](#installation) β’ [Usage](#usage) β’ [Configuration](#οΈconfiguration)
---
## π Table of Contents
- [About](#about)
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Usage](#usage)
- [Configuration](#οΈconfiguration)
- [Improve usability with Raycast](#improve-usability-with-raycast)
- [How It Works](#how-it-works)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
---
## π― About
The **Azure Device Code Login Automation** script transforms the Azure CLI device code authentication experience from a manual, multi-step process into a seamless, automated workflow.
Instead of manually copying device codes, opening browsers, and selecting tenants every time, this script:
- β
Automatically extracts and copies device codes to your clipboard
- β
Opens Firefox with your specified container directly to the login page
- β
Auto-selects your preferred tenant/subscription
- β
Provides clean, informative output
**Perfect for developers, DevOps engineers, and Azure administrators who authenticate frequently.**
---
## β¨ Features
### π **Automated Workflow**
- **Device Code Extraction**: Automatically detects and copies Azure device codes
- **Browser Integration**: Opens Firefox with specified container directly to login page
- **Tenant Auto-Selection**: Pre-configures your preferred tenant/subscription choice
### ποΈ **Flexible Usage Modes**
- **Automatic Mode**: `az-device-login 5` - Silent execution with auto-selection
- **Interactive Mode**: `az-device-login` - Full visibility with manual selection
### π§ **Easy Configuration**
- **Configurable Container**: Easily change Firefox container name
- **Parameterized Selection**: Pass tenant choice as command argument
- **Environment Detection**: Auto-detects available system utilities
---
## π Prerequisites
### Required
- **Azure CLI** (`az`) - [Install Guide](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli)
- **Expect** - Process automation tool
- **Firefox** with Container support (for automatic browser opening)
### Install Expect
```bash
# macOS
brew install expect
# Ubuntu/Debian
sudo apt-get install expect
# CentOS/RHEL
sudo yum install expect
```
### Clipboard Support (Auto-detected)
- **macOS**: `pbcopy` (built-in)
- **Linux**: `xclip` or `xsel`
- **Windows/WSL**: `clip.exe`
### Mozilla Firefox
- **Firefox Browser**: https://www.firefox.com/en-US/
- **Multi-Account Container Extension**: [[Github](https://github.com/mozilla/multi-account-containers)] [[Mozilla Add-Ons](https://addons.mozilla.org/en-US/firefox/addon/multi-account-containers/)] - This extension derives from the concept in Firefox called "[Contextual Identities](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities)" which assumes that users browsing the surface web can have more than one identity.
- **Open external links in a container**: [[Github](https://github.com/honsiorovskyi/open-url-in-container)] [[Mozilla Add-Ons](https://addons.mozilla.org/en-US/firefox/addon/open-url-in-container)] - This guy works with "[protocol_handlers](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers)" that is the main responsible by knows how to handle particular types of links like "magnet:" used by apps like BitTorrent or even "mailto:" used by email clients. In this particular case they allow-us to use URL to call "ext+container:name=ContainerName", translating in a command to open the desired container(or also use terminal firefox-container CLI)
---
## π Installation
### Method 1: Direct Download
```bash
# Download the script
curl -O https://raw.githubusercontent.com/yourusername/azure-device-login/main/az-device-login.sh
# Make executable
chmod +x az-device-login.sh
# Move to PATH (optional)
sudo mv az-device-login.sh /usr/local/bin/az-device-login
```
### Method 2: Git Clone
```bash
# Clone repository
git clone https://github.com/yourusername/azure-device-login.git
cd azure-device-login
# Make executable
chmod +x az-device-login.sh
# Create symlink (optional)
sudo ln -s "$(pwd)/az-device-login.sh" /usr/local/bin/az-device-login
```
---
## π» Usage
### Basic Usage
#### Automatic Mode (Recommended)
```bash
# Auto-select tenant/subscription option 5
az-device-login 5
```
**Output:**
```
Starting Azure device code authentication...
[SCRIPT] Device code detected: ABC123DEF
[SCRIPT] β Device code copied to clipboard!
[SCRIPT] Opening Firefox container...
[SCRIPT] Firefox opened at: https://microsoft.com/devicelogin
[SCRIPT] Will auto-select option [5] after authentication...
[SCRIPT] Auto-selecting option: [5]
[SCRIPT] β Login completed successfully!
```
#### Interactive Mode
```bash
# Full manual control
az-device-login
```
**Output:**
```
Starting Azure device code authentication...
[SCRIPT] Device code detected: ABC123DEF
[SCRIPT] β Device code copied to clipboard!
[SCRIPT] Opening Firefox container...
[SCRIPT] Firefox opened at: https://microsoft.com/devicelogin
[Shows full tenant selection table for manual choice]
[SCRIPT] β Login completed successfully!
```
### Demonstration
*GIF demonstration under construction: coming soon! ...* π§π οΈ

---
## βοΈ Configuration
### Main Variables
Edit the following variables based on your environment
```bash
# This variables is in begin of scripts.sh
# This guy is responsible to store a int with index value of list return by az-login
TENANT_CHOICE=
# This guy is responsible to store your Mozila Multi-Account Container name
FIREFOX_CONTAINER_NAME=
# This guy is responsible to store the path where your Mozilla Firefox is installed (just folder)
FIREFOX_BIN_PATH=
```
---
## π Improve usability with Raycast
### What is Raycast?
[Raycast](https://www.raycast.com) is a blazingly fast, extensible launcher and productivity tool for macOS that replaces Spotlight. It provides a clean, powerful interface to search applications, files, and execute custom commands with lightning speed.
Key Raycast features:
- **β‘ Lightning Fast**: Instant search and command execution
- **π§ Extensible**: Rich ecosystem of extensions and custom scripts
- **β¨οΈ Keyboard-First**: Navigate everything without touching your mouse
- **π¨ Beautiful UI**: Clean, modern interface that feels native to macOS
- **π€ Smart**: AI-powered features and contextual actions
### Raycast Script Commands
Raycast Script Commands allow you to turn any script into a searchable, executable command within Raycast. Instead of opening Terminal and typing commands, you can:
- **Search and Execute**: Type command name in Raycast launcher
- **Pass Parameters**: Interactive forms for script arguments
- **Quick Access**: Assign hotkeys for instant execution
- **Rich Feedback**: Proper success/error handling with notifications
### Workflow Comparison
#### Traditional Terminal Approach
```bash
# Multiple steps, context switching, terminal opening
cd ~/scripts
./az-device-login.sh 5
# Switch to browser, paste code, return to terminal
```
#### Raycast Integration Approach
β₯ + Space β Find Script β Enter Tenant β β¨ Done
Alternative
Custom Keyboard Shortcut β β¨ Done
### Benefits & Tradeoffs
#### β
**Benefits**
- **π₯ Speed**: Instant access without opening Terminal
- **π― Focus**: Stay in your current workflow
- **π Visual Feedback**: Rich notifications and status updates
- **β¨οΈ Keyboard-Driven**: Never touch your mouse
- **π Consistent**: Same interface for all your automation scripts
- **π± Modern UX**: Native macOS experience
#### β οΈ **Tradeoffs**
- **π macOS Only**: Raycast is exclusively for macOS users
- **πΎ Memory Usage**: Additional app running in background
- **π§ Setup Overhead**: Initial configuration required
- **π Dependency**: Adds another tool to your workflow stack
- **π° Premium Features**: Some advanced features require Raycast Pro
#### **Recommendation**
Perfect for **macOS developers** who value speed and elegant UX. If you're already using Spotlight frequently, Raycast + this script integration will significantly improve your Azure authentication workflow.
*GIF demonstration under construction: coming soon! ...* π§π οΈ

---
## π§ How It Works
### Architecture Overview
Click here to expand full architecture diagram
```mermaid
graph TD
%% Main Entry Point
User[π€ User] --> Script[π Main Script
az-device-login.sh]
%% Initial Setup and Validation
Script --> Validate{β
Validate Prerequisites}
Validate -->|β Missing| Error1[β Exit: Install missing tools]
Validate -->|β
Valid| Setup[π§ Setup Signal Handlers
& Temp Files]
%% Parameter Processing
Setup --> Param{π Parameter Provided?}
Param -->|Yes| Auto[π€ Automatic Mode
TENANT_CHOICE = N]
Param -->|No| Interactive[ποΈ Interactive Mode
TENANT_CHOICE = ""]
%% Expect Script Generation
Auto --> ExpectGen[π Generate Expect Script]
Interactive --> ExpectGen
%% Core Expect Process
ExpectGen --> Expect[π― Expect Script
Process Controller]
Expect --> Spawn[ποΈ spawn az login --use-device-code]
%% Device Code Detection Phase
Spawn --> Monitor{ποΈ Monitor Output}
Monitor -->|Device Code Found| Extract[π€ Extract Device Code
Copy to Clipboard]
Monitor -->|Timeout| Timeout[β±οΈ Timeout Handler
Switch to Manual]
%% Browser Integration
Extract --> Browser[π¦ Open Firefox Container
https://microsoft.com/devicelogin]
%% User Authentication
Browser --> UserAuth[π User Pastes Code
& Authenticates]
%% Tenant Selection Phase
UserAuth --> TenantPrompt{π’ Tenant Selection Prompt}
%% Auto vs Manual Selection
TenantPrompt -->|Auto Mode| AutoSelect[π€ Auto-select Tenant
send TENANT_CHOICE]
TenantPrompt -->|Interactive Mode| ManualSelect[π€ User Manual Selection
interact mode]
%% Completion Handling
AutoSelect --> Complete[β
Login Complete
JSON Response]
ManualSelect --> Complete
Timeout --> ManualSelect
%% Cleanup and Exit
Complete --> Cleanup[π§Ή Cleanup Temp Files]
Cleanup --> Success[π Success Message
Exit 0]
%% Error Handling
Error1 --> Exit[πͺ Script Exit]
%% Signal Handling (CTRL+C)
Script -.->|SIGINT| SigMain[π Main Script Cleanup]
Expect -.->|SIGINT| SigExpect[π Expect Script Cleanup]
ManualSelect -.->|CTRL+C| SigInteract[π Interactive Cleanup]
SigMain --> ForceExit[π₯ Force Exit 130]
SigExpected --> ForceExit
SigInteract --> ForceExit
%% Styling
classDef userAction fill:#e1f5fe,stroke:#01579b,stroke-width:2px
classDef processStep fill:#f3e5f5,stroke:#4a148c,stroke-width:2px
classDef decision fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef success fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px
classDef error fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef signal fill:#fce4ec,stroke:#880e4f,stroke-width:2px,stroke-dasharray: 5 5
class User,UserAuth,ManualSelect userAction
class Script,Setup,ExpectGen,Expect,Spawn,Extract,Browser,AutoSelect,Complete,Cleanup processStep
class Validate,Param,Monitor,TenantPrompt decision
class Success success
class Error1,Timeout,ForceExit error
class SigMain,SigExpect,SigInteract signal
```
### Execution Flow
1. **Initialization**
- Validates prerequisites (Azure CLI, expect)
- Sets up signal handlers for cleanup
- Creates temporary files
2. **Device Code Phase**
- Spawns `az login --use-device-code`
- Monitors output for device code patterns
- Extracts code and copies to clipboard
- Opens Firefox with container
3. **Authentication Phase**
- User pastes code in browser
- Completes authentication flow
- Script waits for tenant selection prompt
4. **Selection Phase**
- **Automatic**: Sends predetermined choice
- **Interactive**: Hands control to user
- Processes selection and completes login
5. **Completion**
- Cleans up temporary files
- Reports success/failure status
- Returns control to shell
### Signal Handling
The script implements 3-level SIGINT handling:
- **Main Script Level**: Cleans temporary files
- **Expect Script Level**: Proper process termination
- **Interactive Level**: User can cancel during tenant selection
---
## π Troubleshooting
### Common Issues
#### `expect: command not found`
```bash
# Install expect
brew install expect # macOS
sudo apt-get install expect # Ubuntu/Debian
sudo yum install expect # CentOS/RHEL
```
#### `az: command not found`
```bash
# Install Azure CLI
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash # Linux
brew install azure-cli # macOS
```
#### `Firefox doesn't open`
- Verify Firefox is installed correcly, e.g., `/Applications/Firefox.app/Contents/MacOS/firefox`
- Check if the specified container exists in Firefox
- Ensure Firefox Multi-Account Container and OpenExternal Links extension is installed
#### `Device code not detected`
- Check if the pattern matches your Azure CLI output
- Verify expect script has proper permissions
- Try running in interactive mode first
#### `Clipboard not working`
```bash
# Install clipboard utilities
sudo apt-get install xclip # Linux
sudo apt-get install xsel # Linux alternative
```
---
## π€ Contributing
Under construction: coming soon! ... π§π οΈ

---
## π License
This project is licensed under the MIT License - see the [LICENSE](https://choosealicense.com/licenses/mit/) file for details.
```
MIT License
Copyright (c) 2025 zevolution
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
---
## π Acknowledgments
- **Azure CLI Team** - For providing the device code authentication flow
- **Expect Contributors** - For the powerful process automation tool
- **Community** - For future feedbacks and suggestions that'll shape this tool
---
_β Star this repository if it helped you!_
[Report Bug](https://github.com/zevolution/az-login-automation/issues) β’ [Request Feature](https://github.com/zevolution/az-login-automation/discussions/categories/ideas) β’ [Discussions](https://github.com/zevolution/az-login-automation/discussions/categories/q-a)
---