Okay, here is a bash script using the AWS CLI and jq to migrate an AWS Glue table definition from one location (potentially different account/region) to another.
Key Assumptions:
Metadata Migration: This script migrates the metadata definition of the Glue table (schema, partition keys, storage format, etc.). It does not migrate the actual data stored in S3. You'll need a separate process (like aws s3 sync) to copy the data if necessary.
S3 Location Change: The most critical part of migration is changing the S3 data location. The script requires you to provide the new S3 path for the target table.
Dependencies: You need awscli and jq installed and configured correctly.
Permissions: The environment running the script needs IAM permissions to:
glue:GetTable (source)
glue:GetDatabase (target)
glue:CreateTable (target)
glue:UpdateTable (target, if overwriting)
glue:CreateDatabase (target, if needed)
Potentially S3 permissions if you were to extend this to copy data.
AWS Profiles (Optional): The script includes optional arguments for specifying AWS profiles if you aren't using the default configuration or environment variables.
The Script:
bash
#!/bin/bash
# Exit immediately if a command exits with a non-zero status.
set -e
# Treat unset variables as an error when substituting.
set -u
# Pipelines return the exit status of the last command that failed,
# or zero if all commands in the pipeline succeeded.
set -o pipefail
# --- Configuration ---
SCRIPT_NAME=$(basename "$0")
# --- Functions ---
usage() {
echo "Usage: $SCRIPT_NAME [-o] [-p <source_profile>] [-P <target_profile>] <source_region> <source_db> <source_table> <target_region> <target_db> <target_table> <target_s3_location>"
echo ""
echo "Migrates an AWS Glue table definition."
echo ""
echo "Arguments:"
echo " <source_region> AWS region of the source table (e.g., us-east-1)"
echo " <source_db> Name of the source Glue database"
echo " <source_table> Name of the source Glue table"
echo " <target_region> AWS region for the target table"
echo " <target_db> Name of the target Glue database (will be created if it doesn't exist)"
echo " <target_table> Name of the target Glue table"
echo " <target_s3_location> The S3 path for the target table's data (e.g., s3://your-target-bucket/path/to/table/)"
echo ""
echo "Options:"
echo " -o Overwrite the target table if it already exists."
echo " -p <source_profile> AWS CLI profile name for the source account/region."
echo " -P <target_profile> AWS CLI profile name for the target account/region."
echo ""
echo "Dependencies:"
echo " - awscli (v2 recommended)"
echo " - jq"
echo ""
echo "Example:"
echo " $SCRIPT_NAME us-east-1 my_source_db my_source_table us-west-2 my_target_db my_target_table s3://my-data-bucket/processed/my_target_table/"
echo " $SCRIPT_NAME -o -p dev_profile -P prod_profile eu-central-1 prod_db prod_table ap-southeast-2 dev_db dev_table s3://dev-data-bucket/dev_table/"
exit 1
}
# --- Argument Parsing ---
SOURCE_PROFILE=""
TARGET_PROFILE=""
OVERWRITE=false
while getopts ":op:P:" opt; do
case $opt in
o)
OVERWRITE=true
;;
p)
SOURCE_PROFILE="--profile $OPTARG"
;;
P)
TARGET_PROFILE="--profile $OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
;;
esac
done
shift $((OPTIND-1))
if [[ "$#" -ne 7 ]]; then
echo "Error: Incorrect number of arguments." >&2
usage
fi
SOURCE_REGION="$1"
SOURCE_DB="$2"
SOURCE_TABLE="$3"
TARGET_REGION="$4"
TARGET_DB="$5"
TARGET_TABLE="$6"
TARGET_S3_LOCATION="$7"
# --- Prerequisite Check ---
command -v aws >/dev/null 2>&1 || { echo >&2 "AWS CLI is required but not installed. Aborting."; exit 1; }
command -v jq >/dev/null 2>&1 || { echo >&2 "jq is required but not installed. Aborting."; exit 1; }
# --- Helper Functions ---
# Function to construct AWS CLI commands with optional profiles and regions
aws_cmd() {
local target_cmd=$1
shift
aws "$target_cmd" --region "${!2}" ${3:-} "$@"
}
# --- Main Logic ---
echo "Starting Glue table migration..."
echo "-------------------------------------"
echo "Source Region: $SOURCE_REGION"
echo "Source Database: $SOURCE_DB"
echo "Source Table: $SOURCE_TABLE"
echo "Target Region: $TARGET_REGION"
echo "Target Database: $TARGET_DB"
echo "Target Table: $TARGET_TABLE"
echo "Target S3 Location: $TARGET_S3_LOCATION"
echo "Overwrite Target: $OVERWRITE"
[[ -n "$SOURCE_PROFILE" ]] && echo "Source Profile: $(${SOURCE_PROFILE#--profile } )"
[[ -n "$TARGET_PROFILE" ]] && echo "Target Profile: $(${TARGET_PROFILE#--profile } )"
echo "-------------------------------------"
# 1. Get Source Table Definition
echo "[1/5] Fetching definition for source table '$SOURCE_DB.$SOURCE_TABLE' in region '$SOURCE_REGION'..."
TABLE_DEFINITION=$(aws_cmd glue get-table SOURCE_REGION SOURCE_PROFILE --database-name "$SOURCE_DB" --table-name "$SOURCE_TABLE")
if [[ $? -ne 0 || -z "$TABLE_DEFINITION" ]]; then
echo >&2 "Error: Failed to get table definition for '$SOURCE_DB.$SOURCE_TABLE' in region '$SOURCE_REGION'."
exit 1
fi
# Extract the Table object, which contains TableInput and DatabaseName
# We need TableInput for create/update, and DatabaseName separately
SOURCE_TABLE_OBJECT=$(echo "$TABLE_DEFINITION" | jq '.Table')
if [[ -z "$SOURCE_TABLE_OBJECT" || "$SOURCE_TABLE_OBJECT" == "null" ]]; then
echo >&2 "Error: Could not parse Table object from get-table output."
exit 1
fi
# 2. Prepare Target Table Definition JSON
echo "[2/5] Preparing modified definition for target table '$TARGET_DB.$TARGET_TABLE'..."
# Extract TableInput structure, remove DatabaseName (it's handled separately)
# Update the Location, Name, and potentially other fields
MODIFIED_TABLE_INPUT=$(echo "$SOURCE_TABLE_OBJECT" | jq --arg loc "$TARGET_S3_LOCATION" \
'.StorageDescriptor.Location = $loc' \
| jq --arg tbl "$TARGET_TABLE" \
'.Name = $tbl')
# Add any other desired modifications here using jq, e.g.:
# MODIFIED_TABLE_INPUT=$(echo "$MODIFIED_TABLE_INPUT" | jq '...')
# Ensure S3 location ends with a slash if the original did, Glue generally handles it, but good practice.
# Example: Check and potentially add:
# ORIGINAL_LOCATION=$(echo "$SOURCE_TABLE_OBJECT" | jq -r '.StorageDescriptor.Location')
# if [[ "$ORIGINAL_LOCATION" == */ ]] && [[ "$TARGET_S3_LOCATION" != */ ]]; then
# MODIFIED_TABLE_INPUT=$(echo "$MODIFIED_TABLE_INPUT" | jq --arg loc "${TARGET_S3_LOCATION}/" '.StorageDescriptor.Location = $loc')
# fi
# Construct the final JSON payload structure for create-table command
CREATE_PAYLOAD=$(echo "$MODIFIED_TABLE_INPUT" | jq --arg db "$TARGET_DB" \
'{DatabaseName: $db, TableInput: .}')
# Construct the TableInput JSON needed for update-table command
UPDATE_TABLE_INPUT_JSON=$(echo "$MODIFIED_TABLE_INPUT")
# 3. Check and Create Target Database if necessary
echo "[3/5] Checking target database '$TARGET_DB' in region '$TARGET_REGION'..."
DB_CHECK=$(aws_cmd glue get-database TARGET_REGION TARGET_PROFILE --database-name "$TARGET_DB")
if [[ $? -ne 0 || -z "$DB_CHECK" || "$(echo $DB_CHECK | jq '.Database' )" == "null" ]]; then
echo "Database '$TARGET_DB' not found. Creating database..."
# Use explicit JSON structure for create-database
DB_CREATE_JSON="{\"Name\": \"$TARGET_DB\"}"
aws_cmd glue create-database TARGET_REGION TARGET_PROFILE --database-input "$DB_CREATE_JSON"
if [[ $? -ne 0 ]]; then
echo >&2 "Error: Failed to create database '$TARGET_DB' in region '$TARGET_REGION'."
exit 1
fi
echo "Database '$TARGET_DB' created successfully."
else
echo "Database '$TARGET_DB' already exists."
fi
# 4. Check if Target Table Exists and Create or Update
echo "[4/5] Checking target table '$TARGET_DB.$TARGET_TABLE' in region '$TARGET_REGION'..."
TABLE_EXISTS_CHECK=$(aws_cmd glue get-table TARGET_REGION TARGET_PROFILE --database-name "$TARGET_DB" --table-name "$TARGET_TABLE")
if [[ $? -eq 0 && "$(echo $TABLE_EXISTS_CHECK | jq '.Table' )" != "null" ]]; then
echo "Target table '$TARGET_DB.$TARGET_TABLE' already exists."
if [[ "$OVERWRITE" = true ]]; then
echo "Overwrite flag is set. Updating table definition..."
aws_cmd glue update-table TARGET_REGION TARGET_PROFILE \
--database-name "$TARGET_DB" \
--table-name "$TARGET_TABLE" \
--table-input "$UPDATE_TABLE_INPUT_JSON"
if [[ $? -ne 0 ]]; then
echo >&2 "Error: Failed to update table '$TARGET_DB.$TARGET_TABLE' in region '$TARGET_REGION'."
exit 1
fi
echo "Table '$TARGET_DB.$TARGET_TABLE' updated successfully."
else
echo >&2 "Error: Target table '$TARGET_DB.$TARGET_TABLE' exists. Use the -o option to overwrite."
exit 1
fi
else
echo "Target table '$TARGET_DB.$TARGET_TABLE' does not exist. Creating table..."
aws_cmd glue create-table TARGET_REGION TARGET_PROFILE --cli-input-json "$CREATE_PAYLOAD"
if [[ $? -ne 0 ]]; then
echo >&2 "Error: Failed to create table '$TARGET_DB.$TARGET_TABLE' in region '$TARGET_REGION'."
exit 1
fi
echo "Table '$TARGET_DB.$TARGET_TABLE' created successfully."
fi
echo "[5/5] Migration process completed successfully!"
exit 0
How to Use:
Save: Save the script to a file, e.g., migrate_glue_table.sh.
Configure AWS Credentials: Make sure your AWS CLI is configured with credentials that have the necessary permissions (either via environment variables like AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_DEFAULT_REGION, or via an IAM role if running on EC2/ECS/etc., or using named profiles).
Example: Migrate table sales_data in database raw_db (region us-east-1) to table sales_data_processed in database processed_db (region us-west-2), pointing to a new S3 location:
Data Migration: Remember, this only copies the Glue Data Catalog definition. You need to migrate the actual data separately using tools like aws s3 sync:
bash
# Example: Sync data from old location to new location
aws s3 sync s3://source-bucket/path/to/table/ s3://target-bucket/path/to/table/ --source-region <source_region> --region <target_region>
Schema Evolution: If the schema needs to change during migration, you'll need to modify the jq command that updates MODIFIED_TABLE_INPUT.
Table Properties/Parameters: Other properties like TableType, Parameters (e.g., for Athena workgroups, SerDe properties) are copied as-is from the source. If you need to modify these, add more jq commands after fetching the SOURCE_TABLE_OBJECT.
SerDe Library: The script copies the SerDe settings. Ensure the target environment has access to the same SerDe library if it's a custom one.
Partitioning: The script correctly copies the partition key definitions. However, it does not update the PartitionKeys list within the StorageDescriptor if the partitioning scheme itself changes (e.g., adding/removing partition columns). It also doesn't re-partition the data; it just points the new table definition to the S3 location. If you partition data differently, you'll need to re-process the data and update the jq logic significantly.
Error Handling: The set -e helps, but complex failures might require more specific checks. Review the output carefully.