Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

Os exemplos de código e scripts fornecidos nestes tutoriais são apenas para fins educacionais. A Macfleet não é responsável por quaisquer problemas, danos ou vulnerabilidades de segurança que possam surgir do uso, modificação ou implementação destes exemplos. Sempre revise e teste o código em um ambiente seguro antes de usá-lo em sistemas de produção.

Application Launch Management for macOS

Implement enterprise-grade application launch management across your MacFleet deployment with automated app deployment, security validation, remote execution, and comprehensive fleet-wide application lifecycle management. This tutorial provides solutions for maintaining application availability while ensuring secure and efficient application launching.

Understanding macOS Application Launch Management

macOS provides several methods for application launching:

  • open - System command for opening files, directories, and applications
  • open -a - Launch applications by name
  • open -b - Launch applications by bundle identifier
  • Finder - GUI-based application launching
  • Spotlight - Search-based application launching

Basic Application Launch Operations

Simple Application Launch

#!/bin/bash

# Basic app launch
open -a "App name"

Launch by Bundle Identifier

#!/bin/bash

# Launch using bundle ID
open -b com.apple.AppStore

Background Application Launch

#!/bin/bash

# Launch app in background
open -g -a "App Store"

Multiple Instance Launch

#!/bin/bash

# Open new instance
open -n -a "App Store"

Hidden Application Launch

#!/bin/bash

# Launch app hidden
open -j -a "App Store"

Enterprise Application Launch Management System

#!/bin/bash

# MacFleet Enterprise Application Launch Management Tool
# Advanced application deployment and lifecycle management

# Configuration
CONFIG_FILE="/etc/macfleet/app_launch_policy.conf"
LOG_FILE="/var/log/macfleet_app_launch.log"
APP_REGISTRY="/Library/MacFleet/AppRegistry"
DEPLOYMENT_LOG="/var/log/macfleet_deployment_audit.log"

# Create directories
mkdir -p "$(dirname "$CONFIG_FILE")" "$(dirname "$LOG_FILE")" "$APP_REGISTRY" "$(dirname "$DEPLOYMENT_LOG")"

# Default application launch management policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Enterprise Application Launch Management Policy
# Version: 2.0

# Launch Policy Enforcement
ENFORCE_LAUNCH_POLICIES=true
VALIDATE_APP_SIGNATURES=true
CHECK_APP_PERMISSIONS=true
QUARANTINE_UNKNOWN_APPS=true
BUSINESS_HOURS_ENFORCEMENT=true

# Security and Validation
REQUIRE_ADMIN_APPROVAL=false
WHITELIST_ENFORCEMENT=true
MALWARE_SCANNING=true
SECURITY_ASSESSMENT=true
CERTIFICATE_VALIDATION=true

# Application Management
AUTO_UPDATE_DETECTION=true
LICENSE_VALIDATION=true
DEPENDENCY_CHECKING=true
RESOURCE_MONITORING=true
PERFORMANCE_TRACKING=true

# Deployment Controls
STAGED_DEPLOYMENT=true
ROLLBACK_CAPABILITY=true
A_B_TESTING=false
CANARY_RELEASES=false
EMERGENCY_DEPLOYMENT=true

# User Experience
USER_NOTIFICATION_ENABLED=true
LAUNCH_TIMEOUT=30
RETRY_ATTEMPTS=3
GRACEFUL_FAILURE=true
CONTEXT_AWARENESS=true

# Compliance and Audit
AUDIT_ALL_LAUNCHES=true
COMPLIANCE_REPORTING=true
LAUNCH_ANALYTICS=true
USAGE_TRACKING=true
INCIDENT_LOGGING=true
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"
}

# Audit logging function
audit_log() {
    local action="$1"
    local app_name="$2"
    local result="$3"
    local details="$4"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ACTION:$action APP:$app_name RESULT:$result DETAILS:$details USER:$(whoami)" >> "$DEPLOYMENT_LOG"
}

# Validate application before launch
validate_application() {
    local app_identifier="$1"
    local app_path=""
    
    echo "=== Application Validation ==="
    
    # Determine app path
    if [[ "$app_identifier" == *".app" ]]; then
        # Direct app name
        app_path="/Applications/$app_identifier"
    elif [[ "$app_identifier" == com.* ]]; then
        # Bundle identifier
        app_path=$(mdfind "kMDItemCFBundleIdentifier == '$app_identifier'" | head -1)
    else
        # Search for app
        app_path="/Applications/$app_identifier.app"
    fi
    
    if [[ ! -d "$app_path" ]]; then
        echo "❌ Application not found: $app_identifier"
        audit_log "VALIDATION" "$app_identifier" "NOT_FOUND" "Application path not found"
        return 1
    fi
    
    echo "✅ Application found: $app_path"
    
    # Validate code signature
    if [[ "$VALIDATE_APP_SIGNATURES" == "true" ]]; then
        echo "🔐 Validating code signature..."
        if codesign -v "$app_path" 2>/dev/null; then
            echo "✅ Code signature valid"
        else
            echo "❌ Invalid code signature"
            audit_log "VALIDATION" "$app_identifier" "SIGNATURE_INVALID" "Code signature validation failed"
            return 1
        fi
    fi
    
    # Check quarantine status
    if [[ "$QUARANTINE_UNKNOWN_APPS" == "true" ]]; then
        if xattr -l "$app_path" 2>/dev/null | grep -q "com.apple.quarantine"; then
            echo "⚠️  Application is quarantined"
            log_action "Quarantined application launch attempt: $app_identifier"
            audit_log "VALIDATION" "$app_identifier" "QUARANTINED" "Application under quarantine"
            return 1
        fi
    fi
    
    # Whitelist validation
    if [[ "$WHITELIST_ENFORCEMENT" == "true" ]]; then
        if ! check_whitelist "$app_identifier"; then
            echo "❌ Application not in whitelist"
            audit_log "VALIDATION" "$app_identifier" "NOT_WHITELISTED" "Application not in approved whitelist"
            return 1
        fi
    fi
    
    audit_log "VALIDATION" "$app_identifier" "PASSED" "All validation checks passed"
    return 0
}

# Check application whitelist
check_whitelist() {
    local app_identifier="$1"
    local whitelist_file="$APP_REGISTRY/whitelist.txt"
    
    if [[ ! -f "$whitelist_file" ]]; then
        # Create default whitelist
        cat > "$whitelist_file" << 'EOF'
# MacFleet Approved Applications Whitelist
Safari
Google Chrome
Microsoft Word
Microsoft Excel
Microsoft PowerPoint
Slack
Microsoft Teams
Zoom
Finder
System Preferences
Activity Monitor
Terminal
TextEdit
Calculator
Calendar
Contacts
Mail
Notes
Reminders
Maps
App Store
com.apple.Safari
com.google.Chrome
com.microsoft.Word
com.microsoft.Excel
com.microsoft.PowerPoint
com.tinyspeck.slackmacgap
com.microsoft.teams
us.zoom.xos
com.apple.finder
com.apple.systempreferences
EOF
    fi
    
    # Check if app is in whitelist
    if grep -qi "^$app_identifier$" "$whitelist_file" 2>/dev/null; then
        return 0
    fi
    
    return 1
}

# Business hours enforcement
check_business_hours() {
    local app_identifier="$1"
    
    if [[ "$BUSINESS_HOURS_ENFORCEMENT" != "true" ]]; then
        return 0
    fi
    
    local current_hour
    current_hour=$(date +%H)
    local current_day
    current_day=$(date +%u)  # 1=Monday, 7=Sunday
    
    # Business hours: 9 AM to 6 PM, Monday to Friday
    if [[ $current_day -ge 1 && $current_day -le 5 ]]; then
        if [[ $current_hour -ge 9 && $current_hour -lt 18 ]]; then
            # During business hours - check restricted apps
            local restricted_apps=(
                "Steam"
                "Epic Games"
                "Discord"
                "Spotify"
                "Netflix"
                "YouTube"
            )
            
            for restricted_app in "${restricted_apps[@]}"; do
                if [[ "$app_identifier" == *"$restricted_app"* ]]; then
                    echo "⚠️  Application restricted during business hours: $app_identifier"
                    audit_log "BUSINESS_HOURS" "$app_identifier" "RESTRICTED" "Application blocked during business hours"
                    return 1
                fi
            done
        fi
    fi
    
    return 0
}

# Check application dependencies
check_dependencies() {
    local app_identifier="$1"
    
    if [[ "$DEPENDENCY_CHECKING" != "true" ]]; then
        return 0
    fi
    
    echo "=== Dependency Check ==="
    
    # Known dependencies
    case "$app_identifier" in
        *"Microsoft"*)
            if ! check_microsoft_office_license; then
                echo "❌ Microsoft Office license required"
                return 1
            fi
            ;;
        *"Adobe"*)
            if ! check_adobe_license; then
                echo "❌ Adobe license required"
                return 1
            fi
            ;;
        *"Xcode"*)
            if ! check_developer_tools; then
                echo "❌ Developer tools required"
                return 1
            fi
            ;;
    esac
    
    return 0
}

# Enterprise application launch with comprehensive management
enterprise_app_launch() {
    local app_identifier="$1"
    local options="${2:-}"
    local deployment_mode="${3:-standard}"
    
    echo "=== Enterprise Application Launch ==="
    
    if [[ -z "$app_identifier" ]]; then
        echo "❌ Application identifier required"
        return 1
    fi
    
    log_action "ENTERPRISE APP LAUNCH: Starting launch of $app_identifier"
    
    # Pre-launch validation
    if ! validate_application "$app_identifier"; then
        log_action "FAILED: Application validation failed for $app_identifier"
        return 1
    fi
    
    # Business hours check
    if ! check_business_hours "$app_identifier"; then
        log_action "BLOCKED: Business hours restriction for $app_identifier"
        return 1
    fi
    
    # Dependency verification
    if ! check_dependencies "$app_identifier"; then
        log_action "FAILED: Dependency check failed for $app_identifier"
        return 1
    fi
    
    # Resource availability check
    check_system_resources
    
    # Launch application based on type
    local launch_command=""
    local launch_result=""
    
    case "$deployment_mode" in
        "background")
            launch_command="open -g"
            ;;
        "hidden")
            launch_command="open -j"
            ;;
        "new-instance")
            launch_command="open -n"
            ;;
        *)
            launch_command="open"
            ;;
    esac
    
    # Determine launch method
    if [[ "$app_identifier" == com.* ]]; then
        # Bundle identifier
        echo "🚀 Launching by bundle identifier: $app_identifier"
        audit_log "LAUNCH" "$app_identifier" "BUNDLE_ID" "Launch by bundle identifier"
        
        timeout "$LAUNCH_TIMEOUT" $launch_command -b "$app_identifier" $options 2>/dev/null
        launch_result=$?
    else
        # Application name
        echo "🚀 Launching by application name: $app_identifier"
        audit_log "LAUNCH" "$app_identifier" "APP_NAME" "Launch by application name"
        
        timeout "$LAUNCH_TIMEOUT" $launch_command -a "$app_identifier" $options 2>/dev/null
        launch_result=$?
    fi
    
    # Handle launch result
    if [[ $launch_result -eq 0 ]]; then
        echo "✅ Application launched successfully: $app_identifier"
        post_launch_monitoring "$app_identifier"
        audit_log "LAUNCH" "$app_identifier" "SUCCESS" "Application launched successfully"
        
        # Update usage statistics
        update_usage_stats "$app_identifier"
        
        log_action "SUCCESS: Application launched successfully: $app_identifier"
        return 0
    else
        echo "❌ Failed to launch application: $app_identifier"
        
        # Retry logic
        if [[ "$RETRY_ATTEMPTS" -gt 0 ]]; then
            echo "🔄 Retrying launch..."
            retry_launch "$app_identifier" "$options" "$deployment_mode"
        fi
        
        audit_log "LAUNCH" "$app_identifier" "FAILED" "Application launch failed"
        log_action "FAILED: Could not launch application: $app_identifier"
        return 1
    fi
}

# Post-launch monitoring
post_launch_monitoring() {
    local app_identifier="$1"
    
    echo "=== Post-Launch Monitoring ==="
    
    sleep 5  # Allow app to fully launch
    
    # Check if application is running
    if pgrep -f "$app_identifier" >/dev/null 2>&1; then
        echo "✅ Application is running: $app_identifier"
        
        # Monitor resource usage
        local pid
        pid=$(pgrep -f "$app_identifier" | head -1)
        
        if [[ -n "$pid" ]]; then
            local cpu_usage
            local mem_usage
            cpu_usage=$(ps -p "$pid" -o pcpu= | xargs)
            mem_usage=$(ps -p "$pid" -o pmem= | xargs)
            
            echo "📊 Resource usage - CPU: ${cpu_usage}%, Memory: ${mem_usage}%"
            log_action "Post-launch monitoring: $app_identifier (PID: $pid, CPU: $cpu_usage%, Mem: $mem_usage%)"
        fi
    else
        echo "⚠️  Application not detected as running: $app_identifier"
        log_action "WARNING: Application launch successful but not detected running: $app_identifier"
    fi
}

# Bulk application deployment
bulk_app_deployment() {
    local app_list_file="$1"
    local deployment_mode="${2:-standard}"
    
    echo "=== Bulk Application Deployment ==="
    
    if [[ ! -f "$app_list_file" ]]; then
        echo "❌ Application list file not found: $app_list_file"
        return 1
    fi
    
    local success_count=0
    local failure_count=0
    local total_count=0
    
    while IFS= read -r app_line; do
        # Skip empty lines and comments
        if [[ -z "$app_line" || "$app_line" == \#* ]]; then
            continue
        fi
        
        # Parse app identifier and options
        local app_identifier
        local app_options
        read -r app_identifier app_options <<< "$app_line"
        
        ((total_count++))
        echo "Deploying ($total_count): $app_identifier"
        
        if enterprise_app_launch "$app_identifier" "$app_options" "$deployment_mode"; then
            ((success_count++))
        else
            ((failure_count++))
        fi
        
        echo "---"
        sleep 2  # Brief pause between deployments
    done < "$app_list_file"
    
    echo "=== Bulk Deployment Summary ==="
    echo "Total applications: $total_count"
    echo "Successful launches: $success_count"
    echo "Failed launches: $failure_count"
    
    log_action "Bulk deployment completed: $success_count/$total_count successful"
    audit_log "BULK_DEPLOYMENT" "MULTIPLE" "COMPLETED" "Success: $success_count Failed: $failure_count Total: $total_count"
}

# Application lifecycle management
manage_app_lifecycle() {
    local action="$1"
    local app_identifier="$2"
    
    case "$action" in
        "install")
            install_application "$app_identifier"
            ;;
        "update")
            update_application "$app_identifier"
            ;;
        "remove")
            remove_application "$app_identifier"
            ;;
        "status")
            check_app_status "$app_identifier"
            ;;
        *)
            echo "Invalid lifecycle action: $action"
            return 1
            ;;
    esac
}

# Check system resources before launch
check_system_resources() {
    echo "=== System Resource Check ==="
    
    # Check available memory
    local available_memory
    available_memory=$(vm_stat | grep "Pages free" | awk '{print $3}' | tr -d '.')
    available_memory=$((available_memory * 4096 / 1024 / 1024))  # Convert to MB
    
    echo "Available Memory: ${available_memory}MB"
    
    if [[ $available_memory -lt 512 ]]; then
        echo "⚠️  Low memory warning: ${available_memory}MB available"
        log_action "Low memory warning during app launch: ${available_memory}MB"
    fi
    
    # Check CPU load
    local load_average
    load_average=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | tr -d ',')
    
    echo "System Load: $load_average"
    
    if (( $(echo "$load_average > 5.0" | bc -l) )); then
        echo "⚠️  High system load: $load_average"
        log_action "High system load during app launch: $load_average"
    fi
}

# Generate application deployment report
generate_deployment_report() {
    local report_file="/Library/MacFleet/Reports/app_deployment_report_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Application Deployment Report ==="
    
    mkdir -p "$(dirname "$report_file")"
    
    # Count recent deployments from audit log
    local recent_launches=0
    local successful_launches=0
    local failed_launches=0
    
    if [[ -f "$DEPLOYMENT_LOG" ]]; then
        recent_launches=$(grep -c "ACTION:LAUNCH" "$DEPLOYMENT_LOG" 2>/dev/null || echo 0)
        successful_launches=$(grep -c "ACTION:LAUNCH.*RESULT:SUCCESS" "$DEPLOYMENT_LOG" 2>/dev/null || echo 0)
        failed_launches=$(grep -c "ACTION:LAUNCH.*RESULT:FAILED" "$DEPLOYMENT_LOG" 2>/dev/null || echo 0)
    fi
    
    # Get system information
    local total_apps
    total_apps=$(find /Applications -name "*.app" -maxdepth 1 | wc -l)
    
    cat > "$report_file" << EOF
{
  "report_type": "application_deployment",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "device_info": {
    "hostname": "$(hostname)",
    "os_version": "$(sw_vers -productVersion)",
    "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
  },
  "deployment_statistics": {
    "total_applications": $total_apps,
    "recent_launches": $recent_launches,
    "successful_launches": $successful_launches,
    "failed_launches": $failed_launches,
    "success_rate": "$(echo "scale=2; $successful_launches * 100 / ($successful_launches + $failed_launches + 1)" | bc)%"
  },
  "policy_configuration": {
    "whitelist_enforcement": $WHITELIST_ENFORCEMENT,
    "signature_validation": $VALIDATE_APP_SIGNATURES,
    "business_hours_enforcement": $BUSINESS_HOURS_ENFORCEMENT,
    "dependency_checking": $DEPENDENCY_CHECKING
  },
  "security_status": {
    "quarantine_protection": $QUARANTINE_UNKNOWN_APPS,
    "malware_scanning": $MALWARE_SCANNING,
    "certificate_validation": $CERTIFICATE_VALIDATION,
    "audit_enabled": $AUDIT_ALL_LAUNCHES
  }
}
EOF
    
    echo "Application deployment report saved to: $report_file"
    log_action "Deployment report generated: $report_file"
}

# Main function with argument handling
main() {
    log_action "=== MacFleet Application Launch Management Tool Started ==="
    
    case "${1:-help}" in
        "launch")
            enterprise_app_launch "$2" "$3" "$4"
            ;;
        "bulk")
            bulk_app_deployment "$2" "$3"
            ;;
        "lifecycle")
            manage_app_lifecycle "$2" "$3"
            ;;
        "report")
            generate_deployment_report
            ;;
        *)
            echo "MacFleet Enterprise Application Launch Management Tool"
            echo "Usage: $0 [command] [options]"
            echo ""
            echo "Commands:"
            echo "  launch [app_name/bundle_id] [options] [mode]  - Launch application with enterprise controls"
            echo "  bulk [list_file] [mode]                      - Bulk deployment from file list"
            echo "  lifecycle [action] [app_identifier]          - Manage application lifecycle"
            echo "  report                                       - Generate deployment report"
            echo ""
            echo "Launch Modes:"
            echo "  standard      - Normal application launch"
            echo "  background    - Launch in background"
            echo "  hidden        - Launch hidden"
            echo "  new-instance  - Force new instance"
            echo ""
            echo "Examples:"
            echo "  $0 launch \"Safari\"                         - Launch Safari normally"
            echo "  $0 launch com.apple.Safari \"\" background   - Launch Safari in background"
            echo "  $0 bulk essential_apps.txt                  - Deploy apps from list"
            echo "  $0 lifecycle status \"Microsoft Word\"       - Check Word installation status"
            ;;
    esac
    
    log_action "=== Application launch management operation completed ==="
}

# Execute main function
main "$@"

## Advanced Application Management Features

### Smart Application Deployment

```bash
#!/bin/bash

# Intelligent application deployment with machine learning
intelligent_deployment() {
    local app_identifier="$1"
    
    echo "=== Intelligent Application Deployment ==="
    
    # Analyze user patterns
    local usage_pattern
    usage_pattern=$(analyze_usage_patterns "$app_identifier")
    
    # Determine optimal launch strategy
    case "$usage_pattern" in
        "heavy_user")
            # Pre-launch for frequent users
            enterprise_app_launch "$app_identifier" "" "background"
            ;;
        "occasional_user")
            # Standard launch
            enterprise_app_launch "$app_identifier"
            ;;
        "new_user")
            # Guided launch with tutorial
            launch_with_guidance "$app_identifier"
            ;;
    esac
}

# Application health monitoring
monitor_app_health() {
    local app_identifier="$1"
    
    echo "=== Application Health Monitoring ==="
    
    # Check for crashes
    local crash_logs
    crash_logs=$(find ~/Library/Logs/DiagnosticReports -name "*$app_identifier*" -mtime -1 2>/dev/null | wc -l)
    
    if [[ $crash_logs -gt 0 ]]; then
        echo "⚠️  Recent crashes detected: $crash_logs"
        log_action "Application health alert: $app_identifier has $crash_logs recent crashes"
    fi
    
    # Performance monitoring
    local pid
    pid=$(pgrep -f "$app_identifier" | head -1)
    
    if [[ -n "$pid" ]]; then
        local memory_pressure
        memory_pressure=$(ps -p "$pid" -o pmem= | xargs)
        
        if (( $(echo "$memory_pressure > 10.0" | bc -l) )); then
            echo "⚠️  High memory usage: ${memory_pressure}%"
            log_action "Performance alert: $app_identifier using ${memory_pressure}% memory"
        fi
    fi
}

## Important Configuration Notes

### macOS Application Launch Commands

- **`open -a`** - Launch by application name
- **`open -b`** - Launch by bundle identifier  
- **`open -g`** - Launch in background
- **`open -n`** - Open new instance
- **`open -j`** - Launch hidden

### Enterprise Integration Points

- **Application Catalog Management** - Centralized app repository
- **License Management Systems** - Automated license validation
- **Security Platforms** - Integration with endpoint protection
- **Performance Monitoring** - APM platform integration

### Best Practices for Enterprise App Launch

1. **Security and Validation**
   - Validate code signatures before launching
   - Enforce application whitelists
   - Check for malware and quarantine status
   - Monitor for suspicious behavior

2. **User Experience**
   - Provide clear feedback on launch status
   - Implement intelligent pre-loading
   - Handle failures gracefully
   - Support offline scenarios

3. **Performance and Resources**
   - Monitor system resources before launch
   - Implement load balancing for resource-intensive apps
   - Track application performance metrics
   - Optimize launch sequences

Remember to test application launch procedures thoroughly in a controlled environment before implementing across your entire MacFleet to ensure system stability and user productivity. 

Tutorial

Novas atualizações e melhorias para a Macfleet.

Configurando um Runner do GitHub Actions em um Mac Mini (Apple Silicon)

Runner do GitHub Actions

GitHub Actions é uma plataforma poderosa de CI/CD que permite automatizar seus fluxos de trabalho de desenvolvimento de software. Embora o GitHub ofereça runners hospedados, runners auto-hospedados fornecem maior controle e personalização para sua configuração de CI/CD. Este tutorial o guia através da configuração e conexão de um runner auto-hospedado em um Mac mini para executar pipelines do macOS.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Um Mac mini (registre-se no Macfleet)
  • Um repositório GitHub com direitos de administrador
  • Um gerenciador de pacotes instalado (preferencialmente Homebrew)
  • Git instalado em seu sistema

Passo 1: Criar uma Conta de Usuário Dedicada

Primeiro, crie uma conta de usuário dedicada para o runner do GitHub Actions:

# Criar a conta de usuário '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

# Definir a senha para o usuário
sudo dscl . -passwd /Users/gh-runner sua_senha

# Adicionar 'gh-runner' ao grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Mude para a nova conta de usuário:

su gh-runner

Passo 2: Instalar Software Necessário

Instale Git e Rosetta 2 (se estiver usando Apple Silicon):

# Instalar Git se ainda não estiver instalado
brew install git

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

Passo 3: Configurar o Runner do GitHub Actions

  1. Vá para seu repositório GitHub
  2. Navegue para Configurações > Actions > Runners

Runner do GitHub Actions

  1. Clique em "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecione macOS como imagem do runner e ARM64 como arquitetura
  3. Siga os comandos fornecidos para baixar e configurar o runner

Runner do GitHub Actions

Crie um arquivo .env no diretório _work do runner:

# arquivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Execute o script run.sh em seu diretório do runner para completar a configuração.
  2. Verifique se o runner está ativo e ouvindo por trabalhos no terminal e verifique as configurações do repositório GitHub para a associação do runner e status Idle.

Runner do GitHub Actions

Passo 4: Configurar Sudoers (Opcional)

Se suas ações requerem privilégios de root, configure o arquivo sudoers:

sudo visudo

Adicione a seguinte linha:

gh-runner ALL=(ALL) NOPASSWD: ALL

Passo 5: Usar o Runner em Fluxos de Trabalho

Configure seu fluxo de trabalho do GitHub Actions para usar o runner auto-hospedado:

name: Fluxo de trabalho de exemplo

on:
  workflow_dispatch:

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

O runner está autenticado em seu repositório e rotulado com self-hosted, macOS, e ARM64. Use-o em seus fluxos de trabalho especificando estes rótulos no campo runs-on:

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

Melhores Práticas

  • Mantenha seu software do runner atualizado
  • Monitore regularmente os logs do runner para problemas
  • Use rótulos específicos para diferentes tipos de runners
  • Implemente medidas de segurança adequadas
  • Considere usar múltiplos runners para balanceamento de carga

Solução de Problemas

Problemas comuns e soluções:

  1. Runner não conectando:

    • Verifique conectividade de rede
    • Verifique validade do token GitHub
    • Certifique-se de permissões adequadas
  2. Falhas de build:

    • Verifique instalação do Xcode
    • Verifique dependências necessárias
    • Revise logs do fluxo de trabalho
  3. Problemas de permissão:

    • Verifique permissões do usuário
    • Verifique configuração sudoers
    • Revise permissões do sistema de arquivos

Conclusão

Agora você tem um runner auto-hospedado do GitHub Actions configurado em seu Mac mini. Esta configuração fornece mais controle sobre seu ambiente CI/CD e permite executar fluxos de trabalho específicos do macOS de forma eficiente.

Lembre-se de manter regularmente seu runner e mantê-lo atualizado com os patches de segurança e versões de software mais recentes.

Aplicativo Nativo

Aplicativo nativo do Macfleet

Guia de Instalação do Macfleet

Macfleet é uma solução poderosa de gerenciamento de frota projetada especificamente para ambientes Mac Mini hospedados na nuvem. Como provedor de hospedagem na nuvem Mac Mini, você pode usar o Macfleet para monitorar, gerenciar e otimizar toda sua frota de instâncias Mac virtualizadas.

Este guia de instalação o conduzirá através da configuração do monitoramento do Macfleet em sistemas macOS, Windows e Linux para garantir supervisão abrangente de sua infraestrutura na nuvem.

🍎 macOS

  • Baixe o arquivo .dmg para Mac aqui
  • Clique duas vezes no arquivo .dmg baixado
  • Arraste o aplicativo Macfleet para a pasta Aplicativos
  • Ejete o arquivo .dmg
  • Abra Preferências do Sistema > Segurança e Privacidade
    • Aba Privacidade > Acessibilidade
    • Marque Macfleet para permitir monitoramento
  • Inicie o Macfleet a partir de Aplicativos
  • O rastreamento inicia automaticamente

🪟 Windows

  • Baixe o arquivo .exe para Windows aqui
  • Clique com o botão direito no arquivo .exe > "Executar como administrador"
  • Siga o assistente de instalação
  • Aceite os termos e condições
  • Permita no Windows Defender se solicitado
  • Conceda permissões de monitoramento de aplicativo
  • Inicie o Macfleet a partir do Menu Iniciar
  • O aplicativo começa o rastreamento automaticamente

🐧 Linux

  • Baixe o pacote .deb (Ubuntu/Debian) ou .rpm (CentOS/RHEL) aqui
  • Instale usando seu gerenciador de pacotes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permita permissões de acesso X11 se solicitado
  • Adicione o usuário aos grupos apropriados se necessário
  • Inicie o Macfleet a partir do menu Aplicativos
  • O aplicativo começa o rastreamento automaticamente

Nota: Após a instalação em todos os sistemas, faça login com suas credenciais do Macfleet para sincronizar dados com seu painel de controle.