如何通过Python代码监控Azure Automation Python Runbook作业状态?
Azure Automation Python Runbook作业元数据获取与告警实现
为什么os.environ.get无法获取元数据
Azure Automation的Python Runbook执行环境默认不暴露作业相关的环境变量,只有PowerShell Runbook才有AZURE_SUBSCRIPTION_ID、AUTOMATION_JOB_ID这类内置环境变量,因此你用os.environ.get会返回None。
解决方案
1. Runbook执行期间获取元数据并生成告警
可以通过Azure Automation管理SDK,结合托管身份(MSI)认证,在Runbook内部调用API获取当前作业的元数据。
前置准备
- 给自动化账户的系统分配托管身份,添加
Automation Operator或Automation Contributor角色(权限需覆盖作业信息读取)。 - 在自动化账户的Python包中添加
azure-mgmt-automation和azure-identity(可通过自动化账户的“Python包”功能导入)。
代码示例
from azure.identity import ManagedIdentityCredential from azure.mgmt.automation import AutomationClient from datetime import datetime # 配置自动化账户基础信息 SUBSCRIPTION_ID = "你的订阅ID" RESOURCE_GROUP = "你的资源组名" AUTOMATION_ACCOUNT = "你的自动化账户名" RUNBOOK_NAME = "你的Runbook名称" # 初始化认证客户端与Automation管理客户端 credential = ManagedIdentityCredential() automation_client = AutomationClient(credential, SUBSCRIPTION_ID) # 查询当前Runbook的最新作业(即正在执行的作业) jobs = automation_client.job.list_by_automation_account( RESOURCE_GROUP, AUTOMATION_ACCOUNT, filter=f"runbookName eq '{RUNBOOK_NAME}'", orderby="creationTime desc" ) current_job = next(jobs) # 提取作业元数据 subscription = SUBSCRIPTION_ID automation_account = AUTOMATION_ACCOUNT runbook_name = current_job.runbook.name status = current_job.status job_id = current_job.job_id creation_time = current_job.creation_time.strftime("%Y-%m-%d %H:%M:%S") notification_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 捕获执行异常(如果需要) detail = "" try: # 这里写入你的Runbook业务逻辑 print("Runbook业务执行中...") # 示例:模拟错误 # raise Exception("测试错误") except Exception as e: detail = f"执行异常信息: {str(e)}" status = "Failed" # 手动更新状态为失败 # 生成指定格式的告警内容 alert_content = f"""Azure Automation Runbook Job Alert Subscription: {subscription} Automation account name: {automation_account} Runbook name: {runbook_name} Status: {status} Job ID: {job_id} CreationTime: {creation_time} Notification time: {notification_time} Detail: {detail} """ # 这里可添加告警发送逻辑(如Teams机器人、邮件、Azure Monitor告警) print(alert_content)
2. 执行后通过API/SDK获取元数据
如果需要在Runbook执行完成后触发告警(比如通过Azure Monitor规则),可以在告警动作(如逻辑应用、Azure函数)中调用Automation API获取作业详情:
- 使用
azure-mgmt-automationSDK调用get方法获取单个作业详情:job_detail = automation_client.job.get( RESOURCE_GROUP, AUTOMATION_ACCOUNT, job_id # 从告警触发信息中获取作业ID ) - 或直接调用REST API:
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobs/{jobId}?api-version=2023-11-01
内容的提问来源于stack exchange,提问作者soso rabih
相关产品推荐
相关产品推荐

