Azure中部署Python脚本:获取VM列表及数量并推送至邮件/Slack
把本地Python脚本部署到Azure并发送结果到邮件/Slack的实操步骤
一、选对部署方案:Azure Functions(新手友好)
直接用Azure Functions,无服务器架构不用管服务器维护,按运行次数计费,完美适配这种定时/按需执行的脚本场景。
二、适配脚本到Azure环境
1. 调整VM列表脚本的认证逻辑
本地用的本地凭据在Azure上不好使,换成系统分配托管标识来做权限认证:
from azure.mgmt.compute import ComputeManagementClient from azure.identity import ManagedIdentityCredential def get_vm_stats(): # 用托管标识获取凭据 credential = ManagedIdentityCredential() # 替换成你的订阅ID subscription_id = "your-subscription-id" compute_client = ComputeManagementClient(credential, subscription_id) # 获取所有VM并统计 all_vms = list(compute_client.virtual_machines.list_all()) vm_count = len(all_vms) vm_name_list = [vm.name for vm in all_vms] return f"Azure VM统计结果:\n总数: {vm_count}\n列表:\n" + "\n".join(vm_name_list)
然后在Azure门户给你的函数应用分配虚拟机读取者角色到目标订阅,确保托管标识有权限读取VM信息。
2. 加邮件/Slack发送功能
发送邮件(用Azure Communication Services)
from azure.communication.email import EmailClient def send_vm_stats_email(content): # 替换成你的Azure Communication Services连接字符串 conn_str = "your-communication-services-conn-string" email_client = EmailClient.from_connection_string(conn_str) email_msg = { "senderAddress": "vm-alerts@your-domain.com", "recipients": {"to": [{"address": "your-target-email@example.com"}]}, "content": { "subject": "每日Azure VM统计", "plainText": content } } email_client.send(email_msg)
发送到Slack(用Incoming Webhook)
import requests def send_vm_stats_to_slack(content): # 替换成你的Slack Webhook URL slack_webhook = "your-slack-webhook-url" payload = {"text": content} requests.post(slack_webhook, json=payload)
三、部署到Azure Functions
本地准备:
- 装Azure Functions Core Tools和Azure CLI
- 初始化函数项目:
func init VmStatsFunc --python - 进入项目目录,创建定时器触发函数(比如每天中午12点运行):
func new --name DailyVmStats --template "Timer trigger" - 把你的逻辑整合到
__init__.py:import azure.functions as func import logging from .vm_stats import get_vm_stats, send_vm_stats_email, send_vm_stats_to_slack app = func.FunctionApp() @app.timer_trigger(schedule="0 0 12 * * *", arg_name="timer", run_on_startup=False) def DailyVmStats(timer: func.TimerRequest) -> None: logging.info("开始执行VM统计脚本") stats_content = get_vm_stats() logging.info(stats_content) # 选一种发送方式 send_vm_stats_email(stats_content) # send_vm_stats_to_slack(stats_content)
部署到Azure:
- 登录Azure CLI:
az login - 创建资源组:
az group create --name VmStatsRG --location eastus - 创建函数应用:
az functionapp create --resource-group VmStatsRG --consumption-plan-location eastus --runtime python --runtime-version 3.11 --functions-version 4 --name VmStatsFuncDemo --os-type linux - 部署代码:
func azure functionapp publish VmStatsFuncDemo
- 登录Azure CLI:
配置环境变量:
在Azure门户的函数应用「配置」里添加订阅ID、Communication Services连接字符串或Slack Webhook URL,不要硬编码到代码里。
四、验证调试
- 去Azure门户的函数应用「监控」里看日志,确认脚本是否正常执行
- 检查邮件/Slack是否收到统计结果,失败的话优先排查权限配置或环境变量是否正确
内容的提问来源于stack exchange,提问作者Dexter
相关产品推荐
相关产品推荐

