Below is a Bash script to migrate an AWS Glue table from one database to another or to a different AWS account. This script assumes you have the AWS CLI configured and the necessary permissions to access Glue resources.
#!/bin/bash
# Variables
SOURCE_DATABASE="source_db_name"
TARGET_DATABASE="target_db_name"
TABLE_NAME="table_to_migrate"
AWS_REGION="us-east-1"
# Function to check if a table exists in the target database
table_exists() {
aws glue get-table --database-name "$1" --name "$2" --region "$AWS_REGION" > /dev/null 2>&1
}
# Function to migrate the table
migrate_table() {
# Get the table definition from the source database
TABLE_DEFINITION=$(aws glue get-table --database-name "$SOURCE_DATABASE" --name "$TABLE_NAME" --region "$AWS_REGION" --query 'Table' --output text)
# Check if the table already exists in the target database
if table_exists "$TARGET_DATABASE" "$TABLE_NAME"; then
echo "Table $TABLE_NAME already exists in $TARGET_DATABASE. Updating..."
aws glue update-table --database-name "$TARGET_DATABASE" --table-input "$TABLE_DEFINITION" --region "$AWS_REGION"
else
echo "Migrating table $TABLE_NAME from $SOURCE_DATABASE to $TARGET_DATABASE..."
aws glue create-table --database-name "$TARGET_DATABASE" --table-input "$TABLE_DEFINITION" --region "$AWS_REGION"
fi
}
# Main script execution
if [ -z "$SOURCE_DATABASE" ] || [ -z "$TARGET_DATABASE" ] || [ -z "$TABLE_NAME" ]; then
echo "Error: SOURCE_DATABASE, TARGET_DATABASE, and TABLE_NAME must be set."
exit 1
fi
migrate_table
echo "Migration completed successfully!"
How It Works:
Variables: Set the source database, target database, table name, and AWS region.
table_exists Function: Checks if a table exists in the target database using the get-table command.
migrate_table Function:
Fetches the table definition from the source database.
Checks if the table already exists in the target database.
If the table exists, it updates the table; otherwise, it creates a new table in the target database.
Main Script: Validates the required variables and calls the migrate_table function.
Prerequisites:
AWS CLI installed and configured with the necessary permissions.
Ensure the Glue table exists in the source database.
Usage:
Save the script to a file, e.g., migrate_glue_table.sh.
Make it executable: chmod +x migrate_glue_table.sh.
Run the script: ./migrate_glue_table.sh.
Notes:
Modify the AWS_REGION variable to match your AWS region.
Ensure the IAM role used has permissions for glue:GetTable, glue:CreateTable, and glue:UpdateTable.
If migrating across accounts, ensure the AWS CLI is configured with the appropriate credentials for the target account.