【发布时间】:2019-05-20 07:05:44
【问题描述】:
我已将我的 ELB 日志启用到 S3 存储桶。我正在尝试使用以下 lambda 脚本将 S3 日志发送到 Elasticsearch。
日志以 *.log.gz 格式存储在 s3 存储桶中。如何将发送 zip 文件以 json 格式发送到 elasticsearch。
让我知道是否有更好的方法来做到这一点。
import boto3
import re
import requests
from requests_aws4auth import AWS4Auth
region = '' # e.g. us-west-1
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)
host = '' # the Amazon ES domain, including https://
index = 'lambda-s3-index'
type = 'lambda-type'
url = host + '/' + index + '/' + type
headers = { "Content-Type": "application/json" }
s3 = boto3.client('s3')
# Regular expressions used to parse some simple log lines
ip_pattern = re.compile('(\d+\.\d+\.\d+\.\d+)')
time_pattern = re.compile('\[(\d+\/\w\w\w\/\d\d\d\d:\d\d:\d\d:\d\d\s-\d\d\d\d)\]')
message_pattern = re.compile('\"(.+)\"')
# Lambda execution starts here
def handler(event, context):
for record in event['Records']:
# Get the bucket name and key for the new file
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
# Get, read, and split the file into lines
obj = s3.get_object(Bucket=bucket, Key=key)
body = obj['Body'].read()
lines = body.splitlines()
# Match the regular expressions to each line and index the JSON
for line in lines:
ip = ip_pattern.search(line).group(1)
timestamp = time_pattern.search(line).group(1)
message = message_pattern.search(line).group(1)
document = { "ip": ip, "timestamp": timestamp, "message": message }
r = requests.post(url, auth=awsauth, json=document, headers=headers)
【问题讨论】:
-
您是否尝试伪造一个 JSON 事件并手动运行 Lambda?
-
您所指的链接是指未压缩的文件。但是您的问题更多是围绕 *.gz 压缩文件。您的代码缺少首先解压缩 S3 文件的行。例如:
striodata = StringIO.StringIO(body) with gzip.GzipFile(fileobj=striodata, mode='r') as f: lines = (f.read()).splitlines()。让我知道这是否是问题所在,然后我将使用更多代码将其粘贴为答案。
标签: amazon-web-services elasticsearch amazon-s3 aws-sdk boto3