Using AWS Batch jobs to bulk copy/sync files in S3

Overview

Using AWS Batch jobs to bulk copy/sync files in S3

Use Cases

Overview

This guide details how to use AWS Batch to perform bulk copy/sync activities on files in S3. Batch allows users to run massively scalable computing jobs on AWS by provisioning the optimal compute resources needed. The user is able to focus on configuring what the job should be doing instead of provisioning infrastructure.

Here we use Batch's Managed Compute environment with the Fargate provioning model, where Batch runs containers without the user having to manage the underlying EC2 instances. We will package our application within an ECR container image that Fargate will use to launch the environment where the job runs.

With Batch configured, the user will upload a .csv file in an S3 location that has it's events being logged in Cloudtrail. This is being monitored by Eventbridge which will kick off the Batch job once the appropriate file is uploaded. The .csv file contains a list of S3 source/destination pairs to be copied/synced in the job as detailed below. For accessing S3 resources in different AWS accounts, be sure to look at the IAM Roles section below

Architecture

This is an overview of the architecture described above:

awsBatchS3SyncArch

ECR Image

The ECR Image contains our application logic to sync/copy S3 files based on the csv input. This is done in the python script s3CopySyncScript.py. Based on the CSV input, it will perform a managed transfer using the copy api if a file is given as a source/destination. If a prefix is given as source/destination, it will use the AWS CLI to perform an aws s3 sync.

The Dockerfile builds an image based on AL2, installing the AWS cli, python3, boto3, and setting other s3 configuration for optimal transfers.

Create an ECR repository and use these commands to build and push the image as latest using the CLI.

aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <<
   
    >>.dkr.ecr.us-east-1.amazonaws.com

docker build -t <<
    
     >> .

docker tag <<
     
      >>:latest <<
      
       >>.dkr.ecr.us-east-1.amazonaws.com/<<
       
        >>:latest docker push <<
        
         >>.dkr.ecr.us-east-1.amazonaws.com/<<
         
          >>:latest 
         
        
       
      
     
    
   

S3 Input Location

The .csv file will be uploaded to s3 to kick off the job. Designate an area for this. In this example, I've created a sample bucket with the prefix input and will be uploading files here. Notice also the uploaded csv is prefixed as such: s3_batch_sync_input-*.csv. Using a naming convention like this can simplify eventbridge monitoring which we'll see below.

s3InputSample

CSV File Format Details

The csv file should be formatted as such.

source destination
s3://some-bucket/source/ s3://some-bucket/dest/
s3://some-bucket/sourcetwo/ s3://some-bucket/desttwo/
s3://some-bucket/sourceindiv/individualFile.txt s3://some-bucket/dest/individualFile.txt

The first 2 rows in this example are prefixes where we want an s3 sync to occur. The last row is a specific object we want to copy directly. The bucket/AWS account does not need to be the same, as long as IAM permissions are properly applied as noted below.

Cloudtrail Monitoring

Setup a trail that will monitor the S3 location where the input file will land. In setting up the trail you can set these options as you see fit: name, an s3 location for the logs, log encryption using KMS, log validation. You will need to make sure that S3 data events for the location where the input file lands is enabled at a minimum:

cloudTrailS3DataEvents

AWS Batch

Compute Environment

This will serve as a pool that our batch jobs can pull resources from. Create a managed environment with the instance configuration set to fargate for this example. Set the max vCPUs to set an upper limit for concurrent fargate resources being used. Other configuration options for an AWS Batch Compute Environment are detailed here. Lastly pick the VPC and subnets your environment will be located in, and security groups that may need to be attached to instances. If you're using S3 VPC gateway endpoints this would be key. In our example, we're using the default VPC since we're accessing S3 through public internet. Once complete, the environment state would be ENABLED.

batchComputeEnvironment

Job Queue

AWS Batch Jobs are submitted to a job queue until compute environment resources are available for the job to run. You can have multiple queues with different priorities which pull from different compute environments. More details are here. For this example, create a queue and attach it to the compute environment previously made.

batchJobQueue

Job Definition

The Job Definition acts as a template from which to launch our individual jobs. Detailed instructions are here for additional configuration.

  • Basics

    • Enter a name for the template and pick fargate for the platform.
    • Depending on your anticipated use, set a retry strategy and timeout. For this example we set 2 job attempts and a timeout of 120 seconds.
    • We'll also put job logs in the default AWS Batch logs group in cloudwatch but it can be customized as detailed here.
  • Python Script Usage

    • Note the usage of the script described here and then set the container properties in the next step as required
    • Syntax: python s3CopySyncScript.py < > < > <
      > < >
      • header indicates whether the input csv has a header row
      • sync_delete indicates whether the --delete flag is used in case of an aws s3 sync
      • EG: Syntax: python s3CopySyncScript.py my-s3-bucket s3_batch_sync_input-my-sample.csv True True
  • Container Properties

    • In the image box, put the URI of the ECR image that was created.
    • The Command is used as the CMD instruction to execute our container. In our case, we want to execute the python script and pass it our input file details.
      • In JSON form we enter: ["python3","s3CopySyncScript.py","Ref::s3_bucket","Ref::s3_key", "True", "True"]
        • In this example, I have a header in the input and am using the --delete flag an aws s3 sync
    • For vCPUs and memory, we set 1 and 2GB to be conservative for this example. Set it as needed.
    • Job Role and Execution Role are detailed below.
    • We ticked the box for assign public IP since we're accessing S3 through the public internet and are using Fargate platform version 1.4.0
  • Parameters

    • In the python command above, notice the "Ref::s3_bucket","Ref::s3_key". These are parameters to be substituted when a job is invoked through Eventbridge.
    • In this section, we could set defaults for them or other parameters. See more details here.

batchJobDef

IAM Roles

Execution Role
The Execution role is used to setup individual ECS tasks where we run the Batch jobs and for logging. The role should have a trust relationship with ecs-tasks.amazonaws.com. In our example, the AWS managed policy AmazonECSTaskExecutionRolePolicy is attached along with an inline policy giving it permission to create log groups if needed.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
                "logs:DescribeLogStreams"
            ],
            "Resource": [
                "arn:aws:logs:*:*:*"
            ]
        }
    ]
}

More details about ECS task execution roles are here.

Job Role
The Job Role is an IAM role that is used provide AWS API access to individual running jobs. Here we configure access to AWS resources the job accesses, the files in S3 in our case. Here we're only accessing resources in one bucket, but be sure to configure this as needed depending on your sources/destinations. Again, the role should have a trust relationship with ecs-tasks.amazonaws.com.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:ListBucketMultipartUploads",
                "s3:ListBucket",
                "s3:ListMultipartUploadParts"
            ],
            "Resource": [
                "arn:aws:s3:::s3-batch-sync-article/*",
                "arn:aws:s3:::s3-batch-sync-article"
            ]
        }
    ]
}

If you're accessing S3 objects from/syncing to destinations in multiple accounts, Cross Account S3 Resource Access would need to be configured as detailed here. The account where the Batch jobs run can be considered Account A where a policy providing access resources in AWS Account B's buckets is attached to the IAM role. In Account B, the bucket policy would be modified to allow access from Account A's IAM role. More details about these task IAM roles can be found here.

Eventbridge Rule & Job Invokation

Create an Eventbridge rule that will invoke the AWS Batch job.

Here, the S3 uploads are being logged in cloudtrail. An eventbridge rule will invoke the job with an appropriate upload. Using the naming convention mentioned above, we can use a custom event pattern match and content filtering to only trigger on certain uploads.

{
  "source": ["aws.s3"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": ["s3.amazonaws.com"],
    "eventName": ["PutObject", "CompleteMultipartUpload"],
    "requestParameters": {
      "bucketName": ["s3-batch-sync-article"],
      "key": [{
        "prefix": "input/s3_batch_sync_input-"
      }]
    }
  }
}

Here, we'll trigger the target for this rule when a file lands in the appropriate location with the required prefix.

AWS Batch Target

  • Set the target for this rule to a Batch job queue.
  • Give it the job queue and job definition set above. Provide a name for the jobs that will run.
  • Use configure input to pass details about the input file to the job. In our job, the bucket and key is required as arguments to the python script which we supply as Job Parameters.
    • Use the first input path box to get the bucket and key from the event that triggered the Eventbridge rule. This gets the bucket and key
      • {"S3BucketValue":"$.detail.requestParameters.bucketName","S3KeyValue":"$.detail.requestParameters.key"}
    • The input template box lets you pass parameters or other arguments to the job that is to be invoked. Here we pass the s3_bucket and s3_key job parameters
      • {"Parameters" : {"s3_bucket": , "s3_key": }}
    • See more details about AWS Batch Jobs as CloudWatch Events Targets here
Owner
AWS Samples
AWS Samples
YouTube-Discord-Bot - Discord Bot to Search YouTube

YouTube Bot Info YouTube Bot is a discord bot where you can search for anything

Riceblades11 10 Mar 05, 2022
Python client for Toyota North America service API

toyota-na Python client for Toyota North America service API Install pip install toyota-na[qt] [qt] is required for generating authorization code. Us

Gavin Ni 18 Sep 06, 2022
AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications

AWS Serverless Application Model (AWS SAM) The AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications

Amazon Web Services 8.9k Dec 31, 2022
A stock information collector and parser for Taiwan and US market. Automatically send LINE message if the pre-defined rules are triggered.

agastock 開發動機 就在海運飆漲的2021年7月,差點跪在地上喜迎財富自由的當下,EPS超高好消息不斷的長榮竟然套在202元一去不回,有圖有真相(哭) 忽然體會到追高殺低不是辦法,魯蛇我得靠邏輯分析也能出頭天,經過三個月無數個不出門的周末,產出簡單的爬蟲和分析工具。 上過金融研訓院的量化交易

Gavin Lee 12 Nov 16, 2022
Plays air warning sound when detects a certain phrase or a word in a specified Telegram chat.

Tryvoha Bot Disclaimer: this is more a convenient naming, rather than a real bot. It is designed to play air warning sound when detects a certain phra

Dmytro Novikov 2 Mar 02, 2022
An all-in-one discord bot!

Interbot Interbot is a do-it-all bot originally made for the Interbyte Studios discord server. This repo contains the code for this bot, allowing you

Logan 5 Aug 03, 2021
🐍 Mnemonic code for generating deterministic keys, BIP39

python-mnemonic 🐍 Mnemonic code for generating deterministic keys, BIP39 Installation To install this library and its dependencies use: pip install m

9 Dec 22, 2022
Python implementation of Spotify's authorization flow.

Spotify API Apps 🎷 🎶 🎼 This repository consists of many strange codes that make you think why the hell this guy doing this. Well... I got some reas

5 Dec 17, 2021
Tomli is a Python library for parsing TOML. Tomli is fully compatible with TOML v1.0.0.

Tomli A lil' TOML parser Table of Contents generated with mdformat-toc Intro Installation Usage Parse a TOML string Parse a TOML file Handle invalid T

Taneli Hukkinen 313 Dec 26, 2022
Centralized whale instance using github actions, sourcing metadata from bigquery-public-data.

Whale Demo Instance: Bigquery Public Data This is a fully-functioning demo instance of the whale data catalog, actively scraping data from Bigquery's

Hyperquery 17 Dec 14, 2022
Eva Maria Bot With Python

Eva Maria Bot Features Auto Filter Manual Filter IMDB Admin Commands Broadcast Index IMDB search Inline Search Random pics ids and User info Stats, Us

Aadhi 3 Jan 06, 2022
Telegram-Voice Recoginiton Project (Python)

Telegram-Voice Recoginiton Project (Python) It is a telegram bot that analyses voice messages and convert it to text and reply back response on bot's

Krishnadev P Melevila 1 Jan 28, 2022
Starlink Order Status Notification

Starlink Order Status Notification This script logs into Starlink order portal, pulls your estimated delivery date and emails it to a designated email

Aaron R. 1 Jul 08, 2022
Implementation of the paper 'Sentence Bottleneck Autoencoders from Transformer Language Models'

Introduction This repository contains the code for the paper Sentence Bottleneck Autoencoders from Transformer Language Models by Ivan Montero, Nikola

Ivan Montero 14 Dec 28, 2022
Python Client for Instagram API

This project is not actively maintained. Proceed at your own risk! python-instagram A Python 2/3 client for the Instagram REST and Search APIs Install

Facebook Archive 2.9k Dec 30, 2022
An advanced crypto trading bot written in Python

Jesse Jesse is an advanced crypto trading framework which aims to simplify researching and defining trading strategies. Why Jesse? In short, Jesse is

Jesse 4.4k Jan 09, 2023
The best discord Nuk3r !

Discord - Nuker ☢️ Nuk3r ☢️ STEP 1 ✅ We go create discord bot ! [] Go on https://discord.com/developers/applications [] Set the name of your applica

2s.py 1 Apr 16, 2022
Python script for download course from platzi.com

Platzi Downloader Tool Esta es una pequeña herramienta que hace mucho y que te ahorra una gran cantidad de trabajo a la hora de descargar cursos de Pl

Devil64-Dev 21 Sep 22, 2022
Clubhouse API written in Python. Standalone client included. For reference and education purposes only.

clubhouse-py is originally developed for the sake of interoperability. Standalone client is also created with very basic features, including but not limited to the audio-chat

1.7k Jan 05, 2023