如何用Python编写AWS Lambda实现AWS S3文件上传至Microsoft SharePoint
前置准备
- 在Azure AD注册应用,获取客户端ID、客户端密钥、租户ID,并为应用授予
Files.ReadWrite.All、Sites.ReadWrite.All的应用权限(需管理员同意) - 获取SharePoint目标站点ID(可通过Graph API端点
https://graph.microsoft.com/v1.0/sites/root查询)和目标文档库名称 - 为Lambda执行角色配置IAM策略,允许其调用
s3:GetObject访问目标S3桶
Python代码实现(Lambda函数)
1. 获取Graph API访问令牌
import requests import boto3 def get_graph_access_token(client_id, client_secret, tenant_id): token_endpoint = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token" payload = { "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": "https://graph.microsoft.com/.default" } resp = requests.post(token_endpoint, data=payload) resp.raise_for_status() return resp.json()["access_token"]
2. Lambda核心处理逻辑
def lambda_handler(event, context): # 敏感参数建议存储在AWS Secrets Manager,此处为示例直接填写 AZURE_CLIENT_ID = "你的Azure客户端ID" AZURE_CLIENT_SECRET = "你的Azure客户端密钥" AZURE_TENANT_ID = "你的Azure租户ID" SP_SITE_ID = "SharePoint站点ID" SP_DOC_LIB = "目标文档库名称" # 解析S3触发事件中的文件信息 s3_event = event['Records'][0]['s3'] bucket = s3_event['bucket']['name'] file_key = s3_event['object']['key'] file_name = file_key.split('/')[-1] # 读取S3文件内容 s3_client = boto3.client('s3') s3_obj = s3_client.get_object(Bucket=bucket, Key=file_key) file_content = s3_obj['Body'].read() # 获取Graph API访问令牌 access_token = get_graph_access_token(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID) # 上传文件到SharePoint文档库 upload_endpoint = f"https://graph.microsoft.com/v1.0/sites/{SP_SITE_ID}/drive/root:/{SP_DOC_LIB}/{file_name}:/content" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/octet-stream" } upload_resp = requests.put(upload_endpoint, headers=headers, data=file_content) upload_resp.raise_for_status() return { 'statusCode': 200, 'body': f"文件 {file_name} 已成功上传至SharePoint" }
关键注意事项
- 敏感信息管理:禁止硬编码客户端密钥、租户ID等敏感数据,使用AWS Secrets Manager或Systems Manager Parameter Store存储,Lambda运行时通过API读取
- 大文件处理:若上传文件超过4MB,需改用Graph API的分块上传接口(调用
createUploadSession创建会话后分块上传) - 权限校验:确认Azure AD应用的权限已获得管理员同意,Lambda执行角色的IAM策略包含S3读取权限
- 错误处理:建议添加
try-except异常捕获逻辑,处理S3读取失败、令牌获取失败、上传失败等场景,提升函数稳定性
内容的提问来源于stack exchange,提问作者user56564
相关产品推荐
相关产品推荐

