Mylab2 - itnett/FTD02H-N GitHub Wiki

MyLab2: Trinn for Trinn Guide

Dette dokumentet veileder deg gjennom å sette opp et lokalt labmiljø på en Windows 11 laptop ved hjelp av VirtualBox, Docker Desktop, Terraform, Ansible, Minikube, og Git.

Trinn 1: Forberedelse

Forutsetninger:

  • Windows 11 laptop
  • Admin-rettigheter på maskinen

Nødvendig programvare:

  • VirtualBox
  • Docker Desktop
  • Terraform
  • Ansible
  • Minikube
  • Git (for versjonskontroll)

Trinn 2: Opprette Katalogstruktur

Opprett et PowerShell-skript setup-folder-structure.ps1:

# Define base path
$basePath = "C:\lab\mylab2"

# Create directories
$dirs = @(
    "$basePath\ansible",
    "$basePath\docker",
    "$basePath\terraform",
    "$basePath\vbox\vms",
    "$basePath\vbox\iso",
    "$basePath\wsl",
    "$basePath\scripts",
    "$basePath\git"
)

foreach ($dir in $dirs) {
    if (-Not (Test-Path -Path $dir)) {
        New-Item -ItemType Directory -Path $dir
    }
}

Write-Output "Directory structure created."

Trinn 3: Installere Nødvendig Programvare

Opprett et PowerShell-skript install-software.ps1:

# Path to download installers
$downloadPath = "C:\temp"

# Create the download directory if it does not exist
if (-Not (Test-Path -Path $downloadPath)) {
    New-Item -ItemType Directory -Path $downloadPath
}

# Install Chocolatey if not installed
if (-Not (Get-Command choco -ErrorAction SilentlyContinue)) {
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

# Install VirtualBox
choco install virtualbox -y

# Install Docker Desktop
choco install docker-desktop -y

# Install Terraform
choco install terraform -y

# Install Git
choco install git -y

# Install Minikube
choco install minikube -y

# Install WSL and Ubuntu
wsl --install -d Ubuntu

Write-Output "All software installed. Please restart your computer to complete the installation."

Trinn 4: Konfigurere Ansible på WSL

Opprett et skript configure-ansible.sh for å kjøre innenfor WSL:

#!/bin/bash

# Update and upgrade the system
sudo apt update && sudo apt upgrade -y

# Install Ansible
sudo apt install ansible -y

# Verify Ansible installation
ansible --version

Trinn 5: Automatisere Terraform og Ansible

Opprett terraform/main.tf:

provider "virtualbox" {}

resource "virtualbox_vm" "ubuntu_vm" {
  name   = "ubuntu-lab-vm"
  image  = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box"
  cpus   = 2
  memory = "2048 mib"

  network_adapter {
    type           = "hostonly"
    host_interface = "vboxnet0"
  }

  disk {
    image = "${path.module}/../vbox/vms/ubuntu-lab-vm-disk.vdi"
    size  = "20 gib"
  }
}

output "vm_ip" {
  value = virtualbox_vm.ubuntu_vm.network_adapter.0.ipv4_address
}

Opprett ansible/inventory.ini:

[all]
<VM_IP_ADDRESS> ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa

Opprett ansible/playbook.yml:

- name: Configure Ubuntu VM
  hosts: all
  become: yes
  tasks:
    - name: Update and upgrade apt packages
      apt:
        update_cache: yes
        upgrade: dist

    - name: Install Docker
      apt:
        name: docker.io
        state: present
      notify:
        - Start Docker

  handlers:
    - name: Start Docker
      service:
        name: docker
        state: started

Trinn 6: Opprett Hovedskript for Å Kjøre Alt

Opprett setup-environment.ps1:

# Define base path
$basePath = "C:\lab\mylab2"

# Run folder structure setup script
.\setup-folder-structure.ps1

# Run installation script
.\$basePath\scripts\install-software.ps1

# Restart computer to complete installation
Write-Output "Please restart your computer to complete the installation, then run this script again."
Start-Sleep -Seconds 5
exit

# Configure Ansible in WSL
wsl -d Ubuntu -u root -- ./ansible/configure-ansible.sh

# Navigate to terraform directory and run Terraform
cd $basePath\terraform

# Initialize Terraform
terraform init

# Apply Terraform configuration
terraform apply -auto-approve

# Run Ansible playbook
ansible-playbook -i $basePath\ansible\inventory.ini $basePath\ansible\playbook.yml

Trinn 7: Last opp til GitHub og Kjør

  1. Last opp alle skriptene og filene til ditt GitHub repository.

  2. På en ny Windows 11-maskin, klon repository:

    git clone https://github.com/<your-username>/local-lab-setup.git
    cd local-lab-setup
    
  3. Kjør hovedskriptet for å sette opp miljøet:

    .\scripts\setup-environment.ps1
    

Dette vil automatisk opprette katalogstrukturen, installere og konfigurere nødvendig programvare, sette opp et VirtualBox-miljø, kjøre Terraform for å opprette VM-er, og bruke Ansible for å konfigurere dem. All programvare og konfigurering vil være organisert under C:\lab\mylab2, noe som gjør det enkelt å administrere og flytte miljøet mellom ulike maskiner.

Hvis du har flere spørsmål eller trenger ytterligere hjelp, er det bare å si fra!

For å hjelpe deg med å automatisere hele prosessen fra installasjon til konfigurasjon og kjøring av Terraform-skript, inkludert håndtering av SSH-nøkler og variabler, kan vi lage en mer komplett løsning. Dette innebærer å lage et PowerShell-skript som setter opp hele miljøet, inkludert nedlasting og håndtering av SSH-nøkler.

Fullstendig PowerShell Skript

setup-environment.ps1

Dette hovedskriptet vil kjøre alle nødvendige trinn for å sette opp miljøet.

# Define base path
$basePath = "C:\lab\mylab2"

# Step 1: Create Directory Structure
Write-Output "Creating directory structure..."
.\setup-folder-structure.ps1

# Step 2: Install Necessary Software
Write-Output "Installing necessary software..."
.\$basePath\scripts\install-software.ps1

# Step 3: Restart the computer to complete installations
Write-Output "Please restart your computer to complete the installation. After restart, run this script again."
Start-Sleep -Seconds 5
exit

# Step 4: Configure Ansible in WSL
Write-Output "Configuring Ansible in WSL..."
wsl -d Ubuntu -u root -- ./ansible/configure-ansible.sh

# Step 5: Fetch SSH Keys
Write-Output "Generating SSH keys..."
if (-Not (Test-Path -Path "$HOME\.ssh\id_rsa")) {
    ssh-keygen -t rsa -b 4096 -f "$HOME\.ssh\id_rsa" -N ""
}

# Step 6: Apply Terraform Configuration
Write-Output "Applying Terraform configuration..."
cd $basePath\terraform

# Initialize Terraform
terraform init

# Apply Terraform configuration
terraform apply -auto-approve

# Get the VM IP address from Terraform output
$vm_ip = terraform output -raw vm_ip

# Update Ansible inventory with VM IP address
Write-Output "Updating Ansible inventory with VM IP address..."
(invoke-expression "terraform output -json") | ConvertFrom-Json | ForEach-Object {
    $_.vm_ip | Out-File $basePath\ansible\inventory.ini -Append
}

# Step 7: Run Ansible Playbook
Write-Output "Running Ansible playbook..."
ansible-playbook -i $basePath\ansible\inventory.ini $basePath\ansible\playbook.yml

Katalogstruktur Skript

setup-folder-structure.ps1

# Define base path
$basePath = "C:\lab\mylab2"

# Create directories
$dirs = @(
    "$basePath\ansible",
    "$basePath\docker",
    "$basePath\terraform",
    "$basePath\vbox\vms",
    "$basePath\vbox\iso",
    "$basePath\wsl",
    "$basePath\scripts",
    "$basePath\git"
)

foreach ($dir in $dirs) {
    if (-Not (Test-Path -Path $dir)) {
        New-Item -ItemType Directory -Path $dir
    }
}

Write-Output "Directory structure created."

# Copy necessary files to respective directories
Copy-Item -Path ".\install-software.ps1" -Destination "$basePath\scripts\install-software.ps1"
Copy-Item -Path ".\configure-ansible.sh" -Destination "$basePath\ansible\configure-ansible.sh"
Copy-Item -Path ".\main.tf" -Destination "$basePath\terraform\main.tf"
Copy-Item -Path ".\playbook.yml" -Destination "$basePath\ansible\playbook.yml"
Copy-Item -Path ".\inventory.ini" -Destination "$basePath\ansible\inventory.ini"

Write-Output "Files copied to respective directories."

Installasjonsskript

install-software.ps1

# Path to download installers
$downloadPath = "C:\temp"

# Create the download directory if it does not exist
if (-Not (Test-Path -Path $downloadPath)) {
    New-Item -ItemType Directory -Path $downloadPath
}

# Install Chocolatey if not installed
if (-Not (Get-Command choco -ErrorAction SilentlyContinue)) {
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

# Install VirtualBox
choco install virtualbox -y

# Install Docker Desktop
choco install docker-desktop -y

# Install Terraform
choco install terraform -y

# Install Git
choco install git -y

# Install Minikube
choco install minikube -y

# Install WSL and Ubuntu
wsl --install -d Ubuntu

Write-Output "All software installed. Please restart your computer to complete the installation."

Ansible Konfigurasjonsskript

configure-ansible.sh

#!/bin/bash

# Update and upgrade the system
sudo apt update && sudo apt upgrade -y

# Install Ansible
sudo apt install ansible -y

# Verify Ansible installation
ansible --version

Terraform Fil

main.tf

provider "virtualbox" {}

resource "virtualbox_vm" "ubuntu_vm" {
  name   = "ubuntu-lab-vm"
  image  = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box"
  cpus   = 2
  memory = "2048 mib"

  network_adapter {
    type           = "hostonly"
    host_interface = "vboxnet0"
  }

  disk {
    image = "${path.module}/../vbox/vms/ubuntu-lab-vm-disk.vdi"
    size  = "20 gib"
  }
}

output "vm_ip" {
  value = virtualbox_vm.ubuntu_vm.network_adapter.0.ipv4_address
}

Ansible Inventory Fil

inventory.ini

[all]
<VM_IP_ADDRESS> ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa

Ansible Playbook

playbook.yml

- name: Configure Ubuntu VM
  hosts: all
  become: yes
  tasks:
    - name: Update and upgrade apt packages
      apt:
        update_cache: yes
        upgrade: dist

    - name: Install Docker
      apt:
        name: docker.io
        state: present
      notify:
        - Start Docker

  handlers:
    - name: Start Docker
      service:
        name: docker
        state: started

Hvordan Kjør Alt

  1. Last opp til GitHub:

    • Last opp alle skriptene og filene til ditt GitHub repository.
  2. Klon repository på en ny Windows 11-maskin:

    git clone https://github.com/<your-username>/local-lab-setup.git
    cd local-lab-setup
    
  3. Kjør hovedskriptet:

    .\scripts\setup-environment.ps1
    

Dette vil:

  1. Opprette katalogstrukturen.
  2. Installere nødvendig programvare.
  3. Kreve en omstart.
  4. Konfigurere Ansible i WSL.
  5. Generere SSH-nøkler.
  6. Kjøre Terraform for å sette opp VM-er.
  7. Kjøre Ansible playbook for å konfigurere VM-er.

All programvare og konfigurering vil være organisert under C:\lab\mylab2, noe som gjør det enkelt å administrere og flytte miljøet mellom ulike maskiner. Hvis du har flere spørsmål eller trenger ytterligere hjelp, er det bare å si fra!

La oss tydeliggjøre hele prosessen for installasjon, konfigurasjon og bruk av Terraform, inkludert hvor og hvordan Terraform installeres og når du skal kjøre Terraform-malene. Vi skal oppdatere skriptene slik at de gir en fullstendig og sammenhengende prosess.

Overordnet Prosess

  1. Opprett Katalogstruktur: Opprett nødvendige mapper.
  2. Installer Nødvendig Programvare: Installer VirtualBox, Docker Desktop, Terraform, Ansible, Minikube, og Git.
  3. Konfigurer Ansible på WSL: Sett opp Ansible i WSL.
  4. Generer SSH-nøkler: Lag SSH-nøkler for bruk med Ansible.
  5. Kjør Terraform: Initialiser og kjør Terraform for å opprette og konfigurere VM-er.
  6. Kjør Ansible Playbook: Konfigurer VM-ene ved hjelp av Ansible.

Oppdatert Hovedskript

setup-environment.ps1

# Define base path
$basePath = "C:\lab\mylab2"

# Step 1: Create Directory Structure
Write-Output "Creating directory structure..."
.\scripts\setup-folder-structure.ps1

# Step 2: Install Necessary Software
Write-Output "Installing necessary software..."
.\scripts\install-software.ps1

# Step 3: Restart the computer to complete installations
Write-Output "Please restart your computer to complete the installation. After restart, run this script again."
Start-Sleep -Seconds 5
exit

# Step 4: Configure Ansible in WSL
Write-Output "Configuring Ansible in WSL..."
wsl -d Ubuntu -u root -- $basePath\ansible\configure-ansible.sh

# Step 5: Generate SSH Keys
Write-Output "Generating SSH keys..."
if (-Not (Test-Path -Path "$HOME\.ssh\id_rsa")) {
    ssh-keygen -t rsa -b 4096 -f "$HOME\.ssh\id_rsa" -N ""
}

# Step 6: Apply Terraform Configuration
Write-Output "Applying Terraform configuration..."
cd $basePath\terraform

# Initialize Terraform
terraform init

# Apply Terraform configuration
terraform apply -auto-approve

# Get the VM IP address from Terraform output
$vm_ip = terraform output -raw vm_ip

# Update Ansible inventory with VM IP address
Write-Output "Updating Ansible inventory with VM IP address..."
(Get-Content $basePath\ansible\inventory.ini) -replace '<VM_IP_ADDRESS>', $vm_ip | Set-Content $basePath\ansible\inventory.ini

# Step 7: Run Ansible Playbook
Write-Output "Running Ansible playbook..."
ansible-playbook -i $basePath\ansible\inventory.ini $basePath\ansible\playbook.yml

Opprett Katalogstruktur Skript

setup-folder-structure.ps1

# Define base path
$basePath = "C:\lab\mylab2"

# Create directories
$dirs = @(
    "$basePath\ansible",
    "$basePath\docker",
    "$basePath\terraform",
    "$basePath\vbox\vms",
    "$basePath\vbox\iso",
    "$basePath\wsl",
    "$basePath\scripts",
    "$basePath\git"
)

foreach ($dir in $dirs) {
    if (-Not (Test-Path -Path $dir)) {
        New-Item -ItemType Directory -Path $dir
    }
}

Write-Output "Directory structure created."

# Copy necessary files to respective directories
Copy-Item -Path ".\install-software.ps1" -Destination "$basePath\scripts\install-software.ps1"
Copy-Item -Path ".\configure-ansible.sh" -Destination "$basePath\ansible\configure-ansible.sh"
Copy-Item -Path ".\main.tf" -Destination "$basePath\terraform\main.tf"
Copy-Item -Path ".\playbook.yml" -Destination "$basePath\ansible\playbook.yml"
Copy-Item -Path ".\inventory.ini" -Destination "$basePath\ansible\inventory.ini"

Write-Output "Files copied to respective directories."

Installasjonsskript

install-software.ps1

# Path to download installers
$downloadPath = "C:\temp"

# Create the download directory if it does not exist
if (-Not (Test-Path -Path $downloadPath)) {
    New-Item -ItemType Directory -Path $downloadPath
}

# Install Chocolatey if not installed
if (-Not (Get-Command choco -ErrorAction SilentlyContinue)) {
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

# Install VirtualBox
choco install virtualbox -y

# Install Docker Desktop
choco install docker-desktop -y

# Install Terraform
choco install terraform -y

# Install Git
choco install git -y

# Install Minikube
choco install minikube -y

# Install WSL and Ubuntu
wsl --install -d Ubuntu

Write-Output "All software installed. Please restart your computer to complete the installation."

Ansible Konfigurasjonsskript

configure-ansible.sh

#!/bin/bash

# Update and upgrade the system
sudo apt update && sudo apt upgrade -y

# Install Ansible
sudo apt install ansible -y

# Verify Ansible installation
ansible --version

Terraform Fil

main.tf

provider "virtualbox" {}

resource "virtualbox_vm" "ubuntu_vm" {
  name   = "ubuntu-lab-vm"
  image  = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box"
  cpus   = 2
  memory = "2048 mib"

  network_adapter {
    type           = "hostonly"
    host_interface = "vboxnet0"
  }

  disk {
    image = "${path.module}/../vbox/vms/ubuntu-lab-vm-disk.vdi"
    size  = "20 gib"
  }
}

output "vm_ip" {
  value = virtualbox_vm.ubuntu_vm.network_adapter.0.ipv4_address
}

Ansible Inventory Fil

inventory.ini

[all]
<VM_IP_ADDRESS> ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa

Ansible Playbook

playbook.yml

- name: Configure Ubuntu VM
  hosts: all
  become: yes
  tasks:
    - name: Update and upgrade apt packages
      apt:
        update_cache: yes
        upgrade: dist

    - name: Install Docker
      apt:
        name: docker.io
        state: present
      notify:
        - Start Docker

  handlers:
    - name: Start Docker
      service:
        name: docker
        state: started

Hvordan Kjør Alt

  1. Last opp til GitHub:

    • Last opp alle skriptene og filene til ditt GitHub repository.
  2. Klon repository på en ny Windows 11-maskin:

    git clone https://github.com/<your-username>/local-lab-setup.git
    cd local-lab-setup
    
  3. Kjør hovedskriptet:

    .\scripts\setup-environment.ps1
    

Dette vil:

  1. Opprette katalogstrukturen.
  2. Installere nødvendig programvare.
  3. Kreve en omstart (første gang du kjører skriptet).
  4. Konfigurere Ansible i WSL.
  5. Generere SSH-nøkler.
  6. Kjøre Terraform for å sette opp VM-er.
  7. Kjøre Ansible playbook for å konfigurere VM-er.

All programvare og konfigurering vil være organisert under C:\lab\mylab2, noe som gjør det enkelt å administrere og flytte miljøet mellom ulike maskiner. Hvis du har flere spørsmål eller trenger ytterligere hjelp, er det bare å si fra!

Ja, vi kan lage et system som bruker MyLab2 for å distribuere nye miljøer som MyLab3 eller MyLab1 på hvilken som helst Windows 10 eller Windows 11 maskin. Vi kan legge til valgmuligheter i skriptene for å bestemme om vi skal kjøre Win Native WSL/Minikube eller også bruke VirtualBox med VM-er og Docker containere. Dette krever en strukturert tilnærming for å sikre at alle trinnene er automatisert og CI/CD-styrt.

Overordnet Struktur

  1. Opprett Katalogstruktur
  2. Installer Nødvendig Programvare
  3. Konfigurer Ansible på WSL
  4. Generer SSH-nøkler
  5. Kjør Terraform for å sette opp VM-er
  6. Kjør Ansible Playbook for å konfigurere VM-er
  7. Deploying av MyLab3 på samme PC eller en annen PC

Hovedskript med Valg

Vi kan oppdatere hovedskriptet til å inkludere valg for brukeren:

setup-environment.ps1

param (
    [switch]$UseVirtualBox,
    [switch]$UseWSL,
    [switch]$UseDockerInWSL
)

# Define base path
$basePath = "C:\lab\mylab2"

# Step 1: Create Directory Structure
Write-Output "Creating directory structure..."
.\scripts\setup-folder-structure.ps1

# Step 2: Install Necessary Software
Write-Output "Installing necessary software..."
.\scripts\install-software.ps1

# Step 3: Restart the computer to complete installations
Write-Output "Please restart your computer to complete the installation. After restart, run this script again."
Start-Sleep -Seconds 5
exit

if ($UseWSL) {
    # Step 4: Configure Ansible in WSL
    Write-Output "Configuring Ansible in WSL..."
    wsl -d Ubuntu -u root -- $basePath\ansible\configure-ansible.sh
}

# Step 5: Generate SSH Keys
Write-Output "Generating SSH keys..."
if (-Not (Test-Path -Path "$HOME\.ssh\id_rsa")) {
    ssh-keygen -t rsa -b 4096 -f "$HOME\.ssh\id_rsa" -N ""
}

if ($UseVirtualBox) {
    # Step 6: Apply Terraform Configuration for VirtualBox
    Write-Output "Applying Terraform configuration for VirtualBox..."
    cd $basePath\terraform

    # Initialize Terraform
    terraform init

    # Apply Terraform configuration
    terraform apply -auto-approve

    # Get the VM IP address from Terraform output
    $vm_ip = terraform output -raw vm_ip

    # Update Ansible inventory with VM IP address
    Write-Output "Updating Ansible inventory with VM IP address..."
    (Get-Content $basePath\ansible\inventory.ini) -replace '<VM_IP_ADDRESS>', $vm_ip | Set-Content $basePath\ansible\inventory.ini
}

if ($UseDockerInWSL) {
    # Step 7: Run Ansible Playbook to configure Docker in WSL
    Write-Output "Running Ansible playbook to configure Docker in WSL..."
    ansible-playbook -i $basePath\ansible\inventory.ini $basePath\ansible\playbook.yml
}

Oppdatert Terraform Fil

main.tf

provider "virtualbox" {}

resource "virtualbox_vm" "ubuntu_vm" {
  name   = "ubuntu-lab-vm"
  image  = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box"
  cpus   = 2
  memory = "2048 mib"

  network_adapter {
    type           = "hostonly"
    host_interface = "vboxnet0"
  }

  disk {
    image = "${path.module}/../vbox/vms/ubuntu-lab-vm-disk.vdi"
    size  = "20 gib"
  }
}

output "vm_ip" {
  value = virtualbox_vm.ubuntu_vm.network_adapter.0.ipv4_address
}

Ansible Playbook for Docker i WSL

playbook.yml

- name: Configure Ubuntu VM
  hosts: all
  become: yes
  tasks:
    - name: Update and upgrade apt packages
      apt:
        update_cache: yes
        upgrade: dist

    - name: Install Docker
      apt:
        name: docker.io
        state: present
      notify:
        - Start Docker

  handlers:
    - name: Start Docker
      service:
        name: docker
        state: started

Distribusjon av MyLab3 eller MyLab1

For å distribuere et nytt miljø, kan vi bruke samme setup-environment.ps1 med nødvendige parametere for å kontrollere om VirtualBox, WSL, eller Docker i WSL skal brukes.

Eksempel på kjøring

For å sette opp MyLab2 med VirtualBox og Docker i WSL:

.\scripts\setup-environment.ps1 -UseVirtualBox -UseWSL -UseDockerInWSL

For å sette opp MyLab3 på samme PC eller en annen PC:

  1. Klon repository på en annen PC:

    git clone https://github.com/<your-username>/local-lab-setup.git
    cd local-lab-setup
    
  2. Kjør hovedskriptet med ønskede parametere:

    .\scripts\setup-environment.ps1 -UseVirtualBox -UseWSL -UseDockerInWSL
    

Dette systemet vil tillate deg å automatisk opprette og konfigurere et komplett labmiljø på hvilken som helst Windows 10 eller Windows 11 PC, inkludert valg for bruk av VirtualBox, WSL, og Docker. Hvis du har flere spørsmål eller trenger ytterligere detaljer, gi meg beskjed!

Vi kan bygge inn omfattende logging, error håndtering og kommentering i koden for å gjøre den mer robust og enklere å forstå. Her er en oppdatert versjon av skriptene med disse forbedringene.

Hovedskript med Logging og Error Håndtering

setup-environment.ps1

param (
    [switch]$UseVirtualBox,
    [switch]$UseWSL,
    [switch]$UseDockerInWSL
)

# Define base path
$basePath = "C:\lab\mylab2"

# Log file path
$logFile = "$basePath\logs\setup-environment.log"

# Create log directory if it does not exist
if (-Not (Test-Path -Path "$basePath\logs")) {
    New-Item -ItemType Directory -Path "$basePath\logs"
}

# Function to log messages
function Log-Message {
    param (
        [string]$message
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"
    Write-Output $logMessage
    Add-Content -Path $logFile -Value $logMessage
}

# Function to handle errors
function Handle-Error {
    param (
        [string]$errorMessage
    )
    Log-Message "ERROR: $errorMessage"
    exit 1
}

# Step 1: Create Directory Structure
Log-Message "Creating directory structure..."
try {
    .\scripts\setup-folder-structure.ps1
} catch {
    Handle-Error "Failed to create directory structure: $_"
}

# Step 2: Install Necessary Software
Log-Message "Installing necessary software..."
try {
    .\scripts\install-software.ps1
} catch {
    Handle-Error "Failed to install necessary software: $_"
}

# Step 3: Restart the computer to complete installations
Log-Message "Please restart your computer to complete the installation. After restart, run this script again."
Start-Sleep -Seconds 5
exit

if ($UseWSL) {
    # Step 4: Configure Ansible in WSL
    Log-Message "Configuring Ansible in WSL..."
    try {
        wsl -d Ubuntu -u root -- $basePath\ansible\configure-ansible.sh
    } catch {
        Handle-Error "Failed to configure Ansible in WSL: $_"
    }
}

# Step 5: Generate SSH Keys
Log-Message "Generating SSH keys..."
if (-Not (Test-Path -Path "$HOME\.ssh\id_rsa")) {
    try {
        ssh-keygen -t rsa -b 4096 -f "$HOME\.ssh\id_rsa" -N ""
    } catch {
        Handle-Error "Failed to generate SSH keys: $_"
    }
}

if ($UseVirtualBox) {
    # Step 6: Apply Terraform Configuration for VirtualBox
    Log-Message "Applying Terraform configuration for VirtualBox..."
    try {
        cd $basePath\terraform
        terraform init
        terraform apply -auto-approve
    } catch {
        Handle-Error "Failed to apply Terraform configuration: $_"
    }

    # Get the VM IP address from Terraform output
    try {
        $vm_ip = terraform output -raw vm_ip
        Log-Message "VM IP address obtained: $vm_ip"
    } catch {
        Handle-Error "Failed to obtain VM IP address: $_"
    }

    # Update Ansible inventory with VM IP address
    Log-Message "Updating Ansible inventory with VM IP address..."
    try {
        (Get-Content $basePath\ansible\inventory.ini) -replace '<VM_IP_ADDRESS>', $vm_ip | Set-Content $basePath\ansible\inventory.ini
    } catch {
        Handle-Error "Failed to update Ansible inventory: $_"
    }
}

if ($UseDockerInWSL) {
    # Step 7: Run Ansible Playbook to configure Docker in WSL
    Log-Message "Running Ansible playbook to configure Docker in WSL..."
    try {
        ansible-playbook -i $basePath\ansible\inventory.ini $basePath\ansible\playbook.yml
    } catch {
        Handle-Error "Failed to run Ansible playbook: $_"
    }
}

Opprett Katalogstruktur Skript med Logging

setup-folder-structure.ps1

# Define base path
$basePath = "C:\lab\mylab2"

# Log file path
$logFile = "$basePath\logs\setup-folder-structure.log"

# Create log directory if it does not exist
if (-Not (Test-Path -Path "$basePath\logs")) {
    New-Item -ItemType Directory -Path "$basePath\logs"
}

# Function to log messages
function Log-Message {
    param (
        [string]$message
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"
    Write-Output $logMessage
    Add-Content -Path $logFile -Value $logMessage
}

# Create directories
$dirs = @(
    "$basePath\ansible",
    "$basePath\docker",
    "$basePath\terraform",
    "$basePath\vbox\vms",
    "$basePath\vbox\iso",
    "$basePath\wsl",
    "$basePath\scripts",
    "$basePath\git"
)

foreach ($dir in $dirs) {
    try {
        if (-Not (Test-Path -Path $dir)) {
            New-Item -ItemType Directory -Path $dir
        }
        Log-Message "Directory created: $dir"
    } catch {
        Log-Message "Failed to create directory: $dir - $_"
    }
}

# Copy necessary files to respective directories
try {
    Copy-Item -Path ".\install-software.ps1" -Destination "$basePath\scripts\install-software.ps1"
    Copy-Item -Path ".\configure-ansible.sh" -Destination "$basePath\ansible\configure-ansible.sh"
    Copy-Item -Path ".\main.tf" -Destination "$basePath\terraform\main.tf"
    Copy-Item -Path ".\playbook.yml" -Destination "$basePath\ansible\playbook.yml"
    Copy-Item -Path ".\inventory.ini" -Destination "$basePath\ansible\inventory.ini"
    Log-Message "Files copied to respective directories."
} catch {
    Log-Message "Failed to copy files: $_"
}

Installasjonsskript med Logging

install-software.ps1

# Path to download installers
$downloadPath = "C:\temp"

# Log file path
$logFile = "C:\lab\mylab2\logs\install-software.log"

# Create log directory if it does not exist
if (-Not (Test-Path -Path "C:\lab\mylab2\logs")) {
    New-Item -ItemType Directory -Path "C:\lab\mylab2\logs"
}

# Function to log messages
function Log-Message {
    param (
        [string]$message
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"
    Write-Output $logMessage
    Add-Content -Path $logFile -Value $logMessage
}

# Create the download directory if it does not exist
if (-Not (Test-Path -Path $downloadPath)) {
    try {
        New-Item -ItemType Directory -Path $downloadPath
        Log-Message "Download directory created: $downloadPath"
    } catch {
        Log-Message "Failed to create download directory: $downloadPath - $_"
    }
}

# Install Chocolatey if not installed
if (-Not (Get-Command choco -ErrorAction SilentlyContinue)) {
    try {
        Set-ExecutionPolicy Bypass -Scope Process -Force; 
        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; 
        iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
        Log-Message "Chocolatey installed."
    } catch {
        Log-Message "Failed to install Chocolatey: $_"
    }
}

# Install VirtualBox
try {
    choco install virtualbox -y
    Log-Message "VirtualBox installed."
} catch {
    Log-Message "Failed to install VirtualBox: $_"
}

# Install Docker Desktop
try {
    choco install docker-desktop -y
    Log-Message "Docker Desktop installed."
} catch {
    Log-Message "Failed to install Docker Desktop: $_"
}

# Install Terraform
try {
    choco install terraform -y
    Log-Message "Terraform installed."
} catch {
    Log-Message "Failed to install Terraform: $_"
}

# Install Git
try {
    choco install git -y
    Log-Message "Git installed."
} catch {
    Log-Message "Failed to install Git: $_# Install Minikube
try {
    choco install minikube -y
    Log-Message "Minikube installed."
} catch {
    Log-Message "Failed to install Minikube: 
# Install WSL and Ubuntu
try {
    wsl --install -d Ubuntu
    Log-Message "WSL and

Fortsetter med installasjonskriptet for å inkludere logging og fullføre alle nødvendige trinn:

#### `install-software.ps1` (fortsettelse)

```powershell
# Install WSL and Ubuntu
try {
    wsl --install -d Ubuntu
    Log-Message "WSL and Ubuntu installed."
} catch {
    Log-Message "Failed to install WSL and Ubuntu: $_"
}

Write-Output "All software installed. Please restart your computer to complete the installation."
Log-Message "All software installed. Please restart your computer to complete the installation."

Ansible Konfigurasjonsskript med Logging

configure-ansible.sh

#!/bin/bash

LOGFILE="/mnt/c/lab/mylab2/logs/configure-ansible.log"

# Function to log messages
log_message() {
    local MESSAGE=$1
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $MESSAGE" | tee -a $LOGFILE
}

log_message "Starting Ansible configuration..."

# Update and upgrade the system
log_message "Updating and upgrading the system..."
sudo apt update && sudo apt upgrade -y
if [ $? -ne 0 ]; then
    log_message "Failed to update and upgrade the system."
    exit 1
else
    log_message "System updated and upgraded successfully."
fi

# Install Ansible
log_message "Installing Ansible..."
sudo apt install ansible -y
if [ $? -ne 0 ]; then
    log_message "Failed to install Ansible."
    exit 1
else
    log_message "Ansible installed successfully."
fi

# Verify Ansible installation
ANSIBLE_VERSION=$(ansible --version)
log_message "Ansible version: $ANSIBLE_VERSION"

Terraform Fil

main.tf

provider "virtualbox" {}

resource "virtualbox_vm" "ubuntu_vm" {
  name   = "ubuntu-lab-vm"
  image  = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box"
  cpus   = 2
  memory = "2048 mib"

  network_adapter {
    type           = "hostonly"
    host_interface = "vboxnet0"
  }

  disk {
    image = "${path.module}/../vbox/vms/ubuntu-lab-vm-disk.vdi"
    size  = "20 gib"
  }
}

output "vm_ip" {
  value = virtualbox_vm.ubuntu_vm.network_adapter.0.ipv4_address
}

Ansible Inventory Fil

inventory.ini

[all]
<VM_IP_ADDRESS> ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa

Ansible Playbook med Logging

playbook.yml

- name: Configure Ubuntu VM
  hosts: all
  become: yes
  tasks:
    - name: Update and upgrade apt packages
      apt:
        update_cache: yes
        upgrade: dist
      register: result
      ignore_errors: yes
    - name: Log result
      debug:
        var: result

    - name: Install Docker
      apt:
        name: docker.io
        state: present
      notify:
        - Start Docker
      register: result
      ignore_errors: yes
    - name: Log result
      debug:
        var: result

  handlers:
    - name: Start Docker
      service:
        name: docker
        state: started

Hvordan Kjør Alt med CI/CD og Automatisk Distribusjon

  1. Klon repository på en ny Windows 10 eller Windows 11 PC:

    git clone https://github.com/<your-username>/local-lab-setup.git
    cd local-lab-setup
    
  2. Kjør hovedskriptet med ønskede parametere:

    .\scripts\setup-environment.ps1 -UseVirtualBox -UseWSL -UseDockerInWSL
    

Ekstra Ressurser

For videre læring og eksempler på det vi gjør:

  1. Terraform Dokumentasjon: Terraform by HashiCorp
  2. Ansible Dokumentasjon: Ansible Documentation
  3. PowerShell Scripting: Microsoft PowerShell Documentation
  4. Docker Dokumentasjon: Docker Documentation
  5. WSL Dokumentasjon: Windows Subsystem for Linux Documentation

Dette systemet gir deg en robust løsning for å sette opp og administrere et lokalt labmiljø på en Windows-maskin. Med omfattende logging, error-håndtering og fleksibilitet gjennom parametere, kan du enkelt tilpasse miljøet etter behov. Hvis du har flere spørsmål eller trenger ytterligere hjelp, gi meg beskjed!