MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

AWS Tutorials: Python code to sync S3 Buckets

This page shows how to sync Amazon S3 data with Python and boto3. The script above downloads every object in a bucket to a local folder. The sections below explain how it works, fix its limits (only the first 1,000 objects are fetched, everything is downloaded again on every run, and some keys can write files outside the target folder), and add a real bucket-to-bucket sync.



What the example above does

The script creates a boto3 S3 client and calls list_objects_v2 on the bucket. For each returned key it builds a local path, creates any parent folders, skips keys that end in / (the empty "folder" placeholders the S3 console creates) and downloads the object with download_file.

It works for a small test bucket, but it is a one-way copy, not a sync:

  • list_objects_v2 returns at most 1,000 keys per call. With no pagination, a larger bucket is only partly downloaded and no error is shown.
  • Every run downloads every object again, even when nothing has changed.
  • Files deleted from the bucket stay on disk.
  • Object keys come from the bucket owner. A key such as ../../etc/cron.d/job or /tmp/x makes os.path.join produce a path outside local_directory.
  • The bucket name and folder are hardcoded, and there is no error handling for missing credentials or denied access.
  • The title says "sync S3 buckets", but the code only syncs a bucket to a local folder.

Prerequisites

  • Python 3.8 or later and boto3: pip install boto3
  • AWS credentials that boto3 can find: aws configure, the environment variables AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, an SSO profile selected with AWS_PROFILE, or an IAM role on EC2, ECS, Lambda or EKS
  • IAM permissions for the buckets involved (see the policy below)
pip install boto3
aws sts get-caller-identity   # confirms which identity boto3 will use
aws s3 ls s3://my-source-bucket --recursive --summarize | tail -2Code language: PHP (php)

Corrected script: sync a bucket to a local folder

This version uses a paginator so every object is listed. It downloads an object only when the local file is missing, has a different size, or is older than the S3 object. It sets the local file's modification time to the object's LastModified time so the next run can tell the file is unchanged. It also refuses to write outside the target folder.

#!/usr/bin/env python3
"""Sync an S3 bucket (or a prefix inside it) to a local directory."""
import argparse
import os
import sys

import boto3
from botocore.exceptions import ClientError, NoCredentialsError


def safe_local_path(local_root, rel_key):
    root = os.path.realpath(local_root)
    target = os.path.realpath(os.path.join(root, rel_key.lstrip("/")))
    if os.path.commonpath([root, target]) != root:
        raise ValueError(f"Refusing to write outside {root}: {rel_key}")
    return target


def needs_download(path, obj):
    if not os.path.exists(path):
        return True
    st = os.stat(path)
    if st.st_size != obj["Size"]:
        return True
    return st.st_mtime < obj["LastModified"].timestamp()


def sync_bucket_to_local(bucket, local_dir, prefix="", dry_run=False):
    s3 = boto3.client("s3")
    paginator = s3.get_paginator("list_objects_v2")
    transferred = skipped = 0

    for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
        for obj in page.get("Contents", []):
            key = obj["Key"]
            rel = key[len(prefix):].lstrip("/")
            if not rel or key.endswith("/"):
                continue  # skip folder placeholder objects

            path = safe_local_path(local_dir, rel)
            if not needs_download(path, obj):
                skipped += 1
                continue

            transferred += 1
            print(f"{'(dryrun) ' if dry_run else ''}download: s3://{bucket}/{key} -> {path}")
            if dry_run:
                continue
            os.makedirs(os.path.dirname(path), exist_ok=True)
            s3.download_file(bucket, key, path)
            ts = obj["LastModified"].timestamp()
            os.utime(path, (ts, ts))  # lets the next run detect unchanged files

    print(f"Done: {transferred} transferred, {skipped} unchanged")


def main():
    p = argparse.ArgumentParser(description="Sync S3 bucket to local directory")
    p.add_argument("bucket")
    p.add_argument("local_dir")
    p.add_argument("--prefix", default="")
    p.add_argument("--dry-run", action="store_true")
    args = p.parse_args()

    try:
        sync_bucket_to_local(args.bucket, args.local_dir, args.prefix, args.dry_run)
    except NoCredentialsError:
        sys.exit("No AWS credentials found. Run 'aws configure' or set AWS_PROFILE.")
    except ClientError as e:
        sys.exit(f"AWS error: {e.response['Error']['Code']} - {e.response['Error']['Message']}")


if __name__ == "__main__":
    main()Code language: PHP (php)

Run it with a dry run first, then for real. A second run should report everything as unchanged:

$ python s3_sync_local.py my-source-bucket ./backup --dry-run
(dryrun) download: s3://my-source-bucket/logs/app.log -> /home/raj/backup/logs/app.log
Done: 1 transferred, 0 unchanged

$ python s3_sync_local.py my-source-bucket ./backup
download: s3://my-source-bucket/logs/app.log -> /home/raj/backup/logs/app.log
Done: 1 transferred, 0 unchanged

$ python s3_sync_local.py my-source-bucket ./backup
Done: 0 transferred, 1 unchangedCode language: JavaScript (javascript)

Note: download_file is a managed transfer. It uses multipart, parallel downloads for large objects, so you do not need to stream big files yourself.

Sync one S3 bucket to another

To sync two buckets, list both, copy objects that are missing or changed in the destination, and optionally delete destination objects that no longer exist in the source. s3.copy runs a server-side copy, so the data does not pass through your machine. It also switches to multipart copy for objects over 5 GB, which plain copy_object cannot handle.

import boto3


def list_objects(s3, bucket, prefix=""):
    objects = {}
    for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
        for obj in page.get("Contents", []):
            objects[obj["Key"]] = obj
    return objects


def sync_bucket_to_bucket(src, dst, prefix="", delete=False, dry_run=False):
    s3 = boto3.client("s3")
    src_objs = list_objects(s3, src, prefix)
    dst_objs = list_objects(s3, dst, prefix)
    tag = "(dryrun) " if dry_run else ""

    for key, obj in src_objs.items():
        d = dst_objs.get(key)
        if d and d["Size"] == obj["Size"] and d["LastModified"] >= obj["LastModified"]:
            continue  # unchanged
        print(f"{tag}copy: s3://{src}/{key} -> s3://{dst}/{key}")
        if not dry_run:
            s3.copy({"Bucket": src, "Key": key}, dst, key)

    if delete:
        for key in dst_objs.keys() - src_objs.keys():
            print(f"{tag}delete: s3://{dst}/{key}")
            if not dry_run:
                s3.delete_object(Bucket=dst, Key=key)


if __name__ == "__main__":
    sync_bucket_to_bucket("my-source-bucket", "my-dest-bucket", dry_run=True)Code language: PHP (php)

Like aws s3 sync, this compares size and last-modified time. It does not compare ETags, because an object uploaded with multipart upload gets a different ETag from the same bytes uploaded in one request.

Note: Use delete=True only after reviewing a dry run. On a bucket with versioning turned off, deleted objects cannot be recovered. Both key lists are held in memory, so for buckets with many millions of objects, use S3 Inventory, S3 Batch Operations or replication instead.

IAM permissions needed

s3:ListBucket applies to the bucket ARN. Object actions apply to bucket/*. The policy below covers bucket-to-local and bucket-to-bucket sync with deletes. Remove the statements you do not need.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": ["arn:aws:s3:::my-source-bucket", "arn:aws:s3:::my-dest-bucket"]
    },
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-source-bucket/*"
    },
    {
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::my-dest-bucket/*"
    }
  ]
}Code language: JSON / JSON with Comments (json)

If objects are encrypted with a customer managed KMS key, also grant kms:Decrypt on the source key and kms:GenerateDataKey on the destination key.

Common errors and fixes

ErrorLikely causeFix
NoCredentialsError: Unable to locate credentialsboto3 cannot find credentialsRun aws configure, set AWS_PROFILE, or attach an IAM role
AccessDenied on ListObjectsV2No s3:ListBucket on the bucket ARNGrant it on arn:aws:s3:::bucket (without /*)
ClientError: 403 Forbidden on HeadObject during downloadNo s3:GetObject, or no KMS decrypt permissionGrant s3:GetObject on bucket/*, plus kms:Decrypt if SSE-KMS is used
NoSuchBucketTypo in the name, or the bucket was deletedCheck with aws s3 ls
Only some files downloadedOriginal script without paginationUse get_paginator("list_objects_v2")
IsADirectoryError or NotADirectoryErrorBoth a and a/b exist as keys, so one path must be a file and the other a folderRename the conflicting keys; a local filesystem cannot hold both

Script, CLI or replication: which to use

OptionBest forNotes
Python boto3 scriptCustom filters, logic inside an application, Lambda jobsYou maintain the comparison and error handling yourself
aws s3 syncAd-hoc or cron-based syncsSupports --delete, --exclude, --dryrun; no code to write
S3 Replication (same-region or cross-region)Continuous, automatic bucket-to-bucket copiesNeeds versioning on both buckets; copies only new objects unless you run Batch Replication
aws s3 sync s3://my-source-bucket ./backup --dryrun
aws s3 sync s3://my-source-bucket s3://my-dest-bucket --deleteCode language: JavaScript (javascript)

Best practices

  • Always do a dry run before syncs that delete or overwrite data.
  • Use IAM roles or SSO profiles instead of long-lived access keys in scripts.
  • Turn on bucket versioning on the destination so overwrites and deletes can be undone.
  • Run the sync close to the data (EC2 or Lambda in the same region) to cut transfer time and data transfer charges. A VPC gateway endpoint keeps S3 traffic off the internet.
  • Log what was transferred and exit with a non-zero code on failure so schedulers such as cron or CI can alert.

Frequently asked questions

Does boto3 have a built-in sync function like aws s3 sync?

No. boto3 has no sync method. aws s3 sync is built into the AWS CLI, so with boto3 you list objects, compare them and call download_file, upload_file or copy yourself, as the scripts on this page do.

Why does my script download only 1,000 files from S3?

A single list_objects_v2 call returns at most 1,000 keys. Use s3.get_paginator("list_objects_v2") and loop over every page to list the whole bucket.

How do I copy objects between S3 buckets in different AWS accounts?

The identity running the copy needs s3:GetObject on the source and s3:PutObject on the destination, which usually means a bucket policy on one side. If the destination bucket does not use the Bucket owner enforced Object Ownership setting, also pass ExtraArgs={"ACL": "bucket-owner-full-control"} so the destination account owns the copied objects.

How do I sync only one folder of an S3 bucket?

S3 has no real folders, only key prefixes. Pass Prefix="folder/" to the paginator, or use --prefix folder/ with the script above, and only keys under that prefix are listed.

Is it cheaper to sync buckets with a script or with S3 Replication?

Both pay for requests and any cross-region data transfer. Replication avoids running and maintaining your own compute. Check current AWS S3 pricing for your regions before you decide.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

AWS Tutorials: AWS S3 Commands Example

The aws s3 commands in the AWS CLI handle everyday Amazon S3 work: creating and removing buckets, uploading and downloading files, moving objects and syncing whole directories….

Read More

7 Best Amazon S3 Backup Software Options, Compared for 2026

“What’s the best software to back up Amazon S3?” My short answer is that it depends on where the copy has to live, because that one decision…

Read More

Terraform Backend Tutorial

Terraform is a popular open-source infrastructure as code tool used to create and manage infrastructure resources. The state of the infrastructure resources managed by Terraform is stored…

Read More

Top 10 Data Lake Platforms in 2026: Features, Pros, Cons & Comparison

Introduction As businesses continue to accumulate vast amounts of data from a variety of sources, managing and extracting valuable insights from this data becomes a significant challenge….

Read More

Comprehensive Tutorial on Cloud Storage

๐Ÿ“– 1. What is Cloud Storage? Cloud Storage refers to the service model where data is stored, managed, and accessed remotely over the internet instead of being…

Read More

Amazon Data Firehose โ€“ The Ultimate Guide

In an era where data is the new oil, the ability to capture and process streaming data efficiently has become critical for businesses. Whether itโ€™s website activity…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x