Skip to content

Instantly share code, notes, and snippets.

@GedowFather
Last active March 8, 2016 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GedowFather/5dcc4eca2adfe04b2a77 to your computer and use it in GitHub Desktop.
Save GedowFather/5dcc4eca2adfe04b2a77 to your computer and use it in GitHub Desktop.
S3にDEBがアップロードされたらレポジトリを更新するLambdaスクリプト
import json
import urllib
import boto3
import os
import re
# constants
image_id = 'ami-a21529cc' # ubuntu-trusty-14.04-amd64-server-20160114.5
subnet_id = 'subnet-example'
instance_profile_name = 'InstanceProfileName'
s3 = boto3.client('s3')
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
s3.delete_object(Bucket=bucket, Key=key)
# key: debian-packages/jessie/re-index
# target_path: /debian/jessie/
# sync_path: s3://yum-repo-bucket/debian-packages/jessie/
# distribution: jessie
target_path = re.sub(r'([a-zA-Z]+)-packages/([^/]+)/re-index', r'/\1/\2/', key)
sync_path = "s3://%s/%s/" % (bucket, os.path.dirname(key))
codename = key.split('/')[1]
# Create UserData
user_data = """\
#!/bin/bash
apt-get update
apt-get install awscli bzip2 -y
mkdir /aptly
wget -q -O - https://bintray.com/artifact/download/smira/aptly/aptly_0.9.6_linux_amd64.tar.gz | sudo tar xz -C /aptly --strip 1
mkdir /deb
aws s3 sync %s /deb --region ap-northeast-1
codename="%s"
cat <<EOF > /etc/aptly.conf
{
"gpgDisableSign": true,
"gpgDisableVerify": true,
"S3PublishEndpoints": {
"drecom": {
"region": "ap-northeast-1",
"bucket": "%s"
}
}
}
EOF
/aptly/aptly repo create --distribution="$codename" --component=main "$codename"
/aptly/aptly repo add "$codename" /deb
/aptly/aptly snapshot create snap from repo "$codename"
/aptly/aptly publish snapshot snap s3:drecom:%s
shutdown -h now
""" % (sync_path, codename, bucket, target_path)
# Create Instance
ec2.run_instances(
ImageId = image_id,
MinCount = 1,
MaxCount = 1,
InstanceType = 't2.nano',
UserData = user_data,
InstanceInitiatedShutdownBehavior='terminate',
SubnetId = subnet_id,
IamInstanceProfile = { 'Name': instance_profile_name }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment