Skip to content

Instantly share code, notes, and snippets.

@tillkruss

tillkruss/README.md

Last active Jun 22, 2020
Embed
What would you like to do?
AWS Lambda function that optimizes images uploaded to a S3 bucket using Kraken.io's API.

Lambda S3 Kraken

Trigger

  • Event type: ObjectCreated
  • Suffix: jpg

Environment variables

  • AWS_KEY
  • AWS_SECRET
  • KRAKEN_SECRET
  • KRAKEN_KEY

IAM user with access key

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::BUCKET-NAME/*"
        }
    ]
}

IAM role for Lambda

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::BUCKET-NAME/*"
        }
    ]
}
from __future__ import print_function
import os
import json
import urllib
import urllib2
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
try:
head = s3.head_object(Bucket=bucket, Key=key)
if head['Metadata'].has_key('kraked'):
print('Stopped. Image already optimized: ' + key)
return
except:
print('HEAD request unsuccessful: ' + key)
params = {
'auth': {
'api_key': os.environ['KRAKEN_KEY'],
'api_secret': os.environ['KRAKEN_SECRET']
},
'url': 'https://BUCKET-NAME.s3-REGION.amazonaws.com/' + key,
's3_store': {
'key': os.environ['AWS_KEY'],
'secret': os.environ['AWS_SECRET'],
'region': 'us-east-1',
'bucket': 'BUCKET-NAME',
'path': key,
'metadata': {
'kraked': 'yes'
}
},
'wait': True,
'lossy': False
}
url = 'https://api.kraken.io/v1/url'
try:
data = json.dumps(params)
request = urllib2.Request(url, data, {'Content-Type': 'application/json'})
response = urllib2.urlopen(request)
jsonRes = json.loads(str(response.read()))
if (jsonRes['success']):
print('Success. Optimized image: ' + jsonRes['kraked_url'])
else:
print('Failed. Error message: ' + jsonRes['message'])
except Exception as e:
print(e)
print('Error optimizing object: ' + key)
raise e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment