0
votes

I have a Python script I want to run in Azure Resource Manager context within an Azure DevOps pipeline task to be able to access Azure resources (like the Azure CLI or Azure PowerShell tasks).

How can I get Azure RM Service Endpoint credentials stored in Azure DevOps passed - as ServicePrincipal/Secret or OAuth Token - into the script?

2

2 Answers

0
votes

Depends on what you call a python script, but either way Azure DevOps hasn't got native support to authenticate python sdk (or your custom python script), but you can pass in credentials from build\release variables to your script, or try and pull that from the Azure Cli (I think it stores data somewhere under /home/.azure/.

0
votes

based on the hint given by 4c74356b41 above and with some dissecting of Azure CLI I created this function that allows pulling an OAuth token over ADAL from the Service Princial logged in inside an Azure DevOps - Azure CLI task

import os
import json
import adal

_SERVICE_PRINCIPAL_ID = 'servicePrincipalId'
_SERVICE_PRINCIPAL_TENANT = 'servicePrincipalTenant'
_TOKEN_ENTRY_TOKEN_TYPE = 'tokenType'
_ACCESS_TOKEN = 'accessToken'

def get_config_dir():
    return os.getenv('AZURE_CONFIG_DIR', None) or os.path.expanduser(os.path.join('~', '.azure'))

def getOAuthTokenFromCLI():
    token_file = (os.environ.get('AZURE_ACCESS_TOKEN_FILE', None)
              or os.path.join(get_config_dir(), 'accessTokens.json'))

    with open(token_file) as f:
        tokenEntry = json.load(f)[0] # just assume first entry

    tenantID = tokenEntry[_SERVICE_PRINCIPAL_TENANT]
    appId = tokenEntry[_SERVICE_PRINCIPAL_ID]
    appPassword = tokenEntry[_ACCESS_TOKEN]
    authURL = "https://login.windows.net/" + tenantID
    resource = "https://management.azure.com/"
    context = adal.AuthenticationContext(authURL, validate_authority=tenantID, api_version=None)
    token = context.acquire_token_with_client_credentials(resource,appId,appPassword)
    return token[_TOKEN_ENTRY_TOKEN_TYPE] + " " + token[_ACCESS_TOKEN]