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.

Desktop Wallpaper Management on macOS

Implement enterprise-grade desktop wallpaper management across your MacFleet deployment with standardized branding policies, automated image deployment, and comprehensive compliance monitoring. This tutorial provides solutions for maintaining consistent corporate visual identity and brand presence.

Understanding macOS Desktop Wallpaper Management

macOS provides several methods for setting desktop wallpapers programmatically:

  • AppleScript via osascript - Cross-application scripting for Finder integration
  • System Preferences - Native configuration through System Database
  • Desktop Pictures Database - Direct SQLite database manipulation
  • Configuration Profiles - MDM-based wallpaper deployment
  • User Defaults - Per-user preference management

Basic Wallpaper Operations

Set Desktop Wallpaper

#!/bin/bash

# Basic wallpaper setting
path="$1"
osascript -e 'tell application "Finder" to set desktop picture to POSIX file "'"$path"'"'
ret=$?

if [ $ret == "0" ]; then
    echo "Wallpaper set successfully"
else
    echo "Operation failed."
fi

Enhanced Wallpaper Setting with Validation

#!/bin/bash

# Enhanced wallpaper setting with validation and error handling
set_wallpaper() {
    local image_path="$1"
    local user_name="$2"
    
    # Validate image file exists
    if [[ ! -f "$image_path" ]]; then
        echo "❌ Error: Image file not found: $image_path"
        return 1
    fi
    
    # Validate image format
    local file_type
    file_type=$(file --mime-type "$image_path" | awk '{print $2}')
    
    if [[ ! "$file_type" =~ ^image/ ]]; then
        echo "❌ Error: Invalid image format: $file_type"
        return 1
    fi
    
    # Set wallpaper using AppleScript
    echo "Setting wallpaper: $image_path"
    
    if [[ -n "$user_name" ]]; then
        # Set for specific user
        sudo -u "$user_name" osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\""
    else
        # Set for current user
        osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\""
    fi
    
    local result=$?
    
    if [[ $result -eq 0 ]]; then
        echo "✅ Wallpaper set successfully for ${user_name:-current user}"
        return 0
    else
        echo "❌ Failed to set wallpaper (exit code: $result)"
        return 1
    fi
}

# Usage example
# set_wallpaper "/Users/Admin/Pictures/company_wallpaper.png" "admin"

Enterprise Wallpaper Management System

Comprehensive Wallpaper Management Tool

#!/bin/bash

# MacFleet Enterprise Desktop Wallpaper Management Tool
# Centralized branding and wallpaper policy enforcement

# Configuration
CONFIG_FILE="/etc/macfleet/wallpaper_policy.conf"
LOG_FILE="/var/log/macfleet_wallpaper.log"
WALLPAPER_DIR="/Library/MacFleet/Wallpapers"
REPORT_DIR="/var/log/macfleet_reports"

# Create directories
mkdir -p "$(dirname "$CONFIG_FILE")" "$(dirname "$LOG_FILE")" "$WALLPAPER_DIR" "$REPORT_DIR"

# Default wallpaper policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Wallpaper Management Policy
# Version: 2.0

# Branding Configuration
ENFORCE_CORPORATE_BRANDING=true
ALLOW_USER_CUSTOMIZATION=false
DEFAULT_WALLPAPER="corporate_standard.jpg"
FALLBACK_WALLPAPER="macfleet_default.png"

# Wallpaper Repository
WALLPAPER_REPOSITORY_URL="https://assets.macfleet.com/wallpapers"
LOCAL_WALLPAPER_DIR="/Library/MacFleet/Wallpapers"
SYNC_WALLPAPERS=true

# Policy Settings
SCHEDULE_WALLPAPER_CHANGES=false
WALLPAPER_ROTATION_INTERVAL=86400  # 24 hours
VALIDATE_IMAGE_INTEGRITY=true
LOG_WALLPAPER_CHANGES=true

# User Restrictions
BLOCK_SYSTEM_PREFERENCES_DESKTOP=false
HIDE_DESKTOP_PREFERENCES=false
LOCK_WALLPAPER_SETTINGS=false

# Supported Formats
SUPPORTED_FORMATS="jpg,jpeg,png,heic,bmp,tiff,gif"
MAX_FILE_SIZE_MB=10
MIN_RESOLUTION="1024x768"
EOF

# Source configuration
source "$CONFIG_FILE" 2>/dev/null || true

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

# Validate image file
validate_image() {
    local image_path="$1"
    local errors=()
    
    # Check file existence
    if [[ ! -f "$image_path" ]]; then
        errors+=("File does not exist")
        printf '%s\n' "${errors[@]}"
        return 1
    fi
    
    # Check file format
    local file_type
    file_type=$(file --mime-type "$image_path" 2>/dev/null | awk '{print $2}')
    
    if [[ ! "$file_type" =~ ^image/ ]]; then
        errors+=("Invalid image format: $file_type")
    fi
    
    # Check file extension
    local extension
    extension=$(echo "${image_path##*.}" | tr '[:upper:]' '[:lower:]')
    
    if [[ ",$SUPPORTED_FORMATS," != *",$extension,"* ]]; then
        errors+=("Unsupported file format: $extension")
    fi
    
    # Check file size
    if command -v stat >/dev/null; then
        local file_size_mb
        file_size_mb=$(( $(stat -f%z "$image_path" 2>/dev/null || echo 0) / 1024 / 1024 ))
        
        if [[ $file_size_mb -gt $MAX_FILE_SIZE_MB ]]; then
            errors+=("File too large: ${file_size_mb}MB (max: ${MAX_FILE_SIZE_MB}MB)")
        fi
    fi
    
    # Check image dimensions
    if command -v sips >/dev/null; then
        local dimensions
        dimensions=$(sips -g pixelWidth -g pixelHeight "$image_path" 2>/dev/null | grep -E "pixelWidth|pixelHeight" | awk '{print $2}' | tr '\n' 'x' | sed 's/x$//')
        
        if [[ -n "$dimensions" ]]; then
            local width height
            width=$(echo "$dimensions" | cut -d'x' -f1)
            height=$(echo "$dimensions" | cut -d'x' -f2)
            local min_width min_height
            min_width=$(echo "$MIN_RESOLUTION" | cut -d'x' -f1)
            min_height=$(echo "$MIN_RESOLUTION" | cut -d'x' -f2)
            
            if [[ $width -lt $min_width || $height -lt $min_height ]]; then
                errors+=("Resolution too low: ${dimensions} (min: ${MIN_RESOLUTION})")
            fi
        fi
    fi
    
    if [[ ${#errors[@]} -eq 0 ]]; then
        return 0
    else
        printf '%s\n' "${errors[@]}"
        return 1
    fi
}

# Download wallpaper from repository
download_wallpaper() {
    local wallpaper_name="$1"
    local local_path="$WALLPAPER_DIR/$wallpaper_name"
    
    if [[ "$SYNC_WALLPAPERS" != "true" ]]; then
        echo "Wallpaper sync disabled"
        return 1
    fi
    
    echo "Downloading wallpaper: $wallpaper_name"
    
    # Download using curl
    if curl -fsSL "$WALLPAPER_REPOSITORY_URL/$wallpaper_name" -o "$local_path.tmp"; then
        # Validate downloaded image
        if validate_image "$local_path.tmp" >/dev/null 2>&1; then
            mv "$local_path.tmp" "$local_path"
            echo "✅ Downloaded and validated: $wallpaper_name"
            log_action "Downloaded wallpaper: $wallpaper_name"
            return 0
        else
            rm -f "$local_path.tmp"
            echo "❌ Downloaded file failed validation"
            return 1
        fi
    else
        echo "❌ Failed to download wallpaper"
        return 1
    fi
}

# Set wallpaper for user
set_user_wallpaper() {
    local image_path="$1"
    local target_user="$2"
    
    echo "=== Setting Wallpaper ==="
    echo "Image: $image_path"
    echo "User: ${target_user:-current user}"
    
    # Validate image
    if ! validate_image "$image_path"; then
        echo "❌ Image validation failed"
        return 1
    fi
    
    # Set wallpaper
    if [[ -n "$target_user" ]]; then
        # Set for specific user (requires appropriate permissions)
        sudo -u "$target_user" osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\"" 2>/dev/null
    else
        # Set for current user
        osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\""
    fi
    
    local result=$?
    
    if [[ $result -eq 0 ]]; then
        echo "✅ Wallpaper set successfully"
        log_action "Wallpaper set: $image_path for user: ${target_user:-current}"
        return 0
    else
        echo "❌ Failed to set wallpaper (exit code: $result)"
        log_action "FAILED to set wallpaper: $image_path for user: ${target_user:-current}"
        return 1
    fi
}

# Apply corporate wallpaper
apply_corporate_wallpaper() {
    local wallpaper_name="${1:-$DEFAULT_WALLPAPER}"
    local target_user="$2"
    
    echo "=== Applying Corporate Wallpaper ==="
    
    if [[ "$ENFORCE_CORPORATE_BRANDING" != "true" ]]; then
        echo "Corporate branding enforcement disabled"
        return 0
    fi
    
    # Check if wallpaper exists locally
    local wallpaper_path="$WALLPAPER_DIR/$wallpaper_name"
    
    if [[ ! -f "$wallpaper_path" ]]; then
        echo "Wallpaper not found locally, attempting download..."
        if ! download_wallpaper "$wallpaper_name"; then
            echo "Using fallback wallpaper..."
            wallpaper_path="$WALLPAPER_DIR/$FALLBACK_WALLPAPER"
            
            if [[ ! -f "$wallpaper_path" ]]; then
                echo "❌ No wallpaper available (including fallback)"
                return 1
            fi
        else
            wallpaper_path="$WALLPAPER_DIR/$wallpaper_name"
        fi
    fi
    
    # Apply wallpaper
    set_user_wallpaper "$wallpaper_path" "$target_user"
}

# Get current wallpaper information
get_current_wallpaper() {
    echo "=== Current Wallpaper Information ==="
    
    # Get current wallpaper path using AppleScript
    local current_wallpaper
    current_wallpaper=$(osascript -e 'tell application "Finder" to get desktop picture as string' 2>/dev/null)
    
    if [[ -n "$current_wallpaper" ]]; then
        # Convert from HFS+ path to POSIX path
        local posix_path
        posix_path=$(osascript -e "get POSIX path of \"$current_wallpaper\"" 2>/dev/null)
        
        echo "Current wallpaper: $posix_path"
        
        if [[ -f "$posix_path" ]]; then
            echo "File size: $(du -h "$posix_path" | cut -f1)"
            
            # Get image dimensions if sips is available
            if command -v sips >/dev/null; then
                local dimensions
                dimensions=$(sips -g pixelWidth -g pixelHeight "$posix_path" 2>/dev/null | grep -E "pixelWidth|pixelHeight" | awk '{print $2}' | tr '\n' 'x' | sed 's/x$//')
                echo "Dimensions: $dimensions"
            fi
            
            # Check if it's a corporate wallpaper
            if [[ "$posix_path" == "$WALLPAPER_DIR"* ]]; then
                echo "✅ Corporate wallpaper detected"
            else
                echo "⚠️  Non-corporate wallpaper detected"
            fi
        else
            echo "⚠️  Wallpaper file not found"
        fi
    else
        echo "❌ Unable to retrieve current wallpaper"
    fi
}

# Sync wallpaper repository
sync_wallpaper_repository() {
    echo "=== Syncing Wallpaper Repository ==="
    
    if [[ "$SYNC_WALLPAPERS" != "true" ]]; then
        echo "Wallpaper sync disabled"
        return 0
    fi
    
    # Create wallpaper directory
    mkdir -p "$WALLPAPER_DIR"
    
    # Download manifest file
    local manifest_file="$WALLPAPER_DIR/.manifest"
    
    if curl -fsSL "$WALLPAPER_REPOSITORY_URL/manifest.txt" -o "$manifest_file.tmp" 2>/dev/null; then
        echo "Downloaded wallpaper manifest"
        
        # Process manifest and download wallpapers
        while IFS= read -r wallpaper_name; do
            [[ -z "$wallpaper_name" || "$wallpaper_name" =~ ^# ]] && continue
            
            local local_path="$WALLPAPER_DIR/$wallpaper_name"
            
            if [[ ! -f "$local_path" ]]; then
                echo "Downloading: $wallpaper_name"
                download_wallpaper "$wallpaper_name"
            else
                echo "Already exists: $wallpaper_name"
            fi
        done < "$manifest_file.tmp"
        
        mv "$manifest_file.tmp" "$manifest_file"
        echo "✅ Wallpaper repository synchronized"
        log_action "Wallpaper repository synchronized"
    else
        echo "❌ Failed to download manifest"
        return 1
    fi
}

# Generate compliance report
generate_wallpaper_report() {
    local report_file="$REPORT_DIR/wallpaper_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Wallpaper Compliance Report ==="
    
    # Get current wallpaper
    local current_wallpaper
    current_wallpaper=$(osascript -e 'tell application "Finder" to get desktop picture as string' 2>/dev/null)
    local posix_path=""
    local is_corporate="false"
    local compliance_status="non_compliant"
    
    if [[ -n "$current_wallpaper" ]]; then
        posix_path=$(osascript -e "get POSIX path of \"$current_wallpaper\"" 2>/dev/null)
        
        if [[ "$posix_path" == "$WALLPAPER_DIR"* ]]; then
            is_corporate="true"
            compliance_status="compliant"
        fi
    fi
    
    # Create JSON report
    cat > "$report_file" << EOF
{
  "report_type": "wallpaper_compliance",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "device_info": {
    "hostname": "$(hostname)",
    "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)",
    "macos_version": "$(sw_vers -productVersion)",
    "current_user": "$(whoami)"
  },
  "wallpaper_status": {
    "current_wallpaper": "$posix_path",
    "is_corporate_wallpaper": $is_corporate,
    "compliance_status": "$compliance_status",
    "branding_enforced": $ENFORCE_CORPORATE_BRANDING
  },
  "policy_settings": {
    "corporate_branding_enforced": $ENFORCE_CORPORATE_BRANDING,
    "user_customization_allowed": $ALLOW_USER_CUSTOMIZATION,
    "default_wallpaper": "$DEFAULT_WALLPAPER",
    "wallpaper_sync_enabled": $SYNC_WALLPAPERS
  },
  "repository_info": {
    "local_wallpaper_count": $(find "$WALLPAPER_DIR" -name "*.jpg" -o -name "*.png" -o -name "*.jpeg" 2>/dev/null | wc -l | xargs),
    "last_sync": "$(stat -f %Sm "$WALLPAPER_DIR/.manifest" 2>/dev/null || echo "never")"
  }
}
EOF
    
    echo "Wallpaper compliance report saved to: $report_file"
    log_action "Wallpaper compliance report generated: $report_file"
}

# Main function with argument handling
main() {
    log_action "=== MacFleet Wallpaper Management Tool Started ==="
    
    case "${1:-status}" in
        "set")
            set_user_wallpaper "$2" "$3"
            ;;
        "corporate")
            apply_corporate_wallpaper "$2" "$3"
            ;;
        "sync")
            sync_wallpaper_repository
            ;;
        "validate")
            if validate_image "$2"; then
                echo "✅ Image validation passed: $2"
            else
                echo "❌ Image validation failed: $2"
            fi
            ;;
        "download")
            download_wallpaper "$2"
            ;;
        "report")
            generate_wallpaper_report
            ;;
        "status"|*)
            get_current_wallpaper
            ;;
    esac
    
    log_action "=== Wallpaper management operation completed ==="
}

# Execute main function
main "$@"

Advanced Wallpaper Management

Automated Wallpaper Rotation

#!/bin/bash

# Automated wallpaper rotation system
setup_wallpaper_rotation() {
    echo "=== Setting Up Wallpaper Rotation ==="
    
    if [[ "$SCHEDULE_WALLPAPER_CHANGES" != "true" ]]; then
        echo "Wallpaper rotation disabled in policy"
        return 0
    fi
    
    # Create rotation script
    local rotation_script="/usr/local/bin/macfleet-wallpaper-rotate"
    
    cat > "$rotation_script" << 'EOF'
#!/bin/bash
# MacFleet Wallpaper Rotation Script

WALLPAPER_DIR="/Library/MacFleet/Wallpapers"
LOG_FILE="/var/log/macfleet_wallpaper.log"

# Get list of available wallpapers
mapfile -t wallpapers < <(find "$WALLPAPER_DIR" -name "*.jpg" -o -name "*.png" -o -name "*.jpeg" 2>/dev/null)

if [[ ${#wallpapers[@]} -eq 0 ]]; then
    echo "$(date) - No wallpapers found for rotation" >> "$LOG_FILE"
    exit 1
fi

# Select random wallpaper
random_wallpaper="${wallpapers[$RANDOM % ${#wallpapers[@]}]}"

# Apply wallpaper
/usr/local/bin/macfleet-wallpaper set "$random_wallpaper"

echo "$(date) - Rotated to wallpaper: $random_wallpaper" >> "$LOG_FILE"
EOF
    
    chmod +x "$rotation_script"
    
    # Create LaunchDaemon for scheduling
    local plist_file="/Library/LaunchDaemons/com.macfleet.wallpaper-rotation.plist"
    
    cat > "$plist_file" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.macfleet.wallpaper-rotation</string>
    <key>ProgramArguments</key>
    <array>
        <string>$rotation_script</string>
    </array>
    <key>StartInterval</key>
    <integer>$WALLPAPER_ROTATION_INTERVAL</integer>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    # Load the daemon
    launchctl load "$plist_file"
    
    echo "✅ Wallpaper rotation configured (interval: ${WALLPAPER_ROTATION_INTERVAL}s)"
}

setup_wallpaper_rotation

Multi-Display Wallpaper Management

#!/bin/bash

# Multi-display wallpaper management
set_multi_display_wallpapers() {
    echo "=== Multi-Display Wallpaper Management ==="
    
    # Get display count
    local display_count
    display_count=$(system_profiler SPDisplaysDataType | grep -c "Resolution:")
    
    echo "Detected displays: $display_count"
    
    if [[ $display_count -gt 1 ]]; then
        echo "Setting wallpapers for multiple displays..."
        
        # Set different wallpapers for each display
        for ((i=1; i<=display_count; i++)); do
            local wallpaper_file="display_${i}_wallpaper.jpg"
            local wallpaper_path="$WALLPAPER_DIR/$wallpaper_file"
            
            if [[ -f "$wallpaper_path" ]]; then
                echo "Setting wallpaper for display $i: $wallpaper_file"
                
                # Use AppleScript to set wallpaper for specific display
                osascript << EOF
                tell application "System Events"
                    tell desktop $i
                        set picture to "$wallpaper_path"
                    end tell
                end tell
EOF
            else
                echo "⚠️  Wallpaper not found for display $i: $wallpaper_file"
            fi
        done
    else
        echo "Single display detected, using standard wallpaper"
        apply_corporate_wallpaper
    fi
}

set_multi_display_wallpapers

Wallpaper Policy Enforcement

#!/bin/bash

# Monitor and enforce wallpaper policies
monitor_wallpaper_compliance() {
    echo "=== Wallpaper Compliance Monitoring ==="
    
    # Check current wallpaper compliance
    local current_wallpaper
    current_wallpaper=$(osascript -e 'tell application "Finder" to get desktop picture as string' 2>/dev/null)
    
    if [[ -n "$current_wallpaper" ]]; then
        local posix_path
        posix_path=$(osascript -e "get POSIX path of \"$current_wallpaper\"" 2>/dev/null)
        
        # Check if wallpaper is from corporate repository
        if [[ "$posix_path" != "$WALLPAPER_DIR"* ]] && [[ "$ENFORCE_CORPORATE_BRANDING" == "true" ]]; then
            echo "⚠️  Non-corporate wallpaper detected: $posix_path"
            log_action "POLICY VIOLATION: Non-corporate wallpaper detected: $posix_path"
            
            # Auto-remediate if enabled
            if [[ "$ALLOW_USER_CUSTOMIZATION" != "true" ]]; then
                echo "Auto-remediating with corporate wallpaper..."
                apply_corporate_wallpaper
                log_action "Auto-remediated wallpaper policy violation"
            fi
        else
            echo "✅ Wallpaper compliance: OK"
        fi
    else
        echo "❌ Unable to check wallpaper compliance"
    fi
}

monitor_wallpaper_compliance

Integration and Deployment

MDM Integration Script

#!/bin/bash

# MDM integration for wallpaper deployment
deploy_wallpaper_via_mdm() {
    local wallpaper_url="$1"
    local deployment_mode="${2:-immediate}"
    
    echo "=== MDM Wallpaper Deployment ==="
    echo "Source: $wallpaper_url"
    echo "Mode: $deployment_mode"
    
    # Download wallpaper
    local temp_file="/tmp/mdm_wallpaper_$(date +%s).jpg"
    
    if curl -fsSL "$wallpaper_url" -o "$temp_file"; then
        echo "✅ Downloaded wallpaper from MDM"
        
        # Validate and deploy
        if validate_image "$temp_file"; then
            # Copy to corporate wallpaper directory
            local dest_file="$WALLPAPER_DIR/mdm_deployed_$(basename "$temp_file")"
            cp "$temp_file" "$dest_file"
            
            # Apply immediately or schedule
            case "$deployment_mode" in
                "immediate")
                    set_user_wallpaper "$dest_file"
                    ;;
                "next_login")
                    # Set as default for next login
                    defaults write /Library/Preferences/com.apple.desktop Background "{default = {ImageFilePath = '$dest_file'; }; }"
                    ;;
                "scheduled")
                    # Add to rotation pool
                    echo "Added to rotation pool: $dest_file"
                    ;;
            esac
            
            # Cleanup
            rm -f "$temp_file"
            echo "✅ MDM wallpaper deployment completed"
        else
            echo "❌ MDM wallpaper validation failed"
            rm -f "$temp_file"
            return 1
        fi
    else
        echo "❌ Failed to download wallpaper from MDM"
        return 1
    fi
}

# Example usage:
# deploy_wallpaper_via_mdm "https://mdm.company.com/wallpapers/quarterly_branding.jpg" "immediate"

Important Configuration Notes

AppleScript and Security

  • Privacy permissions required for script execution
  • User consent needed for Finder access on first run
  • Automation permissions for System Events access
  • Full Disk Access may be required for some operations

Supported Image Formats

  • JPEG/JPG - Most common, good compression
  • PNG - Supports transparency, larger files
  • HEIC - Apple's modern format, efficient
  • TIFF/BMP - Legacy formats, large files
  • GIF - Animated support (single frame used)

Best Practices for Enterprise

  1. Image Optimization

    • Use appropriate resolution for target displays
    • Optimize file sizes for network deployment
    • Test images across different display configurations
  2. Branding Consistency

    • Maintain corporate color schemes
    • Include company logos and messaging
    • Consider seasonal or campaign-specific variations
  3. Deployment Strategy

    • Use centralized image repositories
    • Implement staged rollouts for new wallpapers
    • Provide fallback options for connectivity issues
  4. User Experience

    • Consider user preferences where policy allows
    • Provide clear communication about branding policies
    • Offer opt-out mechanisms for non-critical branding

Troubleshooting Common Issues

  • Permission denied errors - Check script execution permissions and user context
  • Image not displaying - Verify file format compatibility and path accessibility
  • Policy conflicts - Review configuration profile settings and user defaults
  • Performance issues - Optimize image file sizes and deployment timing

Remember to test wallpaper changes across different display configurations and user scenarios before deploying to your entire MacFleet environment.

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.