# Complete Optimized LVM Setup Guide for Dell Optiplex with Dual SSDs

## System Specifications
- Device: Dell Optiplex
- CPU: Intel Core i7-4790
- RAM: 32GB
- Storage:
  - Drive 1 (sda): Samsung SSD 860 PRO 512GB (476.9G usable)
  - Drive 2 (sdb): PNY CS900 120GB SSD (111.8G usable)

## 1. Partition Scheme and LVM Setup

### System Drive (sdb - PNY CS900 111.8GB):
- /dev/sdb1 - 1GB   - /boot (standard partition, ext4)
- /dev/sdb2 - 1GB   - /boot/efi (standard partition, FAT32)
- /dev/sdb3 - Rest of sdb (~109.8GB) - LVM Physical Volume

LVM setup on sdb:
Volume Group: vg_system

Logical Volumes:
- lv_root  - 30GB  - /
- lv_home  - 25GB  - /home
- lv_var   - 15GB  - /var
- lv_tmp   - 5GB   - /tmp
- lv_swap  - 16GB  - swap
- lv_snap  - Rest of space - Reserved for snapshots

### Data Drive (sda - Samsung 860 PRO 476.9GB):
- /dev/sda1 - Entire disk - LVM Physical Volume

LVM setup on sda:
Volume Group: vg_data

Logical Volumes:
- lv_vms   - 400GB - /vms (for storing virtual machines)
- lv_data  - Rest of space (~76.9GB) - /data (for additional data and LVM practice)

All filesystems will use XFS except for swap and boot partitions.

## 2. Installation Process

1. Boot from Rocky Linux installation media.

2. In the installation wizard:
   a. Select language and keyboard layout.
   b. Set time zone.
   c. In the Installation Destination section:
      - Select both SSDs.
      - Choose "Custom" partitioning.
      - Create partitions and LVM setup as per the scheme above.
   d. Set root password and create a non-root user.
   e. Begin the installation.

3. After installation completes, reboot the system.

## 3. Post-Installation LVM Setup

After first boot, set up the data drive:

```bash
sudo pvcreate /dev/sda
sudo vgcreate vg_data /dev/sda
sudo lvcreate -L 400G -n lv_vms vg_data
sudo lvcreate -l 100%FREE -n lv_data vg_data
sudo mkfs.xfs /dev/vg_data/lv_vms
sudo mkfs.xfs /dev/vg_data/lv_data
sudo mkdir /vms /data
echo "/dev/vg_data/lv_vms /vms xfs defaults,discard 0 0" | sudo tee -a /etc/fstab
echo "/dev/vg_data/lv_data /data xfs defaults,discard 0 0" | sudo tee -a /etc/fstab
sudo mount -a
```

## 4. Initial OS Setup and Optimization

1. Update the system:
   ```bash
   sudo dnf update -y
   ```

2. Install essential packages:
   ```bash
   sudo dnf install -y vim tmux htop iftop iotop git wget curl
   ```

3. Configure firewall:
   ```bash
   sudo systemctl enable firewalld
   sudo systemctl start firewalld
   sudo firewall-cmd --set-default-zone=public
   sudo firewall-cmd --add-service=ssh --permanent
   sudo firewall-cmd --reload
   ```

4. Secure SSH:
   Edit `/etc/ssh/sshd_config`:
   ```bash
   sudo vim /etc/ssh/sshd_config
   ```
   Make these changes:
   - Change `#PermitRootLogin yes` to `PermitRootLogin no`
   - Set `PasswordAuthentication no` if using SSH keys
   - Add `AllowUsers your_username` at the end of the file

   Restart SSH service:
   ```bash
   sudo systemctl restart sshd
   ```

5. Set up automatic security updates:
   ```bash
   sudo dnf install dnf-automatic -y
   sudo systemctl enable --now dnf-automatic.timer
   ```

6. Configure NTP for accurate system time:
   ```bash
   sudo dnf install chrony -y
   sudo systemctl enable --now chronyd
   ```

7. Optimize SSD performance:
   Enable TRIM support:
   ```bash
   sudo systemctl enable fstrim.timer
   sudo systemctl start fstrim.timer
   ```

   Add `discard` option to fstab for all SSD partitions:
   ```bash
   sudo sed -i 's/defaults/defaults,discard/' /etc/fstab
   ```

   Optimize I/O scheduler for SSDs:
   ```bash
   echo 'ACTION=="add|change", KERNEL=="sd[ab]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="mq-deadline"' | sudo tee /etc/udev/rules.d/60-schedulers.rules
   ```

8. Optimize system performance:
   Edit `/etc/sysctl.conf`:
   ```bash
   sudo vim /etc/sysctl.conf
   ```
   Add these lines:
   ```
   # Increase system file descriptor limit
   fs.file-max = 100000

   # Optimize network performance
   net.core.somaxconn = 1024
   net.core.netdev_max_backlog = 5000
   net.core.rmem_max = 16777216
   net.core.wmem_max = 16777216
   net.ipv4.tcp_wmem = 4096 12582912 16777216
   net.ipv4.tcp_rmem = 4096 12582912 16777216
   net.ipv4.tcp_max_syn_backlog = 8096
   net.ipv4.tcp_slow_start_after_idle = 0
   net.ipv4.tcp_tw_reuse = 1
   ```
   Apply changes:
   ```bash
   sudo sysctl -p
   ```

9. Set up fail2ban to protect against brute force attacks:
   ```bash
   sudo dnf install fail2ban -y
   sudo systemctl enable --now fail2ban
   sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
   sudo sed -i 's/bantime  = 10m/bantime  = 1h/' /etc/fail2ban/jail.local
   sudo sed -i 's/maxretry = 5/maxretry = 3/' /etc/fail2ban/jail.local
   sudo systemctl restart fail2ban
   ```

10. Enable KVM nested virtualization for better VM performance:
    ```bash
    echo "options kvm-intel nested=1" | sudo tee /etc/modprobe.d/kvm-intel.conf
    ```

11. Set up a basic backup script:
    Create `/usr/local/bin/backup.sh`:
    ```bash
    sudo tee /usr/local/bin/backup.sh > /dev/null << EOL
    #!/bin/bash
    BACKUP_DIR="/data/backups"
    DIRS_TO_BACKUP=("/etc" "/home" "/var/log")
    
    mkdir -p \$BACKUP_DIR
    for dir in "\${DIRS_TO_BACKUP[@]}"; do
        tar -czf \$BACKUP_DIR/\$(basename \$dir)-\$(date +%F).tar.gz \$dir
    done
    
    # Keep only the last 7 backups
    find \$BACKUP_DIR -type f -mtime +7 -delete
    EOL

    sudo chmod +x /usr/local/bin/backup.sh
    ```
    Set up a cron job to run it daily:
    ```bash
    echo "0 2 * * * /usr/local/bin/backup.sh" | sudo tee -a /etc/crontab
    ```

12. Reboot to ensure all changes take effect:
    ```bash
    sudo reboot
    ```

## 5. Verification and Management Commands

- Display LVM information:
  ```bash
  sudo vgs    # View Volume Groups
  sudo lvs    # View Logical Volumes
  sudo pvs    # View Physical Volumes
  ```

- Extend a Logical Volume:
  ```bash
  sudo lvextend -L +10G /dev/vg_data/lv_data
  sudo xfs_growfs /data
  ```

- Create a snapshot:
  ```bash
  sudo lvcreate -L 5G -s -n lv_data_snapshot /dev/vg_data/lv_data
  ```

- Merge a snapshot:
  ```bash
  sudo lvconvert --merge /dev/vg_data/lv_data_snapshot
  ```

- Check disk usage:
  ```bash
  df -h
  ```

- Monitor system performance:
  ```bash
  htop
  ```

- View current LVM layout:
  ```bash
  sudo lvdisplay
  sudo vgdisplay
  ```

## 6. Next Steps and Learning Opportunities

1. Practice creating and managing LVM snapshots on the lv_data volume.
2. Experiment with extending and reducing logical volume sizes.
3. Set up a KVM virtual machine in the /vms directory and practice VM management.
4. Learn about LVM striping and mirroring (for future multi-disk setups).
5. Explore LVM thin provisioning for efficient storage use in VM environments.

## Conclusion

This setup provides a robust, flexible, and optimized system for your Dell Optiplex with dual SSDs. The LVM configuration allows for easy management and expansion of storage. Remember to regularly update your system, monitor performance, and perform backups, especially before making significant changes to the LVM structure.

As you become more comfortable with LVM, explore advanced features and always test in a safe environment before applying changes to critical data.

---

# **Complete Rocky Linux Lab Setup: Virtualization, Automation, and Networking**

This guide provides a step-by-step process for setting up an advanced lab environment on Rocky Linux, including virtualization, automation, networking, security, and monitoring. It covers everything from system preparation to multi-VM setups using Vagrant and libvirt.

---

## **Step 1: System Update and Repository Configuration**

Start by updating your system and configuring necessary repositories.

1. **Update the system**:
   ```bash
   sudo dnf update -y
   ```

2. **Enable the CodeReady Builder (CRB) repository**:
   ```bash
   sudo dnf config-manager --set-enabled crb
   ```

3. **Add the HashiCorp repository for Vagrant**:
   ```bash
   sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
   ```

4. **Import the GPG key for security** (optional but recommended):
   ```bash
   sudo rpm --import https://rpm.releases.hashicorp.com/gpg
   ```

5. **Refresh the package cache**:
   ```bash
   sudo dnf makecache
   ```

---

## **Step 2: Install Required Tools**

Install all necessary packages for virtualization, development, automation, and monitoring tools.

```bash
sudo dnf install -y \
  qemu-kvm \
  libvirt \
  libvirt-daemon-driver-qemu \
  libvirt-devel \
  vagrant \
  ruby-devel \
  gcc \
  ansible \
  python3 \
  python3-pip \
  bridge-utils \
  net-tools \
  wget \
  curl \
  vim \
  git \
  htop \
  iotop \
  iftop \
  firewalld \
  unzip \
  kernel-devel \
  kernel-headers
```

**Optional**: For a full development environment, install the complete "Development Tools" group:
```bash
sudo dnf groupinstall -y "Development Tools"
```

---

## **Step 3: Enable and Start Services**

Ensure the essential services for virtualization and security are running, and update your user permissions for VM management.

1. **Enable and start libvirt**:
   ```bash
   sudo systemctl enable --now libvirtd
   ```

2. **Enable and start firewalld**:
   ```bash
   sudo systemctl enable --now firewalld
   ```

3. **Add your user to the `libvirt` group**:
   ```bash
   sudo usermod -aG libvirt $USER
   ```

4. **Log out and log back in** or run the following command to apply group membership:
   ```bash
   newgrp libvirt
   ```

---

## **Step 4: Install Vagrant Plugins and Python Setup**

Install the **vagrant-libvirt** plugin and ensure **Python** is fully set up.

1. **Install the vagrant-libvirt plugin**:
   ```bash
   vagrant plugin install vagrant-libvirt
   ```

2. **Ensure pip is upgraded**:
   ```bash
   python3 -m pip install --upgrade pip
   ```

3. **Optional**: Use Python virtual environments to avoid affecting system-wide packages:
   ```bash
   python3 -m venv ~/venv
   source ~/venv/bin/activate
   ```

---

## **Step 5: Create and Run Virtual Machines**

Now that everything is installed, set up and run multiple virtual machines using Vagrant.

1. **Create a Vagrant project directory and initialize**:
   ```bash
   mkdir ~/vagrant-lab
   cd ~/vagrant-lab
   vagrant init generic/rocky9
   ```

2. **Modify the Vagrantfile** for a multi-VM setup (web and database servers):
   ```ruby
   Vagrant.configure("2") do |config|
     config.vm.box = "generic/rocky9"
     
     # Web server VM
     config.vm.define "web" do |web|
       web.vm.provider "libvirt" do |libvirt|
         libvirt.memory = 2048
         libvirt.cpus = 2
       end
       web.vm.network "private_network", ip: "192.168.56.10"
       web.vm.hostname = "webserver"
     end

     # Database server VM
     config.vm.define "db" do |db|
       db.vm.provider "libvirt" do |libvirt|
         libvirt.memory = 4096
         libvirt.cpus = 2
       end
       db.vm.network "private_network", ip: "192.168.56.11"
       db.vm.hostname = "dbserver"
     end
   end
   ```

3. **Bring up the VMs**:
   ```bash
   vagrant up --provider=libvirt
   ```

4. **SSH into the VMs**:
   ```bash
   vagrant ssh web
   vagrant ssh db
   ```

---

## **Step 6: Verify Virtualization and Networking**

Ensure the virtual machines are running correctly and networked.

1. **List running virtual machines**:
   ```bash
   sudo virsh list --all
   ```

2. **Check network interfaces**:
   ```bash
   ip a
   ```

3. **Verify that the `virbr0` bridge is active**:
   ```bash
   ip link show virbr0
   ```

---

## **Step 7: Test Ansible and Python Setup**

Verify that Ansible and Python are ready for automation tasks.

1. **Check Ansible version**:
   ```bash
   ansible --version
   ```

2. **Test Python and pip**:
   ```bash
   python3 --version
   pip3 --version
   ```

3. **Create an Ansible inventory file for the VMs**:
   ```ini
   [webservers]
   webserver ansible_host=192.168.56.10 ansible_user=vagrant ansible_private_key_file=.vagrant/machines/web/libvirt/private_key

   [dbservers]
   dbserver ansible_host=192.168.56.11 ansible_user=vagrant ansible_private_key_file=.vagrant/machines/db/libvirt/private_key
   ```

---

## **Step 8: Configure Security**

Set up firewalld and SELinux to secure your environment.

1. **Allow web traffic on firewalld**:
   ```bash
   sudo firewall-cmd --permanent --add-service=http
   sudo firewall-cmd --reload
   ```

2. **Enable SELinux for web services**:
   ```bash
   sudo setsebool -P httpd_can_network_connect on
   ```

---

## **Additional Suggestions**

- **Automate VM Provisioning**: Use Ansible playbooks to install services on the VMs. For example:
   ```yaml
   ---
   - hosts: webservers
     tasks:
       - name: Install Apache
         yum:
           name: httpd
           state: present
       - name: Start Apache
         service:
           name: httpd
           state: started
           enabled: true
   ```

- **Configure Static IPs**: This is useful for consistent VM addresses.

- **Resource Monitoring**: Use `htop`, `iotop`, and `iftop` inside the VMs for CPU, disk, and network monitoring.

---

## **Summary of Key Commands**

```bash
# System update and repository configuration
sudo dnf update -y
sudo dnf config-manager --set-enabled crb
sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo rpm --import https://rpm.releases.hashicorp.com/gpg
sudo dnf makecache

# Install necessary packages
sudo dnf install -y qemu-kvm libvirt libvirt-daemon-driver-qemu libvirt-devel vagrant ansible python3 python3-pip \
bridge-utils net-tools wget curl vim git htop iotop iftop firewalld unzip kernel-devel kernel-headers

# Enable and start services
sudo systemctl enable --now libvirtd
sudo systemctl enable --now firewalld
sudo usermod -aG libvirt $USER
# Log out and log back in or use `newgrp libvirt`

# Install vagrant-libvirt plugin
vagrant plugin install vagrant-libvirt

# Test Python and Ansible
python3 --version
pip3 --version
ansible --version
```

---

To focus solely on **automating the base system setup** for your Rocky Linux lab, we can use **Ansible** to ensure that all necessary tools, services, and configurations are applied efficiently. This setup will automate installing dependencies, enabling services, configuring the network, and preparing the system for future use.

Here’s how you can automate the entire base system setup using Ansible:

---

## **Automating the Base System Setup with Ansible**

### **Step 1: Create an Ansible Playbook for Base System Setup**

The following playbook will handle:
- System updates.
- Enabling repositories.
- Installing required packages for virtualization, development tools, and networking.
- Enabling services like **libvirt** and **firewalld**.
- Adding the user to the **libvirt** group.

---

### **Base System Setup Playbook (setup-host.yml)**

```yaml
---
- hosts: localhost
  become: yes
  tasks:
    # Update all packages and refresh cache
    - name: Update the system
      dnf:
        name: "*"
        state: latest
        update_cache: yes

    # Enable CodeReady Builder (CRB) repository
    - name: Enable CodeReady Builder repository
      command: dnf config-manager --set-enabled crb

    # Add HashiCorp repository for Vagrant
    - name: Add HashiCorp repository for Vagrant
      command: dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

    # Refresh dnf cache
    - name: Refresh dnf cache
      command: dnf makecache

    # Install necessary packages for virtualization, development, networking, and monitoring
    - name: Install required packages
      dnf:
        name:
          - qemu-kvm
          - libvirt
          - libvirt-daemon-driver-qemu
          - libvirt-devel
          - vagrant
          - ruby-devel
          - gcc
          - ansible
          - python3
          - python3-pip
          - bridge-utils
          - net-tools
          - wget
          - curl
          - vim
          - git
          - htop
          - iotop
          - iftop
          - firewalld
          - unzip
          - kernel-devel
          - kernel-headers
        state: present

    # Enable and start libvirt service
    - name: Enable and start libvirt service
      systemd:
        name: libvirtd
        enabled: yes
        state: started

    # Enable and start firewalld service
    - name: Enable and start firewalld service
      systemd:
        name: firewalld
        enabled: yes
        state: started

    # Add the user to the libvirt group to allow non-root VM management
    - name: Add user to libvirt group
      user:
        name: "{{ ansible_user }}"
        groups: libvirt
        append: yes
```

---

### **Step 2: Run the Ansible Playbook**

1. Save the playbook to a file called `setup-host.yml`.
2. Run the Ansible playbook to automate the entire base system setup:
   
   ```bash
   ansible-playbook setup-host.yml
   ```

---

### **Step 3: Post-Setup Instructions**

1. **Reboot the System**:
   After running the playbook, it’s recommended to reboot the system to ensure all services start properly and the group changes take effect:
   
   ```bash
   sudo reboot
   ```

2. **Verify Installation**:
   Once the system is back online, verify that all services are enabled and working:

   - Check if `libvirt` is running:
     ```bash
     systemctl status libvirtd
     ```

   - Check if `firewalld` is running:
     ```bash
     systemctl status firewalld
     ```

   - Ensure the user is added to the `libvirt` group:
     ```bash
     groups $USER
     ```

---

## **What This Playbook Does**

1. **System Updates**: It ensures your system is up to date and refreshes the DNF cache.
2. **Enabling Repositories**: The playbook enables the CodeReady Builder (CRB) repository for development tools and adds the HashiCorp repository for Vagrant.
3. **Installing Required Packages**: Installs all necessary tools for virtualization (KVM, libvirt), development (GCC, Ruby), and system monitoring (htop, iotop, iftop).
4. **Enabling Services**: Automatically enables and starts key services like `libvirtd` (for VM management) and `firewalld` (for security).
5. **User Management**: Adds your user to the `libvirt` group, allowing you to manage VMs without needing root privileges.

---

## **Conclusion**

This automated base system setup ensures that your Rocky Linux environment is fully prepared for future lab deployments and VM management without manual intervention. Once the playbook is run, your system will be ready with all necessary tools and services enabled.

Let me know if you want to add any more specific features or adjustments!