Automating User creation in AWS SFTP service ( aws transfer for sftp)
DevOps AWS ☁️(CDA,CSA) | Python | Terraform | Packer | Docker | Jenkins | Ansible | ELK | Rancher | Kubernetes | Bash
import boto3
import click
import subprocess
import time
client = boto3.client('transfer')
s3 = boto3.client('s3')
# since we have only one server in ap-southeast-1 , change this accordingly
serverId=client.list_servers().get('Servers')[0].get('ServerId')
bucket_name = "your-bucket-name"
#bucket_notification = s3.BucketNotification(bucket_name)
@click.command()
@click.option('--user','-u',prompt="user name",help="name of the user to create as sftp user")
def create_user(lab):
#print(did)
path = f'~/Downloads/pems/{ user }'
subprocess.call(f'ssh-keygen -t rsa -f { path } -N ""', shell=True)
#print(f'lab privatekey create {path}')
time.sleep(3)
public_key_data=""
with open(f'{path}/pems/{user}.pub','r') as file:
public_key_data= file.read()
scope_down_policy='''{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowListingOfUserFolder",
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::${transfer:HomeBucket}"
],
"Condition": {
"StringLike": {
"s3:prefix": [
"${transfer:HomeFolder}/*",
"${transfer:HomeFolder}"
]
}
}
},
{
"Sid": "AWSTransferRequirements",
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:GetBucketLocation"
],
"Resource": "*"
},
{
"Sid": "HomeDirObjectAccess",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObjectVersion",
"s3:DeleteObject",
"s3:GetObjectVersion"
],
"Resource": "arn:aws:s3:::${transfer:HomeDirectory}/*"
}
]
}'''
tags=[
{
'Key': 'user',
'Value': f'{user}'
},
]
home_dir= f'/your-bucket/{lab}'
client.create_user(
HomeDirectory=home_dir,
Policy=scope_down_policy,
Role='arn:aws:iam::123456789123:role/sftp_role',
ServerId=serverId,
SshPublicKeyBody=f'{public_key_data}',
Tags=tags,
UserName=f'{user}'
)
s3.put_object(Bucket=bucket_name, Key=f'{user}/')
if __name__ == '__main__':
create_user()Published By
DevOps AWS ☁️(CDA,CSA) | Python | Terraform | Packer | Docker | Jenkins | Ansible | ELK | Rancher | Kubernetes | Bash
Last updated