import boto3
import base64
import os
def transfer_files_to_ec2(file_paths, instance_id, region="us-east-1"):
# Initialize SSM client
ssm_client = boto3.client("ssm", region_name=region)
for file_path in file_paths:
# Read and encode each file content in Base64
with open(file_path, "rb") as file:
file_content = file.read()
base64_content = base64.b64encode(file_content).decode("utf-8")
# Extract filename to be saved on EC2
filename = os.path.basename(file_path)
# Prepare SSM command with the Base64 content
commands = [
f'echo "{base64_content}" | base64 -d > /home/ec2-user/{filename}'
]
# Send the command to EC2 via SSM
response = ssm_client.send_command(
DocumentName="AWS-RunShellScript",
Parameters={"commands": commands},
InstanceIds=[instance_id]
)
# Fetch command ID to track
command_id = response["Command"]["CommandId"]
print(f"File '{filename}' is being transferred to instance '{instance_id}' as '/home/ec2-user/{filename}'.")
# Example usage
file_paths = ["test1.py", "test2.py"] # Replace with paths to your files
instance_id = "i-xxxxxxxxxxxxxxx" # Replace with your EC2 instance ID
region = "us-east-1" # Replace with your AWS region if different
transfer_files_to_ec2(file_paths, instance_id, region)
No comments:
Post a Comment