Here's a bash script to migrate an AWS Glue table from one AWS account/region to another. This script uses the AWS CLI and jq to extract and modify table metadata, then creates the table in the target environment.
✅ Prerequisites
- AWS CLI configured with appropriate permissions for both source and target accounts.
jq installed (for JSON processing).
- Replace placeholders (
<source_db>, <source_table>, etc.) with your actual values.
🧩 Script: migrate_glue_table.sh
#!/bin/bash
# Check for AWS CLI and jq
if ! command -v aws &> /dev/null; then
echo "AWS CLI not found. Please install and configure it."
exit 1
fi
if ! command -v jq &> /dev/null; then
echo "jq not found. Please install it."
exit 1
fi
# Configuration (Edit these values)
SOURCE_DB="your_source_database"
SOURCE_TABLE="your_source_table"
SOURCE_REGION="us-east-1"
TARGET_DB="your_target_database"
TARGET_REGION="us-west-2"
# Fetch the source table metadata
echo "Fetching table metadata from source..."
response=$(aws glue get-table --database-name "$SOURCE_DB" --name "$SOURCE_TABLE" --region "$SOURCE_REGION" 2>/dev/null)
if [ $? -ne 0 ]; then
echo "Error: Failed to retrieve table from source. Check permissions or table name."
exit 1
fi
# Extract the table structure
TABLE_JSON=$(echo "$response" | jq '.Table')
# Modify the database name in the table metadata
MODIFIED_JSON=$(echo "$TABLE_JSON" | jq --arg target_db "$TARGET_DB" '.DatabaseName = $target_db')
# Optional: Modify S3 location if needed (e.g., for cross-region migration)
# Example: Change S3 path to match target region
# MODIFIED_JSON=$(echo "$MODIFIED_JSON" | jq --arg target_region "$TARGET_REGION" '(.StorageDescriptor.Location | gsub("us-east-1", $target_region)) as $loc | .StorageDescriptor.Location = $loc')
# Create the table in the target
echo "Creating table in target database..."
aws glue create-table --database-name "$TARGET_DB" --table-input "$MODIFIED_JSON" --region "$TARGET_REGION"
if [ $? -eq 0 ]; then
echo "✅ Table migration completed successfully!"
else
echo "❌ Failed to create table in target. Check the JSON structure or permissions."
exit 1
fi
📌 How to Use
- Save the script as
migrate_glue_table.sh.
- Make it executable:
chmod +x migrate_glue_table.sh
- Run it:
./migrate_glue_table.sh
🧠 Notes
- S3 Location Adjustment: If the source and target regions differ, manually adjust the
StorageDescriptor.Location in the script (uncomment the optional section).
- Permissions: Ensure the AWS CLI profile used has
glue:GetTable and glue:CreateTable permissions in both source and target accounts.
- Existing Tables: This script will fail if the target table already exists. You can add a check to drop it first if needed.
🧪 Example Output
Fetching table metadata from source...
Creating table in target database...
✅ Table migration completed successfully!
Let me know if you need support for partitioned tables or advanced configurations!