I've setup a custom container in Azure that will run a Function App, with the intention of connecting to my organisations GitHub (GHE) instance and using GH CLI pull a list of repos.
I have a PAT token that I can test locally, and get expected results. However, when attempting to connect from within the application, I'm hit with this error:
{"EventType":"MS_FUNCTION_AZURE_MONITOR_EVENT","Level":4,"ResourceId":"ca-dev-github-repos.xxxxxxxxxxxx-xxxxxxxxxxxx.uksouth.azurecontainerapps.io","OperationName":"Microsoft.Web/sites/functions/log","Category":"FunctionAppLogs","RegionName":"","Properties":"\"{'appName':'ca-dev-github-repos','roleInstance':'','message':'Debug - authentication Check\\nCompletedProcess(args=[gh, api, user], returncode=1, stdout={\\'message\\':\\'Bad credentials\\',\\'documentation_url\\':\\'https://docs.github.com/rest\\',\\'status\\':\\'401\\'}, stderr=gh: Bad credentials (HTTP 401)\\\\n)\\n','category':'Function.function_app.User','hostVersion':'4.1040.300.7','functionInvocationId':'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx','functionName':'function_app','hostInstanceId':'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx','level':'Information','levelId':2,'processId':9}\""}
This is my Python code focusing on authentication:
def get_github_token():
KeyvaultName = os.getenv("KEY_VAULT_NAME")
if not KeyvaultName:
raise ValueError("KEY_VAULT_NAME environment variable is not set.")
Keyvault_url = f"https://{KeyvaultName}.vault.azure.net"
credential = DefaultAzureCredential()
client = SecretClient(vault_url=Keyvault_url, credential=credential)
secret_name = os.getenv("GITHUB_TOKEN_SECRET_NAME", "GitHub-PAT")
secret = client.get_secret(secret_name)
return secret.value
def main():
# Get the GH PAT token
github_token = get_github_token()
# Validate the token length
if not github_token or len(github_token.strip()) < 93:
raise ValueError("GitHub PAT token is missing or appears invalid.")
# Set token in environment variable
os.environ["GH_TOKEN"] = github_token
# Ensure the GitHub CLI is installed and the path is set
gh_check = subprocess.run(["which", "gh"], capture_output=True, text=True)
if gh_check.returncode != 0:
raise EnvironmentError("GitHub CLI (gh) is not installed or not in PATH.")
# Check that the token has access to the GH organization.
auth_check = subprocess.run(
["gh", "api", "user"], capture_output=True, text=True
)
print("Debug - authentication Check")
print(auth_check)
if auth_check.returncode != 0:
raise RuntimeError("GitHub CLI authentication failed.")
Any assistance is gratefully received.