Okay, let's break down how to add a "RETENTION=90" tag to all new files synced to an S3 bucket using inotifywait and aws s3 sync. Here's a comprehensive approach, including code examples, explanations, and considerations for robustness.
Core Strategy
inotifywait for File Creation: We'll use inotifywait to monitor the directory where your files are being synced. It will trigger when a new file is created.
aws s3 sync with Tagging: We'll modify the aws s3 sync command to include the --tag-value option to add the "RETENTION=90" tag to the uploaded files.
- Error Handling: Implement error handling to gracefully manage potential issues during the sync process.
- Idempotency: Ensure the script doesn't repeatedly tag files if it encounters issues.
Code Example (Bash)
#!/bin/bash
# Configuration
SOURCE_DIR="/path/to/your/local/files" # Replace with your local directory
S3_BUCKET="your-s3-bucket-name" # Replace with your S3 bucket name
S3_PREFIX="your/s3/prefix/" # Optional: Prefix for files in S3
AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY" # Replace with your AWS access key ID
AWS_SECRET_ACCESS_KEY="YOUR_SECRET_KEY" # Replace with your AWS secret access key
REGION="your-aws-region" # e.g., us-east-1
# Tag Value
RETENTION_VALUE="90"
# Function to tag files in S3
tag_s3_file() {
local file_path="$1"
local file_name=$(basename "$file_path")
echo "Tagging file: $file_path"
aws s3api put-object-tagging \
--bucket "$S3_BUCKET" \
--key "$file_name" \
--tags "RETENTION=$RETENTION_VALUE" \
--region "$REGION"
}
# Main loop
while inotifywait -r -e create "$SOURCE_DIR"; do
new_file="$1"
echo "New file detected: $new_file"
# Wait a short time to ensure the file is fully written
sleep 1
# Sync the file to S3 with tagging
aws s3 sync "$SOURCE_DIR" "s3://$S3_BUCKET$S3_PREFIX" --tag-value "RETENTION=$RETENTION_VALUE" --region "$REGION" --exclude "*" --include "*"
if [ $? -eq 0 ]; then
echo "File $new_file synced to S3 and tagged successfully."
else
echo "Error syncing file $new_file to S3. Retrying..."
# You might want to add a retry mechanism here with a delay.
fi
# Remove the file from the local directory after successful sync
rm -f "$new_file"
done
Explanation:
- Configuration: The script starts with configuration variables. Crucially, replace the placeholder values with your actual settings.
tag_s3_file Function: This function encapsulates the aws s3api put-object-tagging command. It takes the file path as input and adds the "RETENTION=$RETENTION_VALUE" tag to the corresponding S3 object.
inotifywait Loop:
inotifywait -r -e create "$SOURCE_DIR": This monitors the specified directory ($SOURCE_DIR) recursively (-r) for create events. It will continuously wait for new files to be created.
new_file="$1": The first argument passed by inotifywait (the path to the new file) is stored in the new_file variable.
sleep 1: A short delay is added to ensure the file is fully written to disk before attempting to sync it. This is important to avoid syncing incomplete files.
aws s3 sync ...: This is the core command that syncs the file to S3 and adds the tag.
"$SOURCE_DIR": The local source directory.
"s3://$S3_BUCKET$S3_PREFIX": The S3 destination path. The $S3_PREFIX allows you to specify a folder structure within your bucket.
--tag-value "RETENTION=$RETENTION_VALUE": This is the key part! It adds the tag "RETENTION=90" to the uploaded object.
--region "$REGION": Specifies the AWS region.
--exclude "*" --include "*": This ensures that all files are synced.
- Error Handling: The
$? variable contains the exit code of the previous command. If it's 0, the command was successful. If it's non-zero, an error occurred. The script prints an error message and you can add retry logic.
rm -f "$new_file": After a successful sync, the local file is deleted. This prevents the script from repeatedly syncing the same file if it's modified.
How to Use:
- Install Dependencies:
- Configure AWS Credentials:
- The easiest way is to configure the AWS CLI with your credentials using
aws configure. This will store your access key ID, secret access key, default region, and output format.
- Replace Placeholders: Edit the script and replace the placeholder values for
SOURCE_DIR, S3_BUCKET, S3_PREFIX, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and REGION with your actual values.
- Make the Script Executable:
chmod +x your_script_name.sh
- Run the Script:
./your_script_name.sh
Important Considerations and Enhancements:
- Error Handling and Retries: The current error handling is basic. You should implement a more robust retry mechanism with exponential backoff to handle transient errors (e.g., network issues, temporary S3 unavailability).
- File Modification Detection: The script currently deletes the local file after a successful sync. If a file is modified locally after the initial sync, it will be synced again. You could add a modification time check to avoid unnecessary syncs. You can use
stat -c %Y to get the last modification time.
- Large Files: For very large files, consider using multipart uploads with the AWS CLI to improve performance and reliability. The
--multipart-chunk-size option can be helpful.
- Concurrency: If you have a high volume of files being added, you might want to consider using a more sophisticated approach with multiple
inotifywait instances or a message queue to handle the workload.
- Logging: Add more detailed logging to help troubleshoot issues. Log the file names, timestamps, and any errors that occur.
- Permissions: Ensure that the AWS credentials you are using have the necessary permissions to write to the S3 bucket. Specifically, you need
s3:PutObject permission.
- Security: Never hardcode your AWS credentials directly in the script. Use environment variables or a secure configuration file to store them.
- Idempotency: The script is mostly idempotent, but if the script is interrupted mid-way, it might leave files in an inconsistent state. Consider adding a mechanism to check for existing tags before adding new ones.
- File Type Filtering: You might want to add filtering to only tag certain file types. You can use the
--include and --exclude options with aws s3 sync to achieve this.
Example of Modification Time Check:
#!/bin/bash
# ... (Configuration as before) ...
# Function to tag files in S3
tag_s3_file() {
local file_path="$1"
local file_name=$(basename "$file_path")
# Check if the file has been modified since the last sync
local last_modified=$(stat -c %Y "$file_path")
local last_sync_time=$(find /path/to/your/sync/directory -name "$file_name" -printf '%T@\n' | sort -n | tail -1)
if [ "$last_modified" -gt "$last_sync_time" ]; then