0

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.

1 Answer 1

0

first : store the PAT in Azure Key Vault

create a secret in your Key Vault containing your GitHub PAT : for exemple the secrets name : github-token

second : grant your Function App access to the Key Vault
Make sure your Function App has a managed identity enabled.

give it the role "Key Vault Secret User"

Inject the secret as an environment variable
In your Function App configure an application setting referencing the Key Vault secret, for example:

in you're application_settings.txt :

[email protected](SecretUri=https://{KV_NAME}.vault.azure.net/secrets/github-token/)

Azure will automatically inject the secret value into the GITHUB_TOKEN environment variable when the container starts.

In your code

import os
import subprocess

token = os.environ.get("GITHUB_TOKEN")

process = subprocess.run(
    ['gh', 'auth', 'login', '--with-token'],
    input=token.encode(),  # en bytes
    capture_output=True
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.