Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Aviso importante

Los ejemplos de código y scripts proporcionados en estos tutoriales son solo para propósitos educativos. Macfleet no es responsable de ningún problema, daño o vulnerabilidad de seguridad que pueda surgir del uso, modificación o implementación de estos ejemplos. Siempre revisa y prueba el código en un entorno seguro antes de usarlo en sistemas de producción.

Guest User Management on macOS

Manage guest user accounts and secure temporary access across your MacFleet devices using advanced guest user management systems. This tutorial covers guest account configuration, security policies, access monitoring, and comprehensive guest lifecycle management.

Understanding macOS Guest User Management

macOS provides guest user functionality for temporary, secure access:

  • defaults - System preferences and configuration management
  • Guest User Account - Temporary access without authentication
  • Secure Sandbox - Isolated environment for guest sessions
  • Automatic Cleanup - Session data removal on logout
  • Access Controls - Restrictions and permissions management

Basic Guest User Operations

Enable Guest User Account

#!/bin/bash

# Basic guest user enablement
defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool TRUE

echo "Guest user account enabled successfully"

Enhanced Guest User Configuration

#!/bin/bash

# Comprehensive guest user configuration with security settings
configure_guest_user() {
    echo "=== Comprehensive Guest User Configuration ==="
    
    # Enable guest user
    echo "Enabling guest user account..."
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool TRUE
    
    # Configure guest user restrictions
    echo "Configuring guest user security settings..."
    
    # Disable guest user from making system changes
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestAllowedToChangeNetwork -bool FALSE
    
    # Set guest user home folder restrictions
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestHomeIsSeparateDisk -bool TRUE
    
    # Configure automatic logout
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestAutoLogout -int 3600
    
    # Disable guest user from accessing encrypted volumes
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestCanAccessEncryptedVolumes -bool FALSE
    
    echo "Guest user configuration completed"
}

# Execute comprehensive configuration
configure_guest_user

Guest User Categories

Guest Access Classifications

#!/bin/bash

# Guest user categories for different organizational needs
declare -A GUEST_USER_CATEGORIES=(
    ["lobby_kiosk"]="Public lobby access for visitors and information browsing"
    ["conference_room"]="Meeting room access for presentations and collaboration"
    ["library_station"]="Educational institution public access terminals"
    ["demo_showcase"]="Product demonstration and sales presentation stations"
    ["visitor_workstation"]="Temporary workstations for business visitors"
    ["event_registration"]="Event check-in and registration terminals"
    ["customer_service"]="Customer service and support terminals"
    ["training_lab"]="Training and workshop temporary access"
    ["public_wifi_portal"]="Public WiFi access and terms acceptance"
    ["emergency_access"]="Emergency access stations for staff use"
)

# Security levels for guest access
declare -A SECURITY_LEVELS=(
    ["lobby_kiosk"]="high_restriction"
    ["conference_room"]="medium_restriction"
    ["library_station"]="medium_restriction"
    ["demo_showcase"]="low_restriction"
    ["visitor_workstation"]="high_restriction"
    ["event_registration"]="medium_restriction"
    ["customer_service"]="high_restriction"
    ["training_lab"]="low_restriction"
    ["public_wifi_portal"]="maximum_restriction"
    ["emergency_access"]="minimal_restriction"
)

# Session duration limits
declare -A SESSION_LIMITS=(
    ["lobby_kiosk"]="1800"      # 30 minutes
    ["conference_room"]="10800"  # 3 hours
    ["library_station"]="7200"   # 2 hours
    ["demo_showcase"]="3600"     # 1 hour
    ["visitor_workstation"]="14400" # 4 hours
    ["event_registration"]="900"  # 15 minutes
    ["customer_service"]="1800"   # 30 minutes
    ["training_lab"]="21600"     # 6 hours
    ["public_wifi_portal"]="300"  # 5 minutes
    ["emergency_access"]="unlimited"
)

print_guest_categories() {
    echo "=== Guest User Categories ==="
    for category in "${!GUEST_USER_CATEGORIES[@]}"; do
        echo "Category: $category"
        echo "  Description: ${GUEST_USER_CATEGORIES[$category]}"
        echo "  Security Level: ${SECURITY_LEVELS[$category]}"
        echo "  Session Limit: ${SESSION_LIMITS[$category]} seconds"
        echo ""
    done
}

# Display available categories
print_guest_categories

Guest User Policies

Access Policy Engine

#!/bin/bash

# Guest user management policies for different security requirements
declare -A GUEST_POLICIES=(
    ["public_access_secure"]="Secure public access with maximum restrictions"
    ["business_visitor_standard"]="Standard business visitor access with monitoring"
    ["educational_open"]="Educational environment with learning-focused access"
    ["demo_presentation"]="Demonstration and presentation optimized access"
    ["emergency_minimal"]="Emergency access with minimal restrictions"
    ["compliance_strict"]="Strict compliance with full audit and monitoring"
)

# Policy configurations
get_guest_policy() {
    local policy_type="$1"
    
    case "$policy_type" in
        "public_access_secure")
            cat << EOF
{
    "guest_enabled": true,
    "session_timeout": 1800,
    "network_access": false,
    "file_downloads": false,
    "usb_access": false,
    "printing_allowed": false,
    "applications_allowed": ["Safari", "TextEdit", "Preview"],
    "system_preferences_access": false,
    "auto_logout_enabled": true,
    "session_monitoring": "comprehensive",
    "data_retention": "none",
    "audit_logging": "detailed",
    "password_protection": false,
    "screen_sharing_disabled": true,
    "remote_management_disabled": true
}
EOF
            ;;
        "business_visitor_standard")
            cat << EOF
{
    "guest_enabled": true,
    "session_timeout": 14400,
    "network_access": true,
    "file_downloads": true,
    "usb_access": false,
    "printing_allowed": true,
    "applications_allowed": ["Safari", "TextEdit", "Preview", "Mail", "Calendar"],
    "system_preferences_access": false,
    "auto_logout_enabled": true,
    "session_monitoring": "standard",
    "data_retention": "session_only",
    "audit_logging": "standard",
    "password_protection": false,
    "screen_sharing_disabled": true,
    "remote_management_disabled": true,
    "file_sharing_restrictions": true
}
EOF
            ;;
        "compliance_strict")
            cat << EOF
{
    "guest_enabled": true,
    "session_timeout": 3600,
    "network_access": true,
    "file_downloads": false,
    "usb_access": false,
    "printing_allowed": false,
    "applications_allowed": ["Safari"],
    "system_preferences_access": false,
    "auto_logout_enabled": true,
    "session_monitoring": "comprehensive",
    "data_retention": "none",
    "audit_logging": "comprehensive",
    "password_protection": false,
    "screen_sharing_disabled": true,
    "remote_management_disabled": true,
    "compliance_frameworks": ["hipaa", "gdpr", "sox"],
    "data_encryption": "required",
    "access_logging": "detailed",
    "session_recording": "enabled"
}
EOF
            ;;
        *)
            echo "Unknown guest policy: $policy_type"
            return 1
            ;;
    esac
}

# Apply guest user policy
apply_guest_policy() {
    local policy="$1"
    local config_file="/tmp/guest_policy.json"
    
    echo "Applying guest user policy: $policy"
    
    get_guest_policy "$policy" > "$config_file"
    
    if [[ ! -f "$config_file" ]]; then
        echo "❌ Failed to generate policy configuration"
        return 1
    fi
    
    echo "✅ Guest user policy applied successfully"
    echo "Configuration: $config_file"
    
    # Display key policy settings
    echo "=== Policy Summary ==="
    echo "Guest Enabled: $(jq -r '.guest_enabled' "$config_file")"
    echo "Session Timeout: $(jq -r '.session_timeout' "$config_file") seconds"
    echo "Network Access: $(jq -r '.network_access' "$config_file")"
    echo "Session Monitoring: $(jq -r '.session_monitoring' "$config_file")"
    echo "Audit Logging: $(jq -r '.audit_logging' "$config_file")"
    
    # Apply actual guest settings
    apply_guest_settings "$config_file"
    
    return 0
}

# Apply guest settings
apply_guest_settings() {
    local config_file="$1"
    
    echo "Applying guest user settings..."
    
    # Extract settings from JSON
    local guest_enabled
    guest_enabled=$(jq -r '.guest_enabled' "$config_file")
    local session_timeout
    session_timeout=$(jq -r '.session_timeout' "$config_file")
    local auto_logout
    auto_logout=$(jq -r '.auto_logout_enabled' "$config_file")
    
    # Apply guest user settings
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool "$guest_enabled"
    
    if [[ "$auto_logout" == "true" ]]; then
        sudo defaults write /Library/Preferences/com.apple.loginwindow GuestAutoLogout -int "$session_timeout"
    fi
    
    echo "✅ Guest settings applied successfully"
}

Advanced Guest User Monitoring

Guest Session Analytics

#!/bin/bash

# Comprehensive guest session monitoring and analytics
monitor_guest_sessions() {
    local monitoring_profile="$1"
    local session_report="/tmp/guest_session_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Guest Session Monitoring ==="
    echo "Monitoring Profile: $monitoring_profile"
    
    # Initialize session report
    cat > "$session_report" << EOF
{
    "monitoring_profile": "$monitoring_profile",
    "scan_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "guest_status": {},
    "active_sessions": [],
    "session_analytics": {}
}
EOF
    
    # Check guest user status
    echo "Checking guest user status..."
    local guest_enabled
    guest_enabled=$(defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo "false")
    
    local guest_auto_logout
    guest_auto_logout=$(defaults read /Library/Preferences/com.apple.loginwindow GuestAutoLogout 2>/dev/null || echo "0")
    
    # Check for active guest sessions
    echo "Analyzing active sessions..."
    local active_users
    active_users=$(who | grep -v "^$USER" | wc -l | tr -d ' ')
    
    local guest_sessions
    guest_sessions=$(who | grep "Guest" | wc -l | tr -d ' ')
    
    # Monitor session activity
    echo "Monitoring session activity..."
    local login_history
    login_history=$(last | grep "Guest" | head -10)
    
    # Update session report
    jq --arg guest_enabled "$guest_enabled" \
       --argjson guest_auto_logout "$guest_auto_logout" \
       --argjson active_users "$active_users" \
       --argjson guest_sessions "$guest_sessions" \
       '.guest_status = {
          "enabled": ($guest_enabled == "1"),
          "auto_logout_seconds": $guest_auto_logout,
          "active_users": $active_users,
          "active_guest_sessions": $guest_sessions
        }' "$session_report" > "${session_report}.tmp" && mv "${session_report}.tmp" "$session_report"
    
    # Session analytics
    local total_guest_logins
    total_guest_logins=$(last | grep "Guest" | wc -l | tr -d ' ')
    
    local avg_session_duration="unknown"
    if [[ $total_guest_logins -gt 0 ]]; then
        # Calculate average session duration (simplified)
        avg_session_duration="estimated"
    fi
    
    # Display results
    echo ""
    echo "Guest Session Analysis Results:"
    echo "  Guest User Enabled: $([ "$guest_enabled" = "1" ] && echo "✅ YES" || echo "❌ NO")"
    echo "  Auto Logout: ${guest_auto_logout} seconds"
    echo "  Active Users: $active_users"
    echo "  Active Guest Sessions: $guest_sessions"
    echo "  Total Guest Logins (recent): $total_guest_logins"
    echo "  Average Session Duration: $avg_session_duration"
    echo "  Session Report: $session_report"
    
    # Log monitoring activity
    audit_log "Guest session monitoring completed: $monitoring_profile"
    
    return 0
}

Guest User Management System

#!/bin/bash

# MacFleet Guest User Management System
# Comprehensive guest access control, monitoring, and security

# Configuration
CONFIG_DIR="/etc/macfleet/guest"
LOG_FILE="/var/log/macfleet_guest_management.log"
DATA_DIR="/var/data/macfleet/guest"
REPORTS_DIR="/var/reports/macfleet/guest"
AUDIT_LOG="/var/log/macfleet_guest_audit.log"

# Create required directories
create_directories() {
    local directories=("$CONFIG_DIR" "$DATA_DIR" "$REPORTS_DIR")
    
    for dir in "${directories[@]}"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            sudo chmod 755 "$dir"
        fi
    done
}

# Logging functions
log_action() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $1" | tee -a "$LOG_FILE"
}

log_error() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
}

audit_log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [AUDIT] $1" | tee -a "$AUDIT_LOG"
}

# Guest user security enforcement
enforce_guest_security() {
    local security_level="$1"
    
    log_action "Enforcing guest security level: $security_level"
    
    echo "=== Guest User Security Enforcement ==="
    echo "Security Level: $security_level"
    
    case "$security_level" in
        "maximum_restriction")
            echo "Applying maximum security restrictions..."
            
            # Disable network access for guest
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestNetworkAccess -bool FALSE
            
            # Disable removable media access
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestRemovableMediaAccess -bool FALSE
            
            # Disable printing
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestPrintingAccess -bool FALSE
            
            # Set strict application restrictions
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestAllowedApplications -array "Safari"
            
            echo "  ✅ Maximum security restrictions applied"
            ;;
            
        "standard_restriction")
            echo "Applying standard security restrictions..."
            
            # Allow limited network access
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestNetworkAccess -bool TRUE
            
            # Disable removable media access
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestRemovableMediaAccess -bool FALSE
            
            # Allow printing with restrictions
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestPrintingAccess -bool TRUE
            
            echo "  ✅ Standard security restrictions applied"
            ;;
            
        "minimal_restriction")
            echo "Applying minimal security restrictions..."
            
            # Allow network access
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestNetworkAccess -bool TRUE
            
            # Allow removable media with monitoring
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestRemovableMediaAccess -bool TRUE
            
            # Allow printing
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestPrintingAccess -bool TRUE
            
            echo "  ✅ Minimal security restrictions applied"
            ;;
            
        *)
            echo "❌ Unknown security level: $security_level"
            return 1
            ;;
    esac
    
    audit_log "Guest security enforcement completed: $security_level"
    
    return 0
}

# Guest session lifecycle management
manage_guest_lifecycle() {
    local action="$1"
    local parameters="$2"
    
    log_action "Managing guest lifecycle: $action"
    
    case "$action" in
        "cleanup_expired_sessions")
            echo "Cleaning up expired guest sessions..."
            
            # Force logout inactive guest sessions
            pkill -u Guest 2>/dev/null
            
            # Clean guest home directory
            sudo rm -rf /Users/Guest/* 2>/dev/null
            
            echo "  ✅ Expired sessions cleaned up"
            ;;
            
        "reset_guest_environment")
            echo "Resetting guest environment..."
            
            # Reset guest user preferences
            sudo rm -rf /Users/Guest/Library/Preferences/* 2>/dev/null
            
            # Clear guest application data
            sudo rm -rf /Users/Guest/Library/Application\ Support/* 2>/dev/null
            
            # Clear downloads and documents
            sudo rm -rf /Users/Guest/Downloads/* 2>/dev/null
            sudo rm -rf /Users/Guest/Documents/* 2>/dev/null
            
            echo "  ✅ Guest environment reset"
            ;;
            
        "generate_session_report")
            echo "Generating guest session report..."
            
            local report_file="$REPORTS_DIR/guest_session_report_$(date +%Y%m%d_%H%M%S).json"
            
            # Collect session data
            local session_data
            session_data=$(last | grep "Guest" | head -20)
            
            # Generate report
            cat > "$report_file" << EOF
{
    "report_type": "guest_session_analysis",
    "generated": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "recent_sessions": "$session_data",
    "guest_status": {
        "enabled": $(defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo "false"),
        "auto_logout": $(defaults read /Library/Preferences/com.apple.loginwindow GuestAutoLogout 2>/dev/null || echo "0")
    }
}
EOF
            
            echo "  ✅ Session report generated: $report_file"
            ;;
            
        *)
            echo "❌ Unknown lifecycle action: $action"
            return 1
            ;;
    esac
    
    return 0
}

# Guest compliance monitoring
monitor_guest_compliance() {
    local compliance_framework="$1"
    
    log_action "Monitoring guest user compliance: $compliance_framework"
    
    echo "=== Guest User Compliance Monitoring ==="
    echo "Framework: $compliance_framework"
    
    local violations=()
    local compliance_score=100
    
    case "$compliance_framework" in
        "security_standard")
            # Check if guest user is properly configured
            local guest_enabled
            guest_enabled=$(defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo "false")
            
            if [[ "$guest_enabled" != "1" && "$guest_enabled" != "true" ]]; then
                violations+=("guest_user_not_properly_configured")
                ((compliance_score -= 20))
            fi
            
            # Check for auto-logout configuration
            local auto_logout
            auto_logout=$(defaults read /Library/Preferences/com.apple.loginwindow GuestAutoLogout 2>/dev/null || echo "0")
            
            if [[ "$auto_logout" == "0" ]]; then
                violations+=("auto_logout_not_configured")
                ((compliance_score -= 15))
            fi
            ;;
            
        "privacy_protection")
            # Check for data retention policies
            if [[ -d "/Users/Guest" && -n "$(ls -A /Users/Guest 2>/dev/null)" ]]; then
                violations+=("guest_data_not_cleaned")
                ((compliance_score -= 25))
            fi
            
            # Check session monitoring
            if [[ ! -f "$AUDIT_LOG" ]]; then
                violations+=("session_monitoring_not_configured")
                ((compliance_score -= 20))
            fi
            ;;
            
        *)
            echo "❌ Unknown compliance framework: $compliance_framework"
            return 1
            ;;
    esac
    
    echo ""
    echo "Compliance Results:"
    echo "  Framework: $compliance_framework"
    echo "  Compliance Score: $compliance_score/100"
    echo "  Violations Found: ${#violations[@]}"
    
    if [[ ${#violations[@]} -gt 0 ]]; then
        echo "  Violations:"
        for violation in "${violations[@]}"; do
            echo "    - $violation"
        done
    else
        echo "  ✅ No violations found"
    fi
    
    audit_log "Guest compliance monitoring completed: $compliance_framework (Score: $compliance_score/100)"
    
    return 0
}

# Main function with command routing
main() {
    local command="$1"
    shift
    
    # Initialize
    create_directories
    
    case "$command" in
        "enable")
            # Enable guest user with basic configuration
            configure_guest_user
            ;;
        "disable")
            # Disable guest user
            sudo defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool FALSE
            echo "Guest user disabled"
            ;;
        "status")
            # Check guest user status
            local status
            status=$(defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo "false")
            echo "Guest User Status: $([ "$status" = "1" ] && echo "Enabled" || echo "Disabled")"
            ;;
        "monitor_sessions")
            monitor_guest_sessions "$@"
            ;;
        "apply_policy")
            apply_guest_policy "$@"
            ;;
        "enforce_security")
            enforce_guest_security "$@"
            ;;
        "manage_lifecycle")
            manage_guest_lifecycle "$@"
            ;;
        "compliance_check")
            monitor_guest_compliance "$@"
            ;;
        "show_categories")
            print_guest_categories
            ;;
        "show_policies")
            for policy in public_access_secure business_visitor_standard educational_open demo_presentation emergency_minimal compliance_strict; do
                echo "Policy: $policy"
                get_guest_policy "$policy" | jq .
                echo ""
            done
            ;;
        *)
            echo "MacFleet Guest User Management System"
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  enable                                    - Enable guest user with configuration"
            echo "  disable                                   - Disable guest user"
            echo "  status                                    - Check guest user status"
            echo "  monitor_sessions <profile>                - Monitor guest sessions"
            echo "  apply_policy <policy>                     - Apply guest user policy"
            echo "  enforce_security <level>                  - Enforce security restrictions"
            echo "  manage_lifecycle <action>                 - Manage guest lifecycle"
            echo "  compliance_check <framework>              - Check compliance"
            echo "  show_categories                           - Show guest user categories"
            echo "  show_policies                             - Show guest user policies"
            echo ""
            echo "Examples:"
            echo "  $0 enable"
            echo "  $0 apply_policy public_access_secure"
            echo "  $0 enforce_security maximum_restriction"
            echo "  $0 monitor_sessions comprehensive"
            echo "  $0 manage_lifecycle cleanup_expired_sessions"
            echo "  $0 compliance_check security_standard"
            ;;
    esac
}

# Execute main function with all arguments
main "$@"

Security Considerations

Guest User Security

  • Session Isolation - Complete isolation of guest sessions from system and user data
  • Data Prevention - Prevent data persistence and information leakage
  • Network Restrictions - Control network access and external communications
  • Application Controls - Restrict available applications and system access
  • Monitoring & Auditing - Comprehensive logging of guest activities

Compliance Framework

  • Privacy Protection - Ensure guest sessions don't compromise user privacy
  • Data Security - Prevent unauthorized access to sensitive information
  • Access Controls - Implement proper access restrictions and limitations
  • Session Management - Proper session lifecycle and cleanup procedures
  • Audit Requirements - Maintain compliance with audit and monitoring standards

Troubleshooting Guide

Common Issues

Guest User Not Appearing

  • Verify guest user is enabled: defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled
  • Check login window settings in System Preferences
  • Restart login window process: sudo killall loginwindow

Guest Session Not Auto-Logging Out

  • Verify auto-logout configuration: defaults read /Library/Preferences/com.apple.loginwindow GuestAutoLogout
  • Check for running guest processes preventing logout
  • Manually force guest logout if needed

Guest User Has Too Much Access

  • Review and apply appropriate security policies
  • Check application restrictions and system access controls
  • Verify network and file access limitations

Diagnostic Commands

# Check guest user status
defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled

# Check auto-logout setting
defaults read /Library/Preferences/com.apple.loginwindow GuestAutoLogout

# List active guest sessions
who | grep Guest

# View guest login history
last | grep Guest

Important Notes

  • Data Security - Guest sessions should never have access to sensitive data
  • Session Cleanup - Ensure proper cleanup of guest data on logout
  • Access Restrictions - Implement appropriate restrictions based on use case
  • Monitoring - Maintain logs and monitoring for security and compliance
  • Regular Maintenance - Regularly clean up and reset guest environments
  • Security Testing - Test guest restrictions to ensure proper isolation

Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Configurando un Runner de GitHub Actions en un Mac Mini (Apple Silicon)

Runner de GitHub Actions

GitHub Actions es una plataforma poderosa de CI/CD que te permite automatizar tus flujos de trabajo de desarrollo de software. Aunque GitHub ofrece runners hospedados, los runners auto-hospedados proporcionan mayor control y personalización para tu configuración de CI/CD. Este tutorial te guía a través de la configuración y conexión de un runner auto-hospedado en un Mac mini para ejecutar pipelines de macOS.

Prerrequisitos

Antes de comenzar, asegúrate de tener:

  • Un Mac mini (regístrate en Macfleet)
  • Un repositorio de GitHub con derechos de administrador
  • Un gestor de paquetes instalado (preferiblemente Homebrew)
  • Git instalado en tu sistema

Paso 1: Crear una Cuenta de Usuario Dedicada

Primero, crea una cuenta de usuario dedicada para el runner de GitHub Actions:

# Crear la cuenta de usuario 'gh-runner'
sudo dscl . -create /Users/gh-runner
sudo dscl . -create /Users/gh-runner UserShell /bin/bash
sudo dscl . -create /Users/gh-runner RealName "GitHub runner"
sudo dscl . -create /Users/gh-runner UniqueID "1001"
sudo dscl . -create /Users/gh-runner PrimaryGroupID 20
sudo dscl . -create /Users/gh-runner NFSHomeDirectory /Users/gh-runner

# Establecer la contraseña para el usuario
sudo dscl . -passwd /Users/gh-runner tu_contraseña

# Agregar 'gh-runner' al grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Cambia a la nueva cuenta de usuario:

su gh-runner

Paso 2: Instalar Software Requerido

Instala Git y Rosetta 2 (si usas Apple Silicon):

# Instalar Git si no está ya instalado
brew install git

# Instalar Rosetta 2 para Macs Apple Silicon
softwareupdate --install-rosetta

Paso 3: Configurar el Runner de GitHub Actions

  1. Ve a tu repositorio de GitHub
  2. Navega a Configuración > Actions > Runners

Runner de GitHub Actions

  1. Haz clic en "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecciona macOS como imagen del runner y ARM64 como arquitectura
  3. Sigue los comandos proporcionados para descargar y configurar el runner

Runner de GitHub Actions

Crea un archivo .env en el directorio _work del runner:

# archivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Ejecuta el script run.sh en tu directorio del runner para completar la configuración.
  2. Verifica que el runner esté activo y escuchando trabajos en la terminal y revisa la configuración del repositorio de GitHub para la asociación del runner y el estado Idle.

Runner de GitHub Actions

Paso 4: Configurar Sudoers (Opcional)

Si tus acciones requieren privilegios de root, configura el archivo sudoers:

sudo visudo

Agrega la siguiente línea:

gh-runner ALL=(ALL) NOPASSWD: ALL

Paso 5: Usar el Runner en Flujos de Trabajo

Configura tu flujo de trabajo de GitHub Actions para usar el runner auto-hospedado:

name: Flujo de trabajo de muestra

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64]
    steps:
      - name: Instalar NodeJS
        run: brew install node

El runner está autenticado en tu repositorio y etiquetado con self-hosted, macOS, y ARM64. Úsalo en tus flujos de trabajo especificando estas etiquetas en el campo runs-on:

runs-on: [self-hosted, macOS, ARM64]

Mejores Prácticas

  • Mantén tu software del runner actualizado
  • Monitorea regularmente los logs del runner para problemas
  • Usa etiquetas específicas para diferentes tipos de runners
  • Implementa medidas de seguridad apropiadas
  • Considera usar múltiples runners para balanceo de carga

Solución de Problemas

Problemas comunes y soluciones:

  1. Runner no conectando:

    • Verifica conectividad de red
    • Verifica validez del token de GitHub
    • Asegúrate de permisos apropiados
  2. Fallas de construcción:

    • Verifica instalación de Xcode
    • Verifica dependencias requeridas
    • Revisa logs del flujo de trabajo
  3. Problemas de permisos:

    • Verifica permisos de usuario
    • Verifica configuración de sudoers
    • Revisa permisos del sistema de archivos

Conclusión

Ahora tienes un runner auto-hospedado de GitHub Actions configurado en tu Mac mini. Esta configuración te proporciona más control sobre tu entorno de CI/CD y te permite ejecutar flujos de trabajo específicos de macOS de manera eficiente.

Recuerda mantener regularmente tu runner y mantenerlo actualizado con los últimos parches de seguridad y versiones de software.

Aplicación Nativa

Aplicación nativa de Macfleet

Guía de Instalación de Macfleet

Macfleet es una solución poderosa de gestión de flota diseñada específicamente para entornos de Mac Mini alojados en la nube. Como proveedor de hosting en la nube de Mac Mini, puedes usar Macfleet para monitorear, gestionar y optimizar toda tu flota de instancias Mac virtualizadas.

Esta guía de instalación te llevará a través de la configuración del monitoreo de Macfleet en sistemas macOS, Windows y Linux para asegurar una supervisión integral de tu infraestructura en la nube.

🍎 macOS

  • Descarga el archivo .dmg para Mac aquí
  • Haz doble clic en el archivo .dmg descargado
  • Arrastra la aplicación Macfleet a la carpeta Aplicaciones
  • Expulsa el archivo .dmg
  • Abre Preferencias del Sistema > Seguridad y Privacidad
    • Pestaña Privacidad > Accesibilidad
    • Marca Macfleet para permitir el monitoreo
  • Inicia Macfleet desde Aplicaciones
  • El seguimiento comienza automáticamente

🪟 Windows

  • Descarga el archivo .exe para Windows aquí
  • Haz clic derecho en el archivo .exe > "Ejecutar como administrador"
  • Sigue el asistente de instalación
  • Acepta los términos y condiciones
  • Permite en Windows Defender si se solicita
  • Concede permisos de monitoreo de aplicaciones
  • Inicia Macfleet desde el Menú Inicio
  • La aplicación comienza el seguimiento automáticamente

🐧 Linux

  • Descarga el paquete .deb (Ubuntu/Debian) o .rpm (CentOS/RHEL) aquí
  • Instala usando tu gestor de paquetes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permite permisos de acceso X11 si se solicita
  • Agrega el usuario a los grupos apropiados si es necesario
  • Inicia Macfleet desde el menú de Aplicaciones
  • La aplicación comienza el seguimiento automáticamente

Nota: Después de la instalación en todos los sistemas, inicia sesión con tus credenciales de Macfleet para sincronizar datos con tu panel de control.