Я новичок в Azure, поэтому любая помощь бесполезна. спасибо
Я пытался использовать SDK в этой функции, но не могу подключиться к клостеру, получаю
Код: Выделить всё
DefaultAzureCredential acquired a token from EnvironmentCredential
[2024-09-20T03:41:52.511Z] C:\Users\Andres_Sanchez1\AppData\Roaming\Python\Python311\site-packages\urllib3\connectionpool.py:1061: InsecureRequestWarning: Unverified HTTPS request is being made to host 'abccall-demo-lgq05iz2.hcp.eastus.azmk8s.io'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
[2024-09-20T03:41:52.514Z] warnings.warn(
[2024-09-20T03:42:04.837Z] Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')': /api/v1/namespaces/eks_demo/pods
[2024-09-20T03:42:08.923Z] 401
[2024-09-20T03:42:08.923Z] Unexpected error: HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: /api/v1/namespaces/eks_demo/pods (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
[2024-09-20T03:42:08.928Z] {'kind': 'Status', 'apiVersion': 'v1', 'metadata': {}, 'status': 'Failure', 'message': 'Unauthorized', 'reason': 'Unauthorized', 'code': 401}
Код: Выделить всё
import logging
import os
import azure.functions as func
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from azure.identity import DefaultAzureCredential
import requests
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Processing a request to restart a Kubernetes pod using managed identity.')
# Get pod name and namespace from query parameters
pod_name = req.params.get('pod_name')
namespace = req.params.get('namespace', 'default')
if not pod_name:
return func.HttpResponse(
"Please pass a pod_name in the query string.",
status_code=400
)
try:
# Use ManagedIdentityCredential for managed identity authentication
credential = DefaultAzureCredential()
# Get the AKS API server endpoint from environment variables
aks_api_server = 'https://abccall-demo-lgq05iz2.hcp.eastus.azmk8s.io' # Set this in your Function App settings
if not aks_api_server:
return func.HttpResponse("AKS_API_SERVER environment variable is not set.", status_code=500)
# Get the access token
token = credential.get_token("https://management.azure.com/.default").token
# Create a Kubernetes API client configuration
configuration = client.Configuration()
configuration.host = aks_api_server
configuration.verify_ssl = False # Consider enabling SSL verification in production
configuration.api_key = {"authorization": f"Bearer {token}"}
response = requests.get(f"{aks_api_server}/api/v1/namespaces/default/pods", verify=False) # Change verify=True in production
print(response.status_code)
print(response.json())
# Create the Kubernetes API client
k8s_client = client.CoreV1Api(client.ApiClient(configuration))
v1 = client.CoreV1Api()
pods = v1.list_namespaced_pod(namespace)
for pod in pods.items:
print(f"Pod Name: {pod.metadata.name}")
# Delete the pod to trigger a restart
logging.info(f"Attempting to restart pod {pod_name} in namespace {namespace}.")
k8s_client.delete_namespaced_pod(pod_name, namespace, body=client.V1DeleteOptions())
return func.HttpResponse(
f"Pod {pod_name} in namespace {namespace} has been restarted.",
status_code=200
)
except ApiException as e:
logging.error(f"Exception when calling CoreV1Api->delete_namespaced_pod: {e}")
return func.HttpResponse(
f"Error: {str(e)}",
status_code=e.status
)
except Exception as e:
logging.error(f"Unexpected error: {e}")
return func.HttpResponse(
f"Error: {str(e)}",
status_code=500
)
Подробнее здесь: https://stackoverflow.com/questions/790 ... ion-script