azure

package
v1.210.0-test.31 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DirPermissions is the permission mode for Azure cache directories (owner read/write/execute only).
	DirPermissions = 0o700
	// FilePermissions is the permission mode for Azure credential files (owner read/write only).
	FilePermissions = 0o600
)

File permissions.

View Source
const (
	// BomMarker is the first byte of UTF-8 BOM.
	BomMarker = 0xEF
	// BomSecondByte is the second byte of UTF-8 BOM.
	BomSecondByte = 0xBB
	// BomThirdByte is the third byte of UTF-8 BOM.
	BomThirdByte = 0xBF
)

BOM (Byte Order Mark) constants for UTF-8.

View Source
const (
	FieldHomeAccountID = "home_account_id"
	FieldEnvironment   = "environment"
	FieldRealm         = "realm"
	FieldUsername      = "username"
	FieldLocalID       = "local_account_id"
	FieldAccessToken   = "AccessToken"
	FieldUser          = "user"
)

MSAL cache field names used in azureProfile.json and MSAL cache. Exported for use by device_code_cache.go.

View Source
const (
	IntFormat      = "%d" // Format string for integer output.
	StrconvDecimal = 10   // Decimal base for string conversion.
	Int64BitSize   = 64   // Bit size for int64 conversion.
)

String format and conversion constants.

View Source
const (
	LogFieldIdentity     = "identity"     // Log field for identity name.
	LogFieldSubscription = "subscription" // Log field for subscription ID.
	LogFieldTenantID     = "tenantID"     // Log field for tenant ID.
	LogFieldExpiresOn    = "expiresOn"    // Log field for token expiration.
	LogFieldKey          = "key"          // Log field for cache key.
)

Logging field names.

View Source
const (
	PermissionRWX = 0o700
	PermissionRW  = 0o600
)
View Source
const (
	// AzureDefaultSessionDuration is the default session duration (Azure tokens are typically valid for 1 hour).
	AzureDefaultSessionDuration = 1 * time.Hour
)

Variables

View Source
var (
	ErrGetHomeDir                    = errors.New("failed to get home directory")
	ErrCreateCredentialsFile         = errors.New("failed to create credentials file")
	ErrLoadCredentialsFile           = errors.New("failed to load credentials file")
	ErrWriteCredentialsFile          = errors.New("failed to write credentials file")
	ErrSetCredentialsFilePermissions = errors.New("failed to set credentials file permissions")
	ErrCleanupAzureFiles             = errors.New("failed to cleanup Azure files")
	ErrFileLockTimeout               = errors.New("failed to acquire file lock within timeout")
	ErrRemoveProfile                 = errors.New("failed to remove profile")
)
View Source
var AzurePortalURL = PublicCloud.PortalURL

AzurePortalURL returns the Azure Portal base URL for the public cloud. For sovereign clouds, use GetCloudEnvironment(name).PortalURL instead.

View Source
var PublicCloud = cloudEnvironments["public"]

PublicCloud is the default Azure public cloud environment.

Functions

func AcquireFileLock

func AcquireFileLock(lockPath string) (*flock.Flock, error)

AcquireFileLock attempts to acquire an exclusive file lock with timeout and retries. Exported for use by provider-side code (device_code_cache.go).

func KnownCloudEnvironments added in v1.210.0

func KnownCloudEnvironments() []string

KnownCloudEnvironments returns the names of all known cloud environments.

func NewMSALCache

func NewMSALCache(cachePath string, realm string) (cache.ExportReplace, error)

NewMSALCache creates a new MSAL cache instance. If cachePath is empty, uses the default Azure CLI location (~/.azure/atmos/{realm}/msal_token_cache.json). The realm parameter provides credential isolation between different repositories.

func PrepareEnvironment

func PrepareEnvironment(cfg PrepareEnvironmentConfig) map[string]string

PrepareEnvironment configures environment variables for Azure SDK when using Atmos auth.

This function:

  1. Clears direct Azure credential env vars to prevent conflicts with Atmos-managed credentials
  2. Sets AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_LOCATION
  3. Sets ARM_* variables for Terraform provider compatibility
  4. Sets ARM_USE_CLI=true (for CLI/device-code auth) or ARM_USE_OIDC=true (for OIDC auth)

For OIDC authentication (service principal with federated credentials), it sets:

  • ARM_USE_OIDC=true
  • ARM_CLIENT_ID
  • AZURE_FEDERATED_TOKEN_FILE (if token file path is provided)

For CLI/device-code authentication, it sets ARM_USE_CLI=true which tells Terraform to use the MSAL cache populated by Atmos.

Note: Other cloud provider credentials (AWS, GCP) are NOT cleared to support multi-cloud scenarios such as using S3 backend for Terraform state while deploying to Azure.

Returns a NEW map with modifications - does not mutate the input.

func ResolveDestination

func ResolveDestination(dest string, azureCreds *types.AzureCredentials) (string, error)

ResolveDestination resolves destination aliases to full Azure Portal URLs.

Supports the following destination formats:

  • Empty string or "home" → Tenant home page
  • "subscription" → Subscription overview
  • "resourcegroups" or "rg" → Resource groups blade
  • "vm" or "virtualmachines" → Virtual Machines blade
  • "storage" or "storageaccounts" → Storage Accounts blade
  • "network" or "vnet" → Virtual Networks blade
  • "cosmosdb" → Cosmos DB blade
  • "sql" → SQL Databases blade
  • "keyvault" → Key Vaults blade
  • "monitor" → Azure Monitor blade
  • Full URL starting with https:// → Pass through unchanged

All resolved URLs include tenant context for proper navigation.

func SetAuthContext

func SetAuthContext(params *SetAuthContextParams) error

SetAuthContext populates the Azure auth context with Atmos-managed credential paths. This enables in-process Azure SDK calls to use Atmos-managed credentials.

func SetEnvironmentVariables

func SetEnvironmentVariables(authContext *schema.AuthContext, stackInfo *schema.ConfigAndStacksInfo) error

SetEnvironmentVariables derives Azure environment variables from AuthContext. This populates ComponentEnvSection/ComponentEnvList for spawned processes. The auth context is the single source of truth; this function derives from it.

Uses PrepareEnvironment helper to ensure consistent environment setup across all commands. This clears conflicting credential env vars and sets Azure subscription/tenant/location.

Parameters:

  • authContext: Runtime auth context containing Azure credentials
  • stackInfo: Stack configuration to populate with environment variables

func SetupFiles

func SetupFiles(providerName, identityName string, creds types.ICredentials, basePath string, realm string) error

SetupFiles sets up Azure credentials files for the given identity. BasePath specifies the base directory for Azure files (from provider's files.base_path). If empty, uses the default ~/.azure/atmos/{realm} path. The realm parameter provides credential isolation between different repositories.

func UpdateAzureCLIFiles

func UpdateAzureCLIFiles(creds types.ICredentials, tenantID, subscriptionID, cloudEnvName string) error

UpdateAzureCLIFiles updates Azure CLI files (MSAL cache and azureProfile.json) so Terraform providers can use them. This makes Atmos authentication work exactly like `az login`. This should be called from PostAuthenticate to ensure CLI compatibility. The cloudEnvName selects the Azure cloud environment ("public", "usgovernment", "china"). If empty, defaults to "public".

func UpdateSubscriptionsInProfile

func UpdateSubscriptionsInProfile(profile map[string]interface{}, params ProfileUpdateParams) []interface{}

UpdateSubscriptionsInProfile updates the subscriptions array in an Azure profile. It sets the specified subscription as default and marks all others as not default.

func ValidateCloudEnvironment added in v1.210.0

func ValidateCloudEnvironment(name string) error

ValidateCloudEnvironment validates that a cloud environment name is known. Empty string is valid (defaults to "public"). Unknown non-empty values return an error.

Types

type AzureFileManager

type AzureFileManager struct {
	// contains filtered or unexported fields
}

AzureFileManager provides helpers to manage Azure credentials files.

func NewAzureFileManager

func NewAzureFileManager(basePath string, realm string) (*AzureFileManager, error)

NewAzureFileManager creates a new Azure file manager. If basePath is empty, uses default ~/.azure/atmos/{realm} path. The realm parameter provides credential isolation between different repositories.

func (*AzureFileManager) Cleanup

func (m *AzureFileManager) Cleanup(providerName string) error

Cleanup removes Azure files for the given provider.

func (*AzureFileManager) CredentialsExist

func (m *AzureFileManager) CredentialsExist(providerName string) bool

CredentialsExist checks if credentials file exists for the given provider.

func (*AzureFileManager) GetCredentialsPath

func (m *AzureFileManager) GetCredentialsPath(providerName string) string

GetCredentialsPath returns the path to the credentials file for the given provider.

func (*AzureFileManager) LoadCredentials

func (m *AzureFileManager) LoadCredentials(providerName string) (*types.AzureCredentials, error)

LoadCredentials loads Azure credentials from a JSON file.

func (*AzureFileManager) WriteCredentials

func (m *AzureFileManager) WriteCredentials(providerName, identityName string, creds *types.AzureCredentials) error

WriteCredentials writes Azure credentials to a JSON file.

type CloudEnvironment added in v1.210.0

type CloudEnvironment struct {
	// Name is the canonical name of the cloud environment.
	Name string
	// LoginEndpoint is the Azure AD / Entra ID authority host (e.g., "login.microsoftonline.com").
	LoginEndpoint string
	// ManagementScope is the Azure Resource Manager API scope.
	ManagementScope string
	// GraphAPIScope is the Microsoft Graph API scope.
	GraphAPIScope string
	// KeyVaultScope is the Azure KeyVault API scope.
	KeyVaultScope string
	// BlobStorageSuffix is the blob storage URL suffix (e.g., "blob.core.windows.net").
	BlobStorageSuffix string
	// PortalURL is the Azure Portal base URL.
	PortalURL string
	// AzureProfileEnvName is the environment name used in azureProfile.json (e.g., "AzureCloud").
	AzureProfileEnvName string
}

CloudEnvironment defines the endpoints for a specific Azure cloud (public, government, China).

func GetCloudEnvironment added in v1.210.0

func GetCloudEnvironment(name string) *CloudEnvironment

GetCloudEnvironment returns the endpoint set for the given cloud name. Returns the "public" environment if name is empty. Unknown non-empty values are rejected by ValidateCloudEnvironment before calling this function.

type ConsoleURLGenerator

type ConsoleURLGenerator struct{}

ConsoleURLGenerator generates Azure Portal URLs with authentication context.

func NewConsoleURLGenerator

func NewConsoleURLGenerator() *ConsoleURLGenerator

NewConsoleURLGenerator creates a new ConsoleURLGenerator.

func (*ConsoleURLGenerator) GetConsoleURL

GetConsoleURL generates an Azure Portal sign-in URL with authentication context.

Azure Portal URLs support deep linking with tenant context:

Unlike AWS federation (which requires a signin token), Azure Portal authentication uses browser-based OAuth with the same credentials used to access Azure APIs. The Portal will automatically pick up the user's authenticated session.

References:

func (*ConsoleURLGenerator) SupportsConsoleAccess

func (g *ConsoleURLGenerator) SupportsConsoleAccess() bool

SupportsConsoleAccess returns true (Azure Console URL generator supports console access).

type PrepareEnvironmentConfig

type PrepareEnvironmentConfig struct {
	Environ          map[string]string // Current environment variables
	SubscriptionID   string            // Azure subscription ID
	TenantID         string            // Azure tenant ID
	Location         string            // Azure location/region (optional)
	CloudEnvironment string            // Azure cloud environment name ("public", "usgovernment", "china")
	// OIDC-specific configuration for Terraform ARM_USE_OIDC support.
	UseOIDC       bool   // Use OIDC instead of CLI authentication
	ClientID      string // Azure AD application (client) ID
	TokenFilePath string // Path to OIDC token file (optional)
}

PrepareEnvironmentConfig holds configuration for Azure environment preparation.

type ProfileUpdateParams added in v1.210.0

type ProfileUpdateParams struct {
	Username            string
	TenantID            string
	SubscriptionID      string
	IsServicePrincipal  bool
	AzureProfileEnvName string
}

ProfileUpdateParams contains the parameters for updating an Azure profile subscription entry.

type SetAuthContextParams

type SetAuthContextParams struct {
	AuthContext  *schema.AuthContext
	StackInfo    *schema.ConfigAndStacksInfo
	ProviderName string
	IdentityName string
	Credentials  types.ICredentials
	BasePath     string
	Realm        string
}

SetAuthContextParams contains parameters for SetAuthContext.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL