SlideShare a Scribd company logo
AWS Lambda
Scheduled file transfer sftp to s3
python
Steps
1. Create a new Administrator user in the IAM
2. Create a Role and allow Lambda execution and permissions for S3
operations
3. Take note of the User ARN
4. Deploy 64-bit Amazon Linux EC2 instance
5. SSH in, make project directory/folder
6. Create requirements.txt file, list python packages (except boto3)
7. Write the Handler
8. Zip up code and Dependencies
9. Create Lambda Function
10. Manually invoke the Lambda Function
11. Create the schedule
Handlerimport paramiko
import boto3
import datetime
import os
LOCALFILE='/tmp/invbatch.txt'
s3 = boto3.client('s3')
def connect_to_sftp():
transport = paramiko.Transport((os.environ['HOST'],int(os.environ['PORT'])))
transport.connect(username=os.environ['USERNAME'],
password=os.environ['PASSWORD'])
sftp = paramiko.SFTPClient.from_transport(transport)
return sftp
def handler(event, context):
sftp = connect_to_sftp()
sftp.get(os.environ['REMOTEFILE'], LOCALFILE)
now = datetime.datetime.today()
S3FILE='test/' + now.strftime('%Y%m%d-%H%M%S') + '_invbatch.txt'
s3.upload_file(Filename=LOCALFILE, Bucket='nufin-test-bucket', Key=S3FILE)
Makefile
Zip up Code and Dependencies
packageDependencies:
zip -r9 $(FUNCTION).zip sftp_to_s3.py
mkdir -p site-packages
virtualenv $(FUNCTION)
. $(FUNCTION)/bin/activate; pip install -r requirements.txt;
cd site-packages; cp -r $$VIRTUAL_ENV/lib/python2.7/site-packages/ ./;
cp -r $$VIRTUAL_ENV/lib64/python2.7/site-packages/ ./;
cd site-packages; zip -r9 ../../$(FUNCTION).zip .
PROJECT = sftp2s3
FUNCTION = $(PROJECT)
REGION = ap-southeast-1
ROLE = arn:aws:iam::864962608331:role/service-role/myLambdaRole
Makefile Variables
Makefile
Create the Lambda Function
createFunction:
aws lambda create-function 
--region $(REGION) 
--function-name $(PROJECT) 
--zip-file fileb://$(FUNCTION).zip 
--role $(ROLE) 
--environment Variables=“{HOST='12.123.123.12',PORT=22,USERNAME='lhftp',PASSWORD='123456789012',REMOTEFILE='lhftp_uploads/invb
--handler sftp_to_s3.handler 
--runtime python2.7 
--profile Administrator 
--timeout 10 
--memory-size 1024
Makefile
manualInvoke:
aws lambda invoke 
--invocation-type RequestResponse 
--function-name $(FUNCTION) 
--region $(REGION) 
--profile Administrator 
outputfile.txt
Manually Invoke the Lambda function to test it
Makefile
# Schedule the Lambda Function
# Step 1:
createRule:
aws events put-rule 
--region $(REGION) 
--name $(FUNCTION)-rule 
--schedule-expression 'cron(0/5 8-17 ? * MON-FRI *)' 
--profile Administrator
Schedule the Lambda function : Create the rule
Makefile
# $(ARNRULE) is taken from the put-rule target output and parsed in
# ARNRULE=arn:aws:events:.....
# Step 2:
addPermission:
aws lambda add-permission 
--region $(REGION) 
--function-name $(FUNCTION) 
--statement-id $(FUNCTION)-event 
--action 'lambda:InvokeFunction' 
--principal events.amazonaws.com 
--source-arn $(ARNRULE) 
--profile Administrator
Schedule the function : Give permission to the event
Makefile
Schedule the function : Associate the Lambda with the Event
putTargets:
aws events put-targets 
--region $(REGION) 
--rule $(FUNCTION)-rule 
--targets file://targets.json 
--profile Administrator
[
{
"Id": "1",
"Arn":"arn:aws:lambda:ap-southeast-1:864962608331:function:sftp2s3"
}
]
targets.json

More Related Content

What's hot

Data Migration to AWS with DataSync & Transfer for SFTP
Data Migration to AWS with DataSync & Transfer for SFTPData Migration to AWS with DataSync & Transfer for SFTP
Data Migration to AWS with DataSync & Transfer for SFTP
Amazon Web Services
 
Introduction to Stream Processing
Introduction to Stream ProcessingIntroduction to Stream Processing
Introduction to Stream Processing
Guido Schmutz
 
AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...
AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...
AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...
Simplilearn
 

What's hot (20)

Maximising the Customer Experience with Amazon Connect and AI Services
Maximising the Customer Experience with Amazon Connect and AI ServicesMaximising the Customer Experience with Amazon Connect and AI Services
Maximising the Customer Experience with Amazon Connect and AI Services
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
Data Migration to AWS with DataSync & Transfer for SFTP
Data Migration to AWS with DataSync & Transfer for SFTPData Migration to AWS with DataSync & Transfer for SFTP
Data Migration to AWS with DataSync & Transfer for SFTP
 
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
 
Server hardening
Server hardeningServer hardening
Server hardening
 
Introducing AWS Transfer for SFTP, a Fully Managed SFTP Service for Amazon S3...
Introducing AWS Transfer for SFTP, a Fully Managed SFTP Service for Amazon S3...Introducing AWS Transfer for SFTP, a Fully Managed SFTP Service for Amazon S3...
Introducing AWS Transfer for SFTP, a Fully Managed SFTP Service for Amazon S3...
 
[NEW LAUNCH!] Introducing Amazon Managed Streaming for Kafka (Amazon MSK) (AN...
[NEW LAUNCH!] Introducing Amazon Managed Streaming for Kafka (Amazon MSK) (AN...[NEW LAUNCH!] Introducing Amazon Managed Streaming for Kafka (Amazon MSK) (AN...
[NEW LAUNCH!] Introducing Amazon Managed Streaming for Kafka (Amazon MSK) (AN...
 
Cloud Computing: Overview and Examples
Cloud Computing: Overview and ExamplesCloud Computing: Overview and Examples
Cloud Computing: Overview and Examples
 
AWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless CloudAWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless Cloud
 
Marlabs Capabilities Overview: IT Services
Marlabs Capabilities Overview: IT ServicesMarlabs Capabilities Overview: IT Services
Marlabs Capabilities Overview: IT Services
 
Introduction to Amazon Redshift
Introduction to Amazon RedshiftIntroduction to Amazon Redshift
Introduction to Amazon Redshift
 
Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...
 
AWS Lambda in C#
AWS Lambda in C#AWS Lambda in C#
AWS Lambda in C#
 
Introduction to Stream Processing
Introduction to Stream ProcessingIntroduction to Stream Processing
Introduction to Stream Processing
 
Building large scale transactional data lake using apache hudi
Building large scale transactional data lake using apache hudiBuilding large scale transactional data lake using apache hudi
Building large scale transactional data lake using apache hudi
 
DevOps on AWS
DevOps on AWSDevOps on AWS
DevOps on AWS
 
AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...
AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...
AWS S3 | Tutorial For Beginners | AWS S3 Bucket Tutorial | AWS Tutorial For B...
 
Analyzing and processing streaming data with Amazon EMR - ADB204 - New York A...
Analyzing and processing streaming data with Amazon EMR - ADB204 - New York A...Analyzing and processing streaming data with Amazon EMR - ADB204 - New York A...
Analyzing and processing streaming data with Amazon EMR - ADB204 - New York A...
 
Oil tankers and helicopters: Convergence of BI and UX in banking
Oil tankers and helicopters: Convergence of BI and UX in bankingOil tankers and helicopters: Convergence of BI and UX in banking
Oil tankers and helicopters: Convergence of BI and UX in banking
 
Change Data Streaming Patterns for Microservices With Debezium
Change Data Streaming Patterns for Microservices With Debezium Change Data Streaming Patterns for Microservices With Debezium
Change Data Streaming Patterns for Microservices With Debezium
 

Similar to Schedule File Transfer from SFTP to S3 with AWS Lambda

Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02
arghya007
 
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
崇之 清水
 

Similar to Schedule File Transfer from SFTP to S3 with AWS Lambda (20)

Intro to AWS Lambda
Intro to AWS LambdaIntro to AWS Lambda
Intro to AWS Lambda
 
A Crash Course on Serverless Applications in Python
A Crash Course on Serverless Applications in PythonA Crash Course on Serverless Applications in Python
A Crash Course on Serverless Applications in Python
 
Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...
 
Step into serverless into the box 2018
Step into serverless into the box 2018Step into serverless into the box 2018
Step into serverless into the box 2018
 
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
 
Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02
 
Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013
Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013
Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013
 
Workshop: Building Your First Big Data Application on AWS
Workshop: Building Your First Big Data Application on AWSWorkshop: Building Your First Big Data Application on AWS
Workshop: Building Your First Big Data Application on AWS
 
【AWS Developers Meetup】RESTful APIをChaliceで紐解く
【AWS Developers Meetup】RESTful APIをChaliceで紐解く【AWS Developers Meetup】RESTful APIをChaliceで紐解く
【AWS Developers Meetup】RESTful APIをChaliceで紐解く
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 
AWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWSAWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWS
 
Writing Redis in Python with asyncio
Writing Redis in Python with asyncioWriting Redis in Python with asyncio
Writing Redis in Python with asyncio
 
Going Serverless
Going ServerlessGoing Serverless
Going Serverless
 
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
 
Building Your First Big Data Application on AWS
Building Your First Big Data Application on AWSBuilding Your First Big Data Application on AWS
Building Your First Big Data Application on AWS
 
Aws meetup building_lambda
Aws meetup building_lambdaAws meetup building_lambda
Aws meetup building_lambda
 
Microservices blue-green-deployment-with-docker
Microservices blue-green-deployment-with-dockerMicroservices blue-green-deployment-with-docker
Microservices blue-green-deployment-with-docker
 
Fabric Python Lib
Fabric Python LibFabric Python Lib
Fabric Python Lib
 
AWS Hadoop and PIG and overview
AWS Hadoop and PIG and overviewAWS Hadoop and PIG and overview
AWS Hadoop and PIG and overview
 
Presentation kyushu-2018
Presentation kyushu-2018Presentation kyushu-2018
Presentation kyushu-2018
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 

Schedule File Transfer from SFTP to S3 with AWS Lambda

  • 1. AWS Lambda Scheduled file transfer sftp to s3 python
  • 2. Steps 1. Create a new Administrator user in the IAM 2. Create a Role and allow Lambda execution and permissions for S3 operations 3. Take note of the User ARN 4. Deploy 64-bit Amazon Linux EC2 instance 5. SSH in, make project directory/folder 6. Create requirements.txt file, list python packages (except boto3) 7. Write the Handler 8. Zip up code and Dependencies 9. Create Lambda Function 10. Manually invoke the Lambda Function 11. Create the schedule
  • 3. Handlerimport paramiko import boto3 import datetime import os LOCALFILE='/tmp/invbatch.txt' s3 = boto3.client('s3') def connect_to_sftp(): transport = paramiko.Transport((os.environ['HOST'],int(os.environ['PORT']))) transport.connect(username=os.environ['USERNAME'], password=os.environ['PASSWORD']) sftp = paramiko.SFTPClient.from_transport(transport) return sftp def handler(event, context): sftp = connect_to_sftp() sftp.get(os.environ['REMOTEFILE'], LOCALFILE) now = datetime.datetime.today() S3FILE='test/' + now.strftime('%Y%m%d-%H%M%S') + '_invbatch.txt' s3.upload_file(Filename=LOCALFILE, Bucket='nufin-test-bucket', Key=S3FILE)
  • 4. Makefile Zip up Code and Dependencies packageDependencies: zip -r9 $(FUNCTION).zip sftp_to_s3.py mkdir -p site-packages virtualenv $(FUNCTION) . $(FUNCTION)/bin/activate; pip install -r requirements.txt; cd site-packages; cp -r $$VIRTUAL_ENV/lib/python2.7/site-packages/ ./; cp -r $$VIRTUAL_ENV/lib64/python2.7/site-packages/ ./; cd site-packages; zip -r9 ../../$(FUNCTION).zip . PROJECT = sftp2s3 FUNCTION = $(PROJECT) REGION = ap-southeast-1 ROLE = arn:aws:iam::864962608331:role/service-role/myLambdaRole Makefile Variables
  • 5. Makefile Create the Lambda Function createFunction: aws lambda create-function --region $(REGION) --function-name $(PROJECT) --zip-file fileb://$(FUNCTION).zip --role $(ROLE) --environment Variables=“{HOST='12.123.123.12',PORT=22,USERNAME='lhftp',PASSWORD='123456789012',REMOTEFILE='lhftp_uploads/invb --handler sftp_to_s3.handler --runtime python2.7 --profile Administrator --timeout 10 --memory-size 1024
  • 6. Makefile manualInvoke: aws lambda invoke --invocation-type RequestResponse --function-name $(FUNCTION) --region $(REGION) --profile Administrator outputfile.txt Manually Invoke the Lambda function to test it
  • 7. Makefile # Schedule the Lambda Function # Step 1: createRule: aws events put-rule --region $(REGION) --name $(FUNCTION)-rule --schedule-expression 'cron(0/5 8-17 ? * MON-FRI *)' --profile Administrator Schedule the Lambda function : Create the rule
  • 8. Makefile # $(ARNRULE) is taken from the put-rule target output and parsed in # ARNRULE=arn:aws:events:..... # Step 2: addPermission: aws lambda add-permission --region $(REGION) --function-name $(FUNCTION) --statement-id $(FUNCTION)-event --action 'lambda:InvokeFunction' --principal events.amazonaws.com --source-arn $(ARNRULE) --profile Administrator Schedule the function : Give permission to the event
  • 9. Makefile Schedule the function : Associate the Lambda with the Event putTargets: aws events put-targets --region $(REGION) --rule $(FUNCTION)-rule --targets file://targets.json --profile Administrator [ { "Id": "1", "Arn":"arn:aws:lambda:ap-southeast-1:864962608331:function:sftp2s3" } ] targets.json