Skip to content

Instantly share code, notes, and snippets.

@roxsross
Last active July 8, 2025 00:08
Show Gist options
  • Save roxsross/335ca81a869d9329605f1d3dae3a1a32 to your computer and use it in GitHub Desktop.
Save roxsross/335ca81a869d9329605f1d3dae3a1a32 to your computer and use it in GitHub Desktop.
deploy portafolio codigo facilito
#!/bin/bash
# Script definitivo para desplegar web estática con Nginx
# Versión limpia y directa con colores
set -e # Salir si hay errores
# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # Sin color
echo -e "${CYAN}🚀 Desplegando web estática con Nginx...${NC}"
# Variables
URL="https://github.com/roxsross/devops-static-web/raw/portafolio-web/portafolio-web.zip"
WEB_DIR="/var/www/portafolio-web"
TEMP_ZIP="/tmp/web.zip"
# Verificar root
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}❌ Ejecuta como root: ${WHITE}sudo ./script.sh${NC}"
exit 1
fi
# 1. Actualizar sistema e instalar dependencias
echo -e "${BLUE}📦 Instalando dependencias...${NC}"
apt update -q
apt install -y nginx wget unzip curl
# 2. Descargar y extraer web
echo -e "${PURPLE}⬇️ Descargando web...${NC}"
wget -q $URL -O $TEMP_ZIP
echo -e "${YELLOW}📂 Extrayendo archivos...${NC}"
rm -rf $WEB_DIR
mkdir -p $WEB_DIR
unzip -q $TEMP_ZIP -d /tmp/extract
# 3. Copiar archivos correctamente (evitar carpetas anidadas)
echo -e "${CYAN}📋 Copiando archivos web...${NC}"
if [ -d "/tmp/extract/portafolio-web" ]; then
cp -r /tmp/extract/portafolio-web/* $WEB_DIR/
else
cp -r /tmp/extract/* $WEB_DIR/
fi
# Verificar que index.html exista
if [ ! -f "$WEB_DIR/index.html" ]; then
echo -e "${YELLOW}🔍 Buscando index.html...${NC}"
# Buscar index.html en subdirectorios y mover todo al root
INDEX_PATH=$(find $WEB_DIR -name "index.html" -type f | head -1)
if [ -n "$INDEX_PATH" ]; then
INDEX_DIR=$(dirname "$INDEX_PATH")
mv $INDEX_DIR/* $WEB_DIR/ 2>/dev/null || true
find $WEB_DIR -type d -empty -delete 2>/dev/null || true
echo -e "${GREEN}✅ index.html encontrado y reorganizado${NC}"
fi
fi
# 4. Establecer permisos
echo -e "${BLUE}🔐 Estableciendo permisos...${NC}"
chown -R www-data:www-data $WEB_DIR
chmod -R 755 $WEB_DIR
# 5. Configurar Nginx
echo -e "${PURPLE}⚙️ Configurando Nginx...${NC}"
rm -f /etc/nginx/sites-enabled/default
cat > /etc/nginx/sites-available/portafolio <<EOF
server {
listen 80 default_server;
listen [::]:80 default_server;
root $WEB_DIR;
index index.html;
server_name _;
location / {
try_files \$uri \$uri/ /index.html;
}
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public";
}
}
EOF
ln -sf /etc/nginx/sites-available/portafolio /etc/nginx/sites-enabled/
# 6. Reiniciar Nginx
echo -e "${YELLOW}🔄 Reiniciando Nginx...${NC}"
nginx -t
systemctl restart nginx
systemctl enable nginx
# 7. Configurar firewall
echo -e "${BLUE}🔥 Configurando firewall...${NC}"
ufw allow 'Nginx HTTP' 2>/dev/null || true
# 8. Limpiar temporales
echo -e "${CYAN}🧹 Limpiando archivos temporales...${NC}"
rm -f $TEMP_ZIP
rm -rf /tmp/extract
# 9. Verificar
echo -e "${PURPLE}✅ Verificando despliegue...${NC}"
sleep 2
if systemctl is-active --quiet nginx; then
echo -e "${GREEN}✅ Nginx corriendo${NC}"
else
echo -e "${RED}❌ Error con Nginx${NC}"
exit 1
fi
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
echo -e "${GREEN}✅ Sitio web respondiendo${NC}"
else
echo -e "${YELLOW}⚠️ Sitio responde con código: $HTTP_CODE${NC}"
fi
echo ""
echo -e "${WHITE}🎉 DESPLIEGUE COMPLETADO${NC}"
echo -e "${CYAN}🌐 URL: ${WHITE}http://localhost${NC}"
echo -e "${BLUE}📁 Archivos: ${WHITE}$WEB_DIR${NC}"
echo ""
echo -e "${GREEN}Archivos desplegados:${NC}"
ls -la $WEB_DIR
exit 0
#!/bin/bash
set -e # Salir si hay errores
echo "🚀 Desplegando web estática con Nginx..."
# Variables
URL="https://github.com/roxsross/devops-static-web/raw/portafolio-web/portafolio-web.zip"
WEB_DIR="/var/www/portafolio-web"
TEMP_ZIP="/tmp/web.zip"
# Verificar root
if [[ $EUID -ne 0 ]]; then
echo "❌ Ejecuta como root: sudo ./script.sh"
exit 1
fi
# 1. Actualizar sistema e instalar dependencias
echo "📦 Instalando dependencias..."
apt update -q
apt install -y nginx wget unzip curl
# 2. Descargar y extraer web
echo "⬇️ Descargando web..."
wget -q $URL -O $TEMP_ZIP
echo "📂 Extrayendo archivos..."
rm -rf $WEB_DIR
mkdir -p $WEB_DIR
unzip -q $TEMP_ZIP -d /tmp/extract
# 3. Copiar archivos correctamente (evitar carpetas anidadas)
echo "📋 Copiando archivos web..."
if [ -d "/tmp/extract/portafolio-web" ]; then
cp -r /tmp/extract/portafolio-web/* $WEB_DIR/
else
cp -r /tmp/extract/* $WEB_DIR/
fi
# Verificar que index.html exista
if [ ! -f "$WEB_DIR/index.html" ]; then
# Buscar index.html en subdirectorios y mover todo al root
INDEX_PATH=$(find $WEB_DIR -name "index.html" -type f | head -1)
if [ -n "$INDEX_PATH" ]; then
INDEX_DIR=$(dirname "$INDEX_PATH")
mv $INDEX_DIR/* $WEB_DIR/ 2>/dev/null || true
find $WEB_DIR -type d -empty -delete 2>/dev/null || true
fi
fi
# 4. Establecer permisos
chown -R www-data:www-data $WEB_DIR
chmod -R 755 $WEB_DIR
# 5. Configurar Nginx
echo "⚙️ Configurando Nginx..."
rm -f /etc/nginx/sites-enabled/default
cat > /etc/nginx/sites-available/portafolio <<EOF
server {
listen 80 default_server;
listen [::]:80 default_server;
root $WEB_DIR;
index index.html;
server_name _;
location / {
try_files \$uri \$uri/ /index.html;
}
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public";
}
}
EOF
ln -sf /etc/nginx/sites-available/portafolio /etc/nginx/sites-enabled/
# 6. Reiniciar Nginx
echo "🔄 Reiniciando Nginx..."
nginx -t
systemctl restart nginx
systemctl enable nginx
# 7. Configurar firewall
ufw allow 'Nginx HTTP' 2>/dev/null || true
# 8. Limpiar temporales
rm -f $TEMP_ZIP
rm -rf /tmp/extract
# 9. Verificar
echo "✅ Verificando despliegue..."
sleep 2
if systemctl is-active --quiet nginx; then
echo "✅ Nginx corriendo"
else
echo "❌ Error con Nginx"
exit 1
fi
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
echo "✅ Sitio web respondiendo"
else
echo "⚠️ Sitio responde con código: $HTTP_CODE"
fi
echo ""
echo "🎉 DESPLIEGUE COMPLETADO"
echo "🌐 URL: http://localhost"
echo "📁 Archivos: $WEB_DIR"
echo ""
echo "Archivos desplegados:"
ls -la $WEB_DIR
exit 0
# =============================================================================
# TERRAFORM
# =============================================================================
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.4"
}
}
}
# -----------------------------------------------------------------------------
# ARCHIVO HTML - LA PÁGINA WEB PRINCIPAL
# -----------------------------------------------------------------------------
resource "local_file" "pagina_principal" {
filename = "./mi-sitio-web/index.html"
content = <<-EOF
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mi Primera Web con Terraform</title>
<link rel="stylesheet" href="estilos.css">
</head>
<body>
<div class="container">
<header>
<h1>🚀 ¡Mi Primera Web con Terraform!</h1>
<p>Esta página fue creada automáticamente</p>
</header>
<main>
<div class="info-box">
<h2>✅ ¡Terraform funcionó!</h2>
<p>Si puedes ver esta página, significa que:</p>
<ul>
<li>✓ Terraform creó los archivos correctamente</li>
<li>✓ Tu primera infraestructura como código está funcionando</li>
<li>✓ Estás listo para el siguiente nivel</li>
</ul>
</div>
<div class="actions">
<button onclick="mostrarMensaje()">
🎉 ¡Hacer clic aquí!
</button>
</div>
<div class="stats">
<h3>📊 Información:</h3>
<p><strong>Herramienta:</strong> Terraform</p>
<p><strong>Provider:</strong> local</p>
<p><strong>Estado:</strong> ¡Funcionando!</p>
</div>
</main>
<footer>
<p>Hecho con ❤️ y Terraform</p>
</footer>
</div>
<script src="script.js"></script>
</body>
</html>
EOF
file_permission = "0644"
}
# -----------------------------------------------------------------------------
# ARCHIVO CSS - ESTILOS
# -----------------------------------------------------------------------------
resource "local_file" "archivo_css" {
filename = "./mi-sitio-web/estilos.css"
content = <<-EOF
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #333;
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 15px;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
overflow: hidden;
animation: slideIn 0.6s ease-out;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
header {
background: linear-gradient(45deg, #2196F3, #21CBF3);
color: white;
text-align: center;
padding: 40px 20px;
}
header h1 {
font-size: 2.5em;
margin-bottom: 10px;
text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}
main {
padding: 40px;
}
.info-box {
background: #f8f9fa;
border-left: 5px solid #28a745;
padding: 20px;
margin-bottom: 30px;
border-radius: 5px;
}
.info-box h2 {
color: #28a745;
margin-bottom: 15px;
}
.info-box ul {
margin-left: 20px;
}
.info-box li {
margin-bottom: 5px;
}
.actions {
text-align: center;
margin: 30px 0;
}
button {
background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
color: white;
border: none;
padding: 15px 30px;
font-size: 18px;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}
.stats {
background: #e9ecef;
padding: 20px;
border-radius: 10px;
margin-top: 20px;
}
.stats h3 {
color: #495057;
margin-bottom: 10px;
}
footer {
background: #343a40;
color: white;
text-align: center;
padding: 20px;
}
@media (max-width: 600px) {
body {
padding: 10px;
}
header h1 {
font-size: 2em;
}
main {
padding: 20px;
}
}
EOF
file_permission = "0644"
}
# -----------------------------------------------------------------------------
# ARCHIVO JAVASCRIPT - SIMPLE Y SIN CONFLICTOS
# -----------------------------------------------------------------------------
resource "local_file" "archivo_js" {
filename = "./mi-sitio-web/script.js"
content = <<-EOF
// JavaScript simple para principiantes
console.log('🎉 ¡Terraform creó esta página correctamente!');
// Función que se ejecuta cuando haces clic en el botón
function mostrarMensaje() {
const mensajes = [
'🎊 ¡Felicidades! Acabas de usar Terraform',
'🚀 ¡Tu primera infraestructura como código funciona!',
'💡 Terraform puede crear mucho más que páginas web',
'🔧 Ahora sabes usar: resources, providers y archivos',
'⭐ ¡Estás listo para proyectos más avanzados!'
];
const mensaje = mensajes[Math.floor(Math.random() * mensajes.length)];
alert(mensaje);
console.log('Mensaje mostrado:', mensaje);
}
// Función que muestra información en la consola
function mostrarInfoTerraform() {
console.log('📋 Información de Terraform:');
console.log('- Herramienta: Infrastructure as Code');
console.log('- Provider usado: local');
console.log('- Archivos creados: HTML, CSS, JS');
console.log('- Comando usado: terraform apply');
}
// Ejecutar cuando la página termine de cargar
document.addEventListener('DOMContentLoaded', function() {
console.log('📄 Página cargada completamente');
mostrarInfoTerraform();
// Cambiar el título de la página cada 5 segundos
let contador = 0;
const titulos = [
'Mi Primera Web con Terraform',
'🚀 Terraform en Acción',
'⚡ Infrastructure as Code',
'🎯 ¡Funcionando Perfectamente!'
];
setInterval(function() {
contador = (contador + 1) % titulos.length;
document.title = titulos[contador];
}, 5000);
// Agregar efectos al botón
const boton = document.querySelector('button');
if (boton) {
boton.addEventListener('mouseenter', function() {
this.style.transform = 'scale(1.05)';
});
boton.addEventListener('mouseleave', function() {
this.style.transform = 'scale(1)';
});
}
});
// Función para mostrar estadísticas básicas
function mostrarEstadisticas() {
const ahora = new Date();
const stats = {
'Hora actual': ahora.toLocaleString(),
'Navegador': navigator.userAgent.split(' ').pop(),
'Idioma': navigator.language,
'Ancho pantalla': screen.width,
'Alto pantalla': screen.height
};
console.table(stats);
return stats;
}
// Ejecutar estadísticas después de 2 segundos
setTimeout(mostrarEstadisticas, 2000);
EOF
file_permission = "0644"
}
# -----------------------------------------------------------------------------
# SCRIPT PARA ABRIR LA PÁGINA
# -----------------------------------------------------------------------------
resource "local_file" "script_abrir" {
filename = "./abrir-mi-web.sh"
content = <<-EOF
#!/bin/bash
echo "🌐 Abriendo tu página web creada con Terraform..."
echo ""
if [ ! -f "./mi-sitio-web/index.html" ]; then
echo "❌ Error: No se encontró el archivo index.html"
echo " ¿Ejecutaste 'terraform apply'?"
exit 1
fi
echo "✅ Archivos encontrados:"
ls -la ./mi-sitio-web/
echo ""
RUTA_COMPLETA=$(pwd)/mi-sitio-web/index.html
echo "📁 Ubicación: file://$RUTA_COMPLETA"
echo ""
echo "🎉 ¡Tu primera página web con Terraform está lista!"
EOF
file_permission = "0755"
}
# -----------------------------------------------------------------------------
# OUTPUTS
# -----------------------------------------------------------------------------
output "felicitaciones" {
value = "🎉 ¡Terraform creó tu página web exitosamente!"
}
output "archivos_creados" {
value = [
"./mi-sitio-web/index.html",
"./mi-sitio-web/estilos.css",
"./mi-sitio-web/script.js",
"./abrir-mi-web.sh"
]
}
output "como_ver_la_web" {
value = "Ejecuta: ./abrir-mi-web.sh"
}
output "comandos_utiles" {
value = {
ver_archivos = "ls -la ./mi-sitio-web/"
abrir_web = "./abrir-mi-web.sh"
validar = "terraform validate"
destruir = "terraform destroy"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment