|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +tenant="" |
| 4 | +help="Usage: az-sub-init.sh [--tenant your-tenant.onmicrosoft.com] [--help] |
| 5 | +
|
| 6 | +Attempts to set the ARM_SUBSCRIPTION_ID env var to 'id' from 'az account show' in the following ways: |
| 7 | +- 'az login' if not logged in (optionally with specific tenant) |
| 8 | +- 'az account show -o tsv --query id' for the current logged in account |
| 9 | +
|
| 10 | +Needed for Terraform |
| 11 | +
|
| 12 | +Current ARM_SUBSCRIPTION_ID: ${ARM_SUBSCRIPTION_ID}" |
| 13 | + |
| 14 | +while [[ $# -gt 0 ]]; do |
| 15 | + case $1 in |
| 16 | + --tenant) |
| 17 | + tenant="$2" |
| 18 | + shift 2 |
| 19 | + ;; |
| 20 | + --help) |
| 21 | + echo "${help}" |
| 22 | + exit 0 |
| 23 | + ;; |
| 24 | + *) |
| 25 | + echo "${help}" |
| 26 | + echo |
| 27 | + echo "Unknown option: $1" |
| 28 | + exit 1 |
| 29 | + ;; |
| 30 | + esac |
| 31 | +done |
| 32 | + |
| 33 | +get_current_subscription_id() { |
| 34 | + az account show -o tsv --query "id" 2>/dev/null |
| 35 | +} |
| 36 | + |
| 37 | +is_correct_tenant() { |
| 38 | + if [[ -z "${tenant}" ]]; then |
| 39 | + return 0 # No specific tenant required |
| 40 | + fi |
| 41 | + |
| 42 | + local current_tenant |
| 43 | + current_tenant=$(az rest --method get --url https://graph.microsoft.com/v1.0/domains \ |
| 44 | + --query 'value[?isDefault].id' -o tsv 2>/dev/null || echo "") |
| 45 | + |
| 46 | + [[ "${tenant}" == "${current_tenant}" ]] |
| 47 | +} |
| 48 | + |
| 49 | +login_to_azure() { |
| 50 | + echo "Logging into Azure..." |
| 51 | + if [[ -n "${tenant}" ]]; then |
| 52 | + if ! az login --tenant "${tenant}"; then |
| 53 | + echo "Error: Failed to login to Azure with tenant ${tenant}" |
| 54 | + exit 1 |
| 55 | + fi |
| 56 | + else |
| 57 | + if ! az login; then |
| 58 | + echo "Error: Failed to login to Azure" |
| 59 | + exit 1 |
| 60 | + fi |
| 61 | + fi |
| 62 | +} |
| 63 | + |
| 64 | +current_subscription_id=$(get_current_subscription_id) |
| 65 | + |
| 66 | +if [[ -z "${current_subscription_id}" ]] || ! is_correct_tenant; then |
| 67 | + login_to_azure |
| 68 | + |
| 69 | + current_subscription_id=$(get_current_subscription_id) |
| 70 | + if [[ -z "${current_subscription_id}" ]]; then |
| 71 | + echo "Error: Login succeeded but could not retrieve subscription ID" |
| 72 | + exit 1 |
| 73 | + fi |
| 74 | +fi |
| 75 | + |
| 76 | +export ARM_SUBSCRIPTION_ID="${current_subscription_id}" |
| 77 | +echo "ARM_SUBSCRIPTION_ID set to: ${ARM_SUBSCRIPTION_ID}" |
0 commit comments