如何通过规则过滤S3创建事件,仅处理BitBucketPipeline触发的事件?
解决S3触发Lambda循环及按UserIdentity过滤事件的问题
问题背景
你的Lambda函数监听S3存储桶的s3:ObjectCreated:*事件,处理对象后写回同存储桶导致事件循环触发;同时希望仅处理由BitBucketPipeline创建的对象,不想在代码中做判断,想用原生规则实现过滤。
原生规则过滤方案:Lambda事件过滤
S3本身的事件通知规则仅支持前缀/后缀过滤,但Lambda支持事件过滤原生功能,可直接在事件源配置中对S3事件的userIdentity字段做匹配,无需修改业务代码。
修改后的Serverless配置
更新你的serverless.yml,在S3事件配置中添加filterPatterns,精准匹配userIdentity.principalId包含BitBucketPipeline的事件:
functions: processPostmanCollection: handler: handler.processPostmanCollection description: Handles the manipulation of postman collections to transform to our desired format. timeout: 900 events: - s3: bucket: example.bucket event: s3:ObjectCreated:* existing: true rules: - prefix: postman-collection-prod/ - suffix: .json filterPatterns: - eventName: ["ObjectCreated:*"] userIdentity: principalId: ["*BitBucketPipeline*"]
配置说明
filterPatterns是Lambda事件过滤的核心配置,这里指定仅触发userIdentity.principalId包含BitBucketPipeline的事件- 结合原有的前缀/后缀规则,进一步缩小触发范围;同时Lambda自身写回S3时的
userIdentity为执行角色,不会包含目标字符串,天然避免循环触发
额外优化:根源避免循环的补充方案
除了按UserIdentity过滤,还可以将处理后的对象写入不同前缀路径(比如postman-collection-prod-processed/),然后在S3事件规则中仅监听原前缀postman-collection-prod/,从根源上切断循环:
functions: processPostmanCollection: handler: handler.processPostmanCollection description: Handles the manipulation of postman collections to transform to our desired format. timeout: 900 events: - s3: bucket: example.bucket event: s3:ObjectCreated:* existing: true rules: - prefix: postman-collection-prod/ - suffix: .json filterPatterns: - eventName: ["ObjectCreated:*"] userIdentity: principalId: ["*BitBucketPipeline*"]
(业务代码中需将处理完成的对象写入postman-collection-prod-processed/前缀下)
这种方式可与UserIdentity过滤结合使用,形成双重保险,彻底解决循环问题。
内容的提问来源于stack exchange,提问作者Jarede
相关产品推荐
相关产品推荐

