S3にRPMがアップロードされたらレポジトリを更新するLambdaスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import urllib | |
import boto3 | |
import os | |
import re | |
# constants | |
image_id = 'ami-59bdb937' # Amazon Linux AMI 2015.09.2 x86_64 HVM GP2 | |
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: centos-packages/7/x86_64/re-index | |
# target_path: s3://yum-repo-bucket/centos/7/x86_64/ | |
# sync_path: s3://yum-repo-bucket/centos-packages/7/x86_64/ | |
target_key = re.sub(r'([a-zA-Z]+)-packages/([^/]+)/([^/]+)/re-index', r'\1/\2/\3', key) | |
target_path = "s3://%s/%s/" % (bucket, target_key) | |
sync_path = "s3://%s/%s/" % (bucket, os.path.dirname(key)) | |
# Create UserData | |
user_data = """\ | |
#!/bin/bash | |
yum install -y createrepo | |
aws s3 sync %s /repo --region ap-northeast-1 | |
createrepo --checksum sha /repo | |
aws s3 sync --exact-timestamps --delete /repo %s --region ap-northeast-1 | |
shutdown -h now | |
""" % (sync_path, 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