# Zabbix

Cosas de zabbix

# Zabbix - Creación de un host vía Agent2 con templates básicos

## Introducción

Esta guía cubre la configuración completa de un host en Zabbix 7.4+ utilizando Agent2 con templates para monitorización de sistema (Linux), servicios web (Nginx) y aplicaciones (MySQL, PHP-FPM).

## Prerrequisitos

- Zabbix Server 7.4+
- Host destino con Ubuntu/Debian
- Agent2 instalado y configurado básicamente
- Servicios a monitorizar funcionando (Nginx, MySQL, PHP-FPM)

## 1. Configuración inicial Agent2

### 1.1 Configuración básica de conectividad

Editar `/etc/zabbix/zabbix_agent2.conf`:

```ini
# Configuración básica
Server=ZABBIX_SERVER_IP
ServerActive=ZABBIX_SERVER_IP
Hostname=subdomain.domain.tld

# Configuración de log
LogFile=/var/log/zabbix/zabbix_agent2.log
LogFileSize=10

# Configuración de timeout
Timeout=30
```

### 1.2 Crear el host en Zabbix Server

1. **Configuration → Hosts → Create host**
2. **Host name:** `subdomain.domain.tld` (exactamente como en Agent2)
3. **Visible name:** Nombre descriptivo del host
4. **Groups:** Seleccionar grupo apropiado (ej: Linux servers)
5. **Templates:** **NINGUNO inicialmente**
6. **Interface:** Agent, IP del host, puerto 10050
7. **Save**

### 1.3 Verificar conectividad básica

Verificar en **Monitoring → Hosts** que aparezca "Available" en verde.

## 2. Configuración de templates básicos

### 2.1 Template de sistema Linux

Una vez verificada la conectividad básica:

1. **Configuration → Hosts → [host] → Templates**
2. **Add:** `Linux by Zabbix agent active`
3. **Update**

Esperar unos minutos y verificar que se reciben datos del sistema.

## 3. Configuración de MySQL

### 3.1 Usuario de monitorización en MySQL

```sql
-- Crear usuario específico para Zabbix
CREATE USER 'zabbix_monitor'@'127.0.0.1' IDENTIFIED BY 'password_segura';

-- Permisos mínimos necesarios
GRANT PROCESS ON *.* TO 'zabbix_monitor'@'127.0.0.1';
GRANT REPLICATION CLIENT ON *.* TO 'zabbix_monitor'@'127.0.0.1';
GRANT SELECT ON performance_schema.* TO 'zabbix_monitor'@'127.0.0.1';

FLUSH PRIVILEGES;
```

### 3.2 Configuración Agent2 para MySQL

En `/etc/zabbix/zabbix_agent2.conf`:

```ini
# Plugin MySQL
Plugins.Mysql.Sessions.mysql1.Uri=tcp://localhost:3306
Plugins.Mysql.Sessions.mysql1.User=zabbix
Plugins.Mysql.Sessions.mysql1.Password=password_segura
```

### 3.3 Template MySQL

1. **Configuration → Hosts → [host] → Templates**
2. **Add:** `MySQL by Zabbix agent 2`
3. **Update**

Reiniciar Agent2: `systemctl restart zabbix-agent2`

## 4. Configuración de Nginx

### 4.1 Habilitar stub_status en Nginx

Crear server block para monitorización en `/etc/nginx/nginx.conf` (dentro del bloque http):

```nginx
server {
    listen 127.0.0.1:80;
    server_name localhost;
    
    location = /nginx_status {
        stub_status;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}
```

### 4.2 Configuración Agent2 para Nginx

En `/etc/zabbix/zabbix_agent2.conf`:

```ini
# Plugin Nginx
Plugins.Nginx.Sessions.nginx1.Url=http://127.0.0.1/nginx_status
```

### 4.3 Template Nginx

1. **Configuration → Hosts → [host] → Templates**
2. **Add:** `Nginx by Zabbix agent 2`
3. **Update**

Reiniciar servicios:
```bash
systemctl reload nginx
systemctl restart zabbix-agent2
```

## 5. Configuración de PHP-FPM (múltiples pools)

### 5.1 Configuración de pools PHP-FPM

Para cada pool que se desee monitorizar, editar el archivo de configuración correspondiente:

**Ejemplo pool1:** `/etc/php/8.2/fpm/pool.d/pool1.domain.tld.conf`
```ini
pm.status_path = /status-pool1
ping.path = /ping-pool1
```

**Ejemplo pool2:** `/etc/php/8.3/fpm/pool.d/pool2.domain.tld.conf`
```ini
pm.status_path = /status-pool2
ping.path = /ping-pool2
```

### 5.2 Configuración Nginx para PHP-FPM

Añadir al server block de monitorización:

```nginx
server {
    listen 127.0.0.1:80;
    server_name localhost;
    
    # Nginx status
    location = /nginx_status {
        stub_status;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
    
    # Enable php-fpm status page
    location ~ ^/(statuscoresitelight|pingcoresitelight)$ {
        ## disable access logging for request if you prefer
        access_log off;

        ## Only allow trusted IPs for security, deny everyone else
        allow 127.0.0.1;
        allow 91.121.226.50;    # your IP here
        deny all;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
        ## Now the port or socket of the php-fpm pool we want the status of
        fastcgi_pass unix:/run/php/coresitelight_endesarrollo_ovh-fpm.sock;
        # fastcgi_pass unix:/run/php-fpm/your_socket.sock;
    }
}
```

### 5.3 Configuración Agent2 para PHP-FPM

En `/etc/zabbix/zabbix_agent2.conf` (configurar solo el pool principal):

```ini
# Plugin PHP-FPM (pool principal) - URLs específicas requeridas
Plugins.PhpFpm.Sessions.php-fpm.StatusUrl=http://127.0.0.1/status-pool1
Plugins.PhpFpm.Sessions.php-fpm.PingUrl=http://127.0.0.1/ping-pool1
```

**Nota:** Para monitorizar múltiples pools simultáneamente:

```ini
# Pool 1
Plugins.PhpFpm.Sessions.pool1.StatusUrl=http://127.0.0.1/status-pool1
Plugins.PhpFpm.Sessions.pool1.PingUrl=http://127.0.0.1/ping-pool1

# Pool 2
Plugins.PhpFpm.Sessions.pool2.StatusUrl=http://127.0.0.1/status-pool2
Plugins.PhpFpm.Sessions.pool2.PingUrl=http://127.0.0.1/ping-pool2
```

*Para múltiples pools se requieren templates personalizados o items custom.*

### 5.4 Template PHP-FPM

1. **Configuration → Hosts → [host] → Templates**
2. **Add:** `PHP-FPM by Zabbix agent 2`
3. **Update**

Reiniciar servicios:
```bash
systemctl restart php*-fpm nginx zabbix-agent2
```

## 6. Verificación final

### 6.1 Tests manuales

```bash
# Test Nginx
curl http://127.0.0.1/nginx_status

# Test PHP-FPM
curl http://127.0.0.1/status-pool1
curl http://127.0.0.1/ping-pool1

# Test MySQL (como usuario zabbix)
mysql -u zabbix -p -e "SHOW GLOBAL STATUS LIKE 'Uptime';"
```

### 6.2 Verificación en Zabbix

1. **Monitoring → Hosts** - Verificar que todos los templates aparecen como "Available"
2. **Monitoring → Latest data** - Comprobar que se reciben métricas de todos los servicios
3. **Monitoring → Problems** - Verificar que no hay alertas críticas

## 7. Troubleshooting común

### 7.1 Host no encontrado
- Verificar que el hostname en Agent2 coincide exactamente con el del servidor
- Comprobar conectividad de red entre agent y servidor

### 7.2 MySQL plugin fallos
- Verificar permisos del usuario zabbix en MySQL
- Comprobar sintaxis de la configuración en Agent2
- Revisar logs: `/var/log/zabbix/zabbix_agent2.log`

### 7.3 PHP-FPM "File not found"
- Verificar que el socket existe: `ls -la /run/php/`
- Comprobar configuración de pools PHP-FPM
- Verificar sintaxis de configuración Nginx

### 7.4 Templates conflictivos
- No usar templates "agent" y "agent active" simultáneamente
- Usar solo "agent active" para Agent2

## 8. Configuración de seguridad (opcional)

### 8.1 PSK (Pre-Shared Key)

Generar clave:
```bash
openssl rand -hex 32
```

En Agent2:
```ini
TLSConnect=psk
TLSAccept=psk
TLSPSKIdentity=host-psk-identity
TLSPSKFile=/etc/zabbix/zabbix_agent2.psk
```

En servidor: configurar la misma identity y clave en la configuración del host.

## Notas finales

- Añadir templates gradualmente, no todos de una vez
- Verificar funcionalidad después de cada template
- Para múltiples pools PHP-FPM, considerar items custom para pools secundarios
- Los logs de Agent2 en `/var/log/zabbix/zabbix_agent2.log` son esenciales para debugging

---
*Guía probada en Zabbix 7.4.2 con Ubuntu 22.04/24.04*