Lo que aprenderas en este tutorial
- Conceptos basicos de S3 (buckets, objetos, regiones)
- Creacion y gestion de buckets
- Subida y descarga de objetos
- Control de acceso (IAM, politicas de bucket)
- Alojamiento de sitios web estaticos
- Operaciones con AWS CLI/SDK
Que es Amazon S3
Amazon S3 (Simple Storage Service) es un servicio de almacenamiento de objetos proporcionado por AWS. Con una durabilidad del 99.999999999% (once nueves), puedes almacenar de forma segura cualquier tipo de datos como imagenes, videos y copias de seguridad.
Caracteristicas de S3
| Caracteristica | Descripcion |
|---|---|
| Escalabilidad | Capacidad ilimitada con escalado automatico |
| Durabilidad | 99.999999999% de durabilidad |
| Disponibilidad | 99.99% de disponibilidad (clase Standard) |
| Eficiencia de costos | Pago por uso |
| Seguridad | Cifrado y control de acceso completos |
Requisitos previos
- Cuenta de AWS
- AWS CLI instalado
Step 1: Configuracion de AWS CLI
Primero, instala AWS CLI y configura las credenciales.
# Instalacion de AWS CLI (macOS)
brew install awscli
# Instalacion de AWS CLI (Linux)
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
# Verificar instalacion
aws --version
# aws-cli/2.x.x Python/3.x.x ...
Configura las credenciales. Emite una clave de acceso desde la consola de IAM.
# Configurar credenciales
aws configure
# AWS Access Key ID: YOUR_ACCESS_KEY
# AWS Secret Access Key: YOUR_SECRET_KEY
# Default region name: ap-northeast-1
# Default output format: json
# Verificar configuracion
aws sts get-caller-identity
# {
# "UserId": "AIDAXXXXXXXXXXXXXXXXX",
# "Account": "123456789012",
# "Arn": "arn:aws:iam::123456789012:user/your-user"
# }
Step 2: Creacion de buckets
Los nombres de buckets en S3 deben ser unicos globalmente.
# Crear bucket (region Tokyo)
aws s3 mb s3://my-tutorial-bucket-2024 --region ap-northeast-1
# Verificar lista de buckets
aws s3 ls
# 2024-12-20 10:00:00 my-tutorial-bucket-2024
Reglas de nomenclatura de buckets
- 3 a 63 caracteres
- Solo minusculas, numeros y guiones
- Debe empezar y terminar con alfanumerico
- No se permiten guiones consecutivos
- No se permite formato de direccion IP
# Verificar detalles del bucket especificando region
aws s3api get-bucket-location --bucket my-tutorial-bucket-2024
# {
# "LocationConstraint": "ap-northeast-1"
# }
Step 3: Operaciones con objetos
Subida
# Subir un archivo individual
aws s3 cp local-file.txt s3://my-tutorial-bucket-2024/
# Subir a una ruta especifica (prefijo)
aws s3 cp local-file.txt s3://my-tutorial-bucket-2024/documents/
# Subir directorio completo (recursivo)
aws s3 cp ./local-folder s3://my-tutorial-bucket-2024/folder/ --recursive
# Verificar subida
aws s3 ls s3://my-tutorial-bucket-2024/
# 2024-12-20 10:05:00 1234 local-file.txt
Descarga
# Descargar un archivo individual
aws s3 cp s3://my-tutorial-bucket-2024/file.txt ./downloaded-file.txt
# Descargar directorio completo
aws s3 cp s3://my-tutorial-bucket-2024/folder/ ./local-folder/ --recursive
Sincronizacion (sync)
El comando sync transfiere solo las diferencias, por lo que es eficiente.
# Sincronizar local → S3
aws s3 sync ./local-folder s3://my-tutorial-bucket-2024/folder/
# Sincronizar S3 → local
aws s3 sync s3://my-tutorial-bucket-2024/folder/ ./local-folder/
# Reflejar archivos eliminados (opcion --delete)
aws s3 sync ./local-folder s3://my-tutorial-bucket-2024/folder/ --delete
# Excluir archivos especificos
aws s3 sync ./local-folder s3://my-tutorial-bucket-2024/folder/ \
--exclude "*.log" \
--exclude ".git/*"
Eliminacion
# Eliminar un objeto individual
aws s3 rm s3://my-tutorial-bucket-2024/file.txt
# Eliminar todo bajo un prefijo (recursivo)
aws s3 rm s3://my-tutorial-bucket-2024/folder/ --recursive
# Eliminar todo el contenido del bucket
aws s3 rm s3://my-tutorial-bucket-2024 --recursive
# Eliminar el bucket (debe estar vacio)
aws s3 rb s3://my-tutorial-bucket-2024
# Eliminar bucket forzadamente (incluyendo contenido)
aws s3 rb s3://my-tutorial-bucket-2024 --force
Step 4: Control de acceso
Existen multiples metodos para el control de acceso en S3.
Politica de bucket
Las politicas de bucket definen permisos de acceso en formato JSON.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadForGetBucketObjects",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/public/*"
}
]
}
# Aplicar politica de bucket
aws s3api put-bucket-policy \
--bucket my-tutorial-bucket-2024 \
--policy file://bucket-policy.json
# Verificar politica de bucket
aws s3api get-bucket-policy --bucket my-tutorial-bucket-2024
# Eliminar politica de bucket
aws s3api delete-bucket-policy --bucket my-tutorial-bucket-2024
Bloqueo de acceso publico
Por seguridad, el acceso publico esta bloqueado por defecto.
# Verificar configuracion de bloqueo de acceso publico
aws s3api get-public-access-block --bucket my-tutorial-bucket-2024
# Configurar bloqueo de acceso publico
aws s3api put-public-access-block \
--bucket my-tutorial-bucket-2024 \
--public-access-block-configuration \
"BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
URL prefirmada (Presigned URL)
Puedes generar URLs que permiten acceso temporal a objetos.
# Generar URL prefirmada valida por 1 hora (para descarga)
aws s3 presign s3://my-tutorial-bucket-2024/private-file.txt --expires-in 3600
# Ejemplo de salida:
# https://my-tutorial-bucket-2024.s3.amazonaws.com/private-file.txt?...
Step 5: Alojamiento de sitios web estaticos
Puedes publicar archivos estaticos como HTML en S3.
# Habilitar alojamiento de sitio web estatico
aws s3 website s3://my-website-bucket \
--index-document index.html \
--error-document error.html
Ejemplo de index.html
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Alojamiento estatico en S3</title>
</head>
<body>
<h1>Hola desde S3!</h1>
<p>Esta pagina esta alojada en Amazon S3.</p>
</body>
</html>
# Subir archivos
aws s3 cp index.html s3://my-website-bucket/
aws s3 cp error.html s3://my-website-bucket/
# Especificar Content-Type explicitamente
aws s3 cp index.html s3://my-website-bucket/ --content-type "text/html"
Configura la politica de bucket para publicacion.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-website-bucket/*"
}
]
}
Endpoint del sitio web:
http://my-website-bucket.s3-website-ap-northeast-1.amazonaws.com
Step 6: Operaciones con SDK (JavaScript)
Ejemplo de operacion de S3 desde Node.js.
# Instalacion de AWS SDK v3
npm install @aws-sdk/client-s3
// s3-example.js
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
ListObjectsV2Command
} from '@aws-sdk/client-s3';
// Inicializacion del cliente S3
const s3Client = new S3Client({ region: 'ap-northeast-1' });
// Subir objeto
async function uploadFile(bucket, key, body) {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: body,
ContentType: 'text/plain',
});
const response = await s3Client.send(command);
console.log('Upload successful:', response);
return response;
}
// Obtener objeto
async function getFile(bucket, key) {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
});
const response = await s3Client.send(command);
// Convertir stream a string
const body = await response.Body.transformToString();
return body;
}
// Obtener lista de objetos
async function listFiles(bucket, prefix = '') {
const command = new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
});
const response = await s3Client.send(command);
return response.Contents || [];
}
// Ejemplo de ejecucion
const bucket = 'my-tutorial-bucket-2024';
await uploadFile(bucket, 'test.txt', 'Hello, S3!');
const content = await getFile(bucket, 'test.txt');
console.log('Content:', content);
const files = await listFiles(bucket);
files.forEach(file => console.log(file.Key, file.Size));
Clases de almacenamiento
Puedes seleccionar la clase de almacenamiento apropiada segun el uso.
| Clase | Uso | Tiempo de recuperacion |
|---|---|---|
| Standard | Datos de acceso frecuente | Inmediato |
| Intelligent-Tiering | Patron de acceso desconocido | Inmediato |
| Standard-IA | Acceso poco frecuente | Inmediato |
| Glacier Instant | Archivo (recuperacion inmediata) | Inmediato |
| Glacier Flexible | Archivo | Minutos a horas |
| Glacier Deep Archive | Archivo a largo plazo | 12 horas |
# Subir especificando clase de almacenamiento
aws s3 cp file.txt s3://my-bucket/ --storage-class STANDARD_IA
Resumen
AWS S3 es un almacenamiento de objetos escalable y de alta durabilidad. Puntos principales:
- Bucket: Contenedor para almacenar datos (nombre unico global)
- Objeto: Combinacion de archivo y metadatos
- Control de acceso: Configuracion detallada con IAM, politicas de bucket, ACL
- Alojamiento estatico: Publicacion simple de sitios web
- Clases de almacenamiento: Seleccion del equilibrio entre costo y tiempo de recuperacion
Enlaces de referencia
- Documentacion oficial de Amazon S3
- Referencia de comandos S3 de AWS CLI
- AWS SDK for JavaScript v3
- Precios de S3