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.

File and Folder Copy Management on macOS

Efficiently manage file and folder copying operations across your MacFleet deployment with enterprise-grade safety features, integrity verification, and comprehensive audit capabilities. This tutorial transforms basic cp commands into robust data distribution solutions.

Understanding Enterprise File Copy Operations

Enterprise file copying goes beyond basic duplication, requiring:

  • Safety validation to prevent accidental overwrites
  • Integrity verification to ensure data consistency
  • Permission preservation for security compliance
  • Progress monitoring for large operations
  • Rollback capabilities for failed transfers
  • Audit logging for compliance requirements

Core Copy Operations

Basic File Copy

#!/bin/bash

# Simple file copy with validation
copy_file() {
    local source="$1"
    local destination="$2"
    
    # Validate source exists
    if [[ ! -f "$source" ]]; then
        echo "Error: Source file '$source' not found"
        return 1
    fi
    
    # Create destination directory if needed
    local dest_dir=$(dirname "$destination")
    mkdir -p "$dest_dir"
    
    # Copy file
    if cp "$source" "$destination"; then
        echo "Successfully copied '$source' to '$destination'"
        return 0
    else
        echo "Failed to copy '$source' to '$destination'"
        return 1
    fi
}

# Usage example
# copy_file "/Users/admin/document.pdf" "/Users/shared/documents/document.pdf"

Basic Directory Copy

#!/bin/bash

# Recursive directory copy with verification
copy_directory() {
    local source="$1"
    local destination="$2"
    
    # Validate source directory exists
    if [[ ! -d "$source" ]]; then
        echo "Error: Source directory '$source' not found"
        return 1
    fi
    
    # Copy directory recursively
    if cp -R "$source" "$destination"; then
        echo "Successfully copied directory '$source' to '$destination'"
        return 0
    else
        echo "Failed to copy directory '$source' to '$destination'"
        return 1
    fi
}

# Usage example
# copy_directory "/Users/admin/project" "/Users/shared/projects/"

Enterprise Copy Management System

#!/bin/bash

# MacFleet Enterprise File Copy Management System
# Comprehensive file and folder copying with enterprise features

# Configuration
SCRIPT_NAME="MacFleet Copy Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_copy_operations.log"
TEMP_DIR="/tmp/macfleet_copy"
MAX_FILE_SIZE="10G"
ALLOWED_EXTENSIONS=(".pdf" ".docx" ".xlsx" ".pptx" ".txt" ".png" ".jpg" ".gif" ".mp4" ".mov")
RESTRICTED_PATHS=("/System" "/usr/bin" "/usr/sbin" "/private/var")
BUSINESS_HOURS_START=9
BUSINESS_HOURS_END=17

# Create necessary directories
mkdir -p "$TEMP_DIR"
mkdir -p "$(dirname "$LOG_FILE")"

# Logging function
log_operation() {
    local level="$1"
    local message="$2"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] [$level] $message" | tee -a "$LOG_FILE"
}

# Check if current time is within business hours
is_business_hours() {
    local current_hour=$(date +%H)
    if [[ $current_hour -ge $BUSINESS_HOURS_START && $current_hour -lt $BUSINESS_HOURS_END ]]; then
        return 0
    else
        return 1
    fi
}

# Validate file extension
is_allowed_extension() {
    local file="$1"
    local extension="${file##*.}"
    extension=".$extension"
    
    for allowed in "${ALLOWED_EXTENSIONS[@]}"; do
        if [[ "$extension" == "$allowed" ]]; then
            return 0
        fi
    done
    return 1
}

# Check if path is restricted
is_restricted_path() {
    local path="$1"
    for restricted in "${RESTRICTED_PATHS[@]}"; do
        if [[ "$path" == "$restricted"* ]]; then
            return 0
        fi
    done
    return 1
}

# Get file size in human readable format
get_file_size() {
    local file="$1"
    if [[ -f "$file" ]]; then
        stat -f%z "$file" 2>/dev/null
    elif [[ -d "$file" ]]; then
        du -sk "$file" 2>/dev/null | awk '{print $1 * 1024}'
    else
        echo "0"
    fi
}

# Convert bytes to human readable format
format_size() {
    local bytes="$1"
    local sizes=("B" "KB" "MB" "GB" "TB")
    local unit=0
    
    while [[ $bytes -gt 1024 && $unit -lt 4 ]]; do
        bytes=$((bytes / 1024))
        ((unit++))
    done
    
    echo "${bytes}${sizes[$unit]}"
}

# Calculate checksum for integrity verification
calculate_checksum() {
    local file="$1"
    if [[ -f "$file" ]]; then
        shasum -a 256 "$file" 2>/dev/null | awk '{print $1}'
    else
        echo ""
    fi
}

# Verify copy integrity
verify_copy_integrity() {
    local source="$1"
    local destination="$2"
    
    if [[ -f "$source" && -f "$destination" ]]; then
        local source_checksum=$(calculate_checksum "$source")
        local dest_checksum=$(calculate_checksum "$destination")
        
        if [[ "$source_checksum" == "$dest_checksum" ]]; then
            log_operation "INFO" "Integrity verification passed for: $destination"
            return 0
        else
            log_operation "ERROR" "Integrity verification failed for: $destination"
            return 1
        fi
    elif [[ -d "$source" && -d "$destination" ]]; then
        # For directories, compare file counts and sizes
        local source_count=$(find "$source" -type f | wc -l)
        local dest_count=$(find "$destination" -type f | wc -l)
        
        if [[ $source_count -eq $dest_count ]]; then
            log_operation "INFO" "Directory integrity verification passed for: $destination"
            return 0
        else
            log_operation "ERROR" "Directory integrity verification failed for: $destination"
            return 1
        fi
    else
        log_operation "ERROR" "Cannot verify integrity - source or destination missing"
        return 1
    fi
}

# Create backup before overwrite
create_backup() {
    local file="$1"
    local backup_dir="/var/backups/macfleet/copy_operations"
    local timestamp=$(date '+%Y%m%d_%H%M%S')
    
    mkdir -p "$backup_dir"
    
    if [[ -e "$file" ]]; then
        local filename=$(basename "$file")
        local backup_file="$backup_dir/${filename}_backup_$timestamp"
        
        if cp -R "$file" "$backup_file"; then
            log_operation "INFO" "Backup created: $backup_file"
            echo "$backup_file"
            return 0
        else
            log_operation "ERROR" "Failed to create backup for: $file"
            return 1
        fi
    fi
}

# Enhanced file copy with enterprise features
enterprise_copy_file() {
    local source="$1"
    local destination="$2"
    local preserve_permissions="${3:-true}"
    local verify_integrity="${4:-true}"
    local create_backup_flag="${5:-true}"
    
    log_operation "INFO" "Starting file copy operation: $source -> $destination"
    
    # Pre-flight validations
    if [[ ! -f "$source" ]]; then
        log_operation "ERROR" "Source file not found: $source"
        return 1
    fi
    
    # Check if source is restricted
    if is_restricted_path "$source"; then
        log_operation "ERROR" "Source path is restricted: $source"
        return 1
    fi
    
    # Check if destination is restricted
    if is_restricted_path "$destination"; then
        log_operation "ERROR" "Destination path is restricted: $destination"
        return 1
    fi
    
    # Validate file extension
    if ! is_allowed_extension "$source"; then
        log_operation "WARNING" "File extension not in allowed list: $source"
    fi
    
    # Check file size
    local file_size=$(get_file_size "$source")
    local max_size_bytes=$(echo "$MAX_FILE_SIZE" | sed 's/G//' | awk '{print $1 * 1024 * 1024 * 1024}')
    
    if [[ $file_size -gt $max_size_bytes ]]; then
        log_operation "ERROR" "File too large: $(format_size $file_size) > $MAX_FILE_SIZE"
        return 1
    fi
    
    # Business hours check for large files (>100MB)
    if [[ $file_size -gt 104857600 ]] && ! is_business_hours; then
        log_operation "WARNING" "Large file copy outside business hours: $(format_size $file_size)"
    fi
    
    # Create destination directory
    local dest_dir=$(dirname "$destination")
    if ! mkdir -p "$dest_dir"; then
        log_operation "ERROR" "Failed to create destination directory: $dest_dir"
        return 1
    fi
    
    # Create backup if destination exists
    local backup_file=""
    if [[ -f "$destination" && "$create_backup_flag" == "true" ]]; then
        backup_file=$(create_backup "$destination")
        if [[ $? -ne 0 ]]; then
            log_operation "ERROR" "Failed to create backup for existing file: $destination"
            return 1
        fi
    fi
    
    # Perform the copy operation
    local copy_options=""
    if [[ "$preserve_permissions" == "true" ]]; then
        copy_options="-p"
    fi
    
    if cp $copy_options "$source" "$destination"; then
        log_operation "INFO" "File copied successfully: $(format_size $file_size)"
        
        # Verify integrity if requested
        if [[ "$verify_integrity" == "true" ]]; then
            if ! verify_copy_integrity "$source" "$destination"; then
                log_operation "ERROR" "Copy integrity verification failed, removing destination"
                rm -f "$destination"
                
                # Restore backup if it exists
                if [[ -n "$backup_file" && -f "$backup_file" ]]; then
                    cp "$backup_file" "$destination"
                    log_operation "INFO" "Restored backup file: $destination"
                fi
                return 1
            fi
        fi
        
        # Log successful operation
        log_operation "SUCCESS" "File copy completed: $source -> $destination"
        return 0
    else
        log_operation "ERROR" "Copy operation failed: $source -> $destination"
        
        # Restore backup if it exists
        if [[ -n "$backup_file" && -f "$backup_file" ]]; then
            cp "$backup_file" "$destination"
            log_operation "INFO" "Restored backup file: $destination"
        fi
        return 1
    fi
}

# Enhanced directory copy with enterprise features
enterprise_copy_directory() {
    local source="$1"
    local destination="$2"
    local preserve_permissions="${3:-true}"
    local verify_integrity="${4:-true}"
    local create_backup_flag="${5:-true}"
    
    log_operation "INFO" "Starting directory copy operation: $source -> $destination"
    
    # Pre-flight validations
    if [[ ! -d "$source" ]]; then
        log_operation "ERROR" "Source directory not found: $source"
        return 1
    fi
    
    # Check if source is restricted
    if is_restricted_path "$source"; then
        log_operation "ERROR" "Source path is restricted: $source"
        return 1
    fi
    
    # Check if destination is restricted
    if is_restricted_path "$destination"; then
        log_operation "ERROR" "Destination path is restricted: $destination"
        return 1
    fi
    
    # Calculate directory size
    local dir_size=$(get_file_size "$source")
    local file_count=$(find "$source" -type f | wc -l)
    
    log_operation "INFO" "Directory stats - Size: $(format_size $dir_size), Files: $file_count"
    
    # Business hours check for large directories (>1GB or >1000 files)
    if [[ $dir_size -gt 1073741824 || $file_count -gt 1000 ]] && ! is_business_hours; then
        log_operation "WARNING" "Large directory copy outside business hours"
    fi
    
    # Create backup if destination exists
    local backup_dir=""
    if [[ -d "$destination" && "$create_backup_flag" == "true" ]]; then
        backup_dir=$(create_backup "$destination")
        if [[ $? -ne 0 ]]; then
            log_operation "ERROR" "Failed to create backup for existing directory: $destination"
            return 1
        fi
    fi
    
    # Perform the copy operation
    local copy_options="-R"
    if [[ "$preserve_permissions" == "true" ]]; then
        copy_options="-Rp"
    fi
    
    if cp $copy_options "$source" "$destination"; then
        log_operation "INFO" "Directory copied successfully: $(format_size $dir_size)"
        
        # Verify integrity if requested
        if [[ "$verify_integrity" == "true" ]]; then
            if ! verify_copy_integrity "$source" "$destination"; then
                log_operation "ERROR" "Directory copy integrity verification failed, removing destination"
                rm -rf "$destination"
                
                # Restore backup if it exists
                if [[ -n "$backup_dir" && -d "$backup_dir" ]]; then
                    cp -R "$backup_dir" "$destination"
                    log_operation "INFO" "Restored backup directory: $destination"
                fi
                return 1
            fi
        fi
        
        # Log successful operation
        log_operation "SUCCESS" "Directory copy completed: $source -> $destination"
        return 0
    else
        log_operation "ERROR" "Directory copy operation failed: $source -> $destination"
        
        # Restore backup if it exists
        if [[ -n "$backup_dir" && -d "$backup_dir" ]]; then
            cp -R "$backup_dir" "$destination"
            log_operation "INFO" "Restored backup directory: $destination"
        fi
        return 1
    fi
}

# Bulk copy operations with progress monitoring
bulk_copy_operation() {
    local operation_type="$1"  # "file" or "directory"
    local source_list="$2"     # File containing source paths
    local destination_base="$3" # Base destination directory
    
    if [[ ! -f "$source_list" ]]; then
        log_operation "ERROR" "Source list file not found: $source_list"
        return 1
    fi
    
    local total_items=$(wc -l < "$source_list")
    local current_item=0
    local success_count=0
    local failure_count=0
    
    log_operation "INFO" "Starting bulk copy operation - Total items: $total_items"
    
    while IFS= read -r source_path; do
        ((current_item++))
        
        # Skip empty lines and comments
        [[ -z "$source_path" || "$source_path" =~ ^#.* ]] && continue
        
        local filename=$(basename "$source_path")
        local destination="$destination_base/$filename"
        
        echo "Processing [$current_item/$total_items]: $filename"
        
        if [[ "$operation_type" == "file" ]]; then
            if enterprise_copy_file "$source_path" "$destination"; then
                ((success_count++))
            else
                ((failure_count++))
            fi
        elif [[ "$operation_type" == "directory" ]]; then
            if enterprise_copy_directory "$source_path" "$destination"; then
                ((success_count++))
            else
                ((failure_count++))
            fi
        fi
        
        # Progress update
        local progress=$((current_item * 100 / total_items))
        echo "Progress: $progress% ($success_count successful, $failure_count failed)"
        
    done < "$source_list"
    
    log_operation "SUCCESS" "Bulk copy completed - Success: $success_count, Failed: $failure_count"
    return $failure_count
}

# Generate copy operation report
generate_copy_report() {
    local report_file="/tmp/macfleet_copy_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Copy Operations Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "=============================="
        echo ""
        
        echo "Recent Copy Operations (Last 24 hours):"
        if [[ -f "$LOG_FILE" ]]; then
            local yesterday=$(date -v-1d '+%Y-%m-%d')
            grep "$yesterday\|$(date '+%Y-%m-%d')" "$LOG_FILE" | tail -50
        else
            echo "No log file found"
        fi
        
        echo ""
        echo "System Information:"
        echo "Available Space:"
        df -h | grep -E "^/dev/"
        
        echo ""
        echo "Copy Operation Statistics:"
        if [[ -f "$LOG_FILE" ]]; then
            echo "Total Operations: $(grep -c "copy operation" "$LOG_FILE" 2>/dev/null || echo "0")"
            echo "Successful: $(grep -c "SUCCESS.*copy completed" "$LOG_FILE" 2>/dev/null || echo "0")"
            echo "Failed: $(grep -c "ERROR.*copy.*failed" "$LOG_FILE" 2>/dev/null || echo "0")"
        fi
        
    } > "$report_file"
    
    echo "Copy operations report saved to: $report_file"
    log_operation "INFO" "Copy report generated: $report_file"
}

# Main copy management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "copy-file")
            local source="$2"
            local destination="$3"
            local preserve_perms="${4:-true}"
            local verify="${5:-true}"
            local backup="${6:-true}"
            
            if [[ -z "$source" || -z "$destination" ]]; then
                echo "Usage: $0 copy-file <source> <destination> [preserve_permissions] [verify_integrity] [create_backup]"
                exit 1
            fi
            
            enterprise_copy_file "$source" "$destination" "$preserve_perms" "$verify" "$backup"
            ;;
        "copy-directory")
            local source="$2"
            local destination="$3"
            local preserve_perms="${4:-true}"
            local verify="${5:-true}"
            local backup="${6:-true}"
            
            if [[ -z "$source" || -z "$destination" ]]; then
                echo "Usage: $0 copy-directory <source> <destination> [preserve_permissions] [verify_integrity] [create_backup]"
                exit 1
            fi
            
            enterprise_copy_directory "$source" "$destination" "$preserve_perms" "$verify" "$backup"
            ;;
        "bulk-files")
            local source_list="$2"
            local destination="$3"
            
            if [[ -z "$source_list" || -z "$destination" ]]; then
                echo "Usage: $0 bulk-files <source_list_file> <destination_directory>"
                exit 1
            fi
            
            bulk_copy_operation "file" "$source_list" "$destination"
            ;;
        "bulk-directories")
            local source_list="$2"
            local destination="$3"
            
            if [[ -z "$source_list" || -z "$destination" ]]; then
                echo "Usage: $0 bulk-directories <source_list_file> <destination_directory>"
                exit 1
            fi
            
            bulk_copy_operation "directory" "$source_list" "$destination"
            ;;
        "report")
            generate_copy_report
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise File and Folder Copy Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  copy-file <source> <destination>       - Copy single file"
            echo "  copy-directory <source> <destination>  - Copy directory recursively"
            echo "  bulk-files <list_file> <destination>   - Bulk copy files from list"
            echo "  bulk-directories <list_file> <dest>    - Bulk copy directories from list"
            echo "  report                                  - Generate operations report"
            echo "  help                                    - Show this help message"
            echo ""
            echo "Features:"
            echo "  • Safety validation and integrity verification"
            echo "  • Automatic backup creation before overwrite"
            echo "  • Business hours compliance checking"
            echo "  • Comprehensive audit logging"
            echo "  • Permission preservation"
            echo "  • Progress monitoring for bulk operations"
            ;;
    esac
}

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

Quick Reference Commands

Single File Operations

# Copy file with full enterprise features
./copy_manager.sh copy-file "/Users/admin/document.pdf" "/Users/shared/documents/document.pdf"

# Copy file without backup creation
./copy_manager.sh copy-file "/source/file.txt" "/destination/file.txt" true true false

# Copy file without integrity verification (faster)
./copy_manager.sh copy-file "/source/file.txt" "/destination/file.txt" true false true

Directory Operations

# Copy directory with all subdirectories
./copy_manager.sh copy-directory "/Users/admin/project" "/Users/shared/projects/"

# Copy directory preserving permissions
./copy_manager.sh copy-directory "/source/folder" "/destination/" true true true

Bulk Operations

# Create file list for bulk operations
echo "/Users/admin/doc1.pdf" > /tmp/files_to_copy.txt
echo "/Users/admin/doc2.pdf" >> /tmp/files_to_copy.txt
echo "/Users/admin/doc3.pdf" >> /tmp/files_to_copy.txt

# Execute bulk file copy
./copy_manager.sh bulk-files "/tmp/files_to_copy.txt" "/Users/shared/documents/"

# Execute bulk directory copy
./copy_manager.sh bulk-directories "/tmp/dirs_to_copy.txt" "/Users/shared/projects/"

Integration Examples

JAMF Pro Integration

#!/bin/bash

# JAMF Pro script for enterprise file distribution
# Parameters: $4 = source_path, $5 = destination_path, $6 = operation_type

SOURCE_PATH="$4"
DESTINATION_PATH="$5"
OPERATION_TYPE="$6"

# Download copy manager if not present
if [[ ! -f "/usr/local/bin/macfleet_copy_manager.sh" ]]; then
    curl -o "/usr/local/bin/macfleet_copy_manager.sh" "https://scripts.macfleet.com/copy_manager.sh"
    chmod +x "/usr/local/bin/macfleet_copy_manager.sh"
fi

# Execute copy operation
case "$OPERATION_TYPE" in
    "file")
        /usr/local/bin/macfleet_copy_manager.sh copy-file "$SOURCE_PATH" "$DESTINATION_PATH"
        ;;
    "directory")
        /usr/local/bin/macfleet_copy_manager.sh copy-directory "$SOURCE_PATH" "$DESTINATION_PATH"
        ;;
    *)
        echo "Invalid operation type: $OPERATION_TYPE"
        exit 1
        ;;
esac

# Generate report
/usr/local/bin/macfleet_copy_manager.sh report

exit $?

Configuration Profile for Copy Policies

<?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>PayloadContent</key>
    <array>
        <dict>
            <key>PayloadType</key>
            <string>com.macfleet.copy.policy</string>
            <key>PayloadIdentifier</key>
            <string>com.macfleet.copy.policy.main</string>
            <key>PayloadDisplayName</key>
            <string>MacFleet Copy Policy</string>
            <key>MaxFileSize</key>
            <string>10G</string>
            <key>AllowedExtensions</key>
            <array>
                <string>.pdf</string>
                <string>.docx</string>
                <string>.xlsx</string>
                <string>.pptx</string>
            </array>
            <key>BusinessHoursOnly</key>
            <true/>
            <key>RequireIntegrityCheck</key>
            <true/>
            <key>CreateBackups</key>
            <true/>
        </dict>
    </array>
</dict>
</plist>

Security and Compliance Features

File System Monitoring

# Monitor copy operations with FSEvents
fswatch -r /Users/shared/ | while read event; do
    if [[ "$event" =~ "CREATED" ]]; then
        log_operation "MONITOR" "File created: $event"
    fi
done

Compliance Reporting

# Generate compliance report for auditors
generate_compliance_report() {
    local report_file="/var/reports/copy_compliance_$(date +%Y%m%d).csv"
    
    echo "Timestamp,User,Source,Destination,Size,Status,Checksum" > "$report_file"
    
    # Parse log file for copy operations
    grep "copy completed\|copy.*failed" "$LOG_FILE" | while read line; do
        # Extract relevant information and format as CSV
        echo "$line" | awk -F' - ' '{print $1","$2}' >> "$report_file"
    done
    
    echo "Compliance report generated: $report_file"
}

Troubleshooting

Common Issues and Solutions

IssueCauseSolution
Permission deniedInsufficient privilegesRun with sudo or check file permissions
Disk space errorDestination fullCheck available space with df -h
Integrity check failedCorrupt copyRe-run copy operation, check disk health
Source not foundIncorrect pathVerify source path exists
Operation timeoutLarge file/slow diskIncrease timeout or split operation

Log Analysis

# View recent copy operations
tail -f /var/log/macfleet_copy_operations.log

# Search for failed operations
grep "ERROR" /var/log/macfleet_copy_operations.log

# Count operations by status
grep -c "SUCCESS" /var/log/macfleet_copy_operations.log
grep -c "ERROR" /var/log/macfleet_copy_operations.log

Best Practices

  1. Always test on single device before fleet deployment
  2. Monitor disk space before large copy operations
  3. Use business hours restrictions for resource-intensive operations
  4. Enable integrity verification for critical data
  5. Maintain regular backups of important destinations
  6. Review logs regularly for failed operations
  7. Set appropriate file size limits based on network capacity
  8. Use bulk operations for efficiency at scale

This enterprise copy management system provides comprehensive safety, monitoring, and compliance features while maintaining the simplicity of basic copy operations for day-to-day fleet management tasks.

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.