Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 95 ยท System Administration

WSL, Cloud Instances and cloud-init

Run Linux on Windows with WSL 2, start a Linux server in the cloud, and use cloud-init to configure it on first boot. Includes runnable path and cloud-init demos.

You do not need a spare computer to practice Linux. On a Windows PC, WSL (the Windows Subsystem for Linux) gives you a real Linux distribution next to your normal desktop. For anything that must be online around the clock, you rent a cloud instance: a virtual machine in a provider's data center that boots a Linux image in seconds. This lesson covers both, and then shows cloud-init, the tool that turns a blank cloud image into a configured server the first time it starts.

Neither WSL nor a cloud provider can be reached from the editors on this page, so the Windows commands and provider steps are read-only. The parts that are pure Linux logic, such as converting paths between Windows and Linux and the "run once per instance" behavior of cloud-init, are small enough to rebuild in Bash, and you can run those examples. Everything you learned about the shell, permissions and SSH applies unchanged in both worlds.

Linux on Windows with WSL 2

WSL 2 runs a real Linux kernel inside a lightweight virtual machine that Windows manages for you. You get a normal distribution (Ubuntu by default), a terminal, apt, and your usual tools, with no dual boot and no VirtualBox window to babysit.

flowchart LR
  subgraph WIN["Windows"]
    A["Windows apps<br/>Terminal, VS Code, browser"]
  end
  subgraph VM["WSL 2 virtual machine"]
    B["Linux kernel + your distro<br/>ext4 virtual disk"]
  end
  A -- "wsl.exe, the wsl.localhost share" --> B
  B -- "/mnt/c (Windows drives)" --> A

Windows and the WSL 2 virtual machine see each other's files through two bridges.

You control WSL from PowerShell or Windows Terminal (these commands run in Windows, not in Linux, so they are read-only here):

CONSOLE
PS> wsl --install                      # enable WSL and install Ubuntu (a reboot may be needed)
PS> wsl --list --online                # which distributions can I install?
PS> wsl --install -d Debian            # install a specific one
PS> wsl --list --verbose               # installed distros, their state and WSL version
PS> wsl -d Ubuntu                      # open a shell in a distro
PS> wsl --shutdown                     # stop every WSL VM (use this to apply config changes)
PS> wsl --update                       # update the WSL kernel and components
PS> wsl --export Ubuntu ubuntu.tar     # back up a whole distro to a tar file
PS> wsl --import Lab D:\wsl\lab ubuntu.tar   # restore or clone it under a new name
PS> wsl --unregister Ubuntu            # delete the distro and ALL its files

--export and --import are the easy way to make a throwaway copy before an experiment. --unregister has no confirmation and no undo, so treat it like rm -rf.

Two worlds, one machine

Inside your distro, Windows drives appear as /mnt/c, /mnt/d and so on. From Windows, the Linux files are available at \\wsl.localhost\Ubuntu\home\ada, and explorer.exe . opens the current Linux folder in the Windows file manager. You can even start Windows programs from the Linux shell (notepad.exe notes.txt) and pipe their output like any command.

One rule saves a lot of frustration: keep your projects on the Linux side (in ~), not under /mnt/c. Reading thousands of small files across the bridge is much slower than reading them from the Linux disk, and permission bits and case sensitivity behave differently on Windows drives. Tools such as git, npm and compilers feel fast at home and slow on /mnt/c.

The command wslpath converts between the two path styles. The sandbox has no WSL, but the rules are simple enough to rebuild:

Bash Converting Windows and Linux paths by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The second half shows why \\wsl.localhost\Ubuntu\... exists at all: files outside /mnt live on the virtual disk, so Windows reaches them through a network-share style name. The same distro name is used in wsl -d.

Configuration files

WSL has two configuration files, one on each side:

INI
# /etc/wsl.conf   (inside the distro, per distro)
[boot]
systemd=true            # run systemd, so services and `systemctl` work

[interop]
appendWindowsPath=false # keep Windows folders out of $PATH
INI
# C:\Users\ada\.wslconfig   (on Windows, applies to all WSL 2 distros)
[wsl2]
memory=8GB
processors=4

After editing either file, run wsl --shutdown from PowerShell and start the distro again. Without systemd you can still run programs, but service commands from Packages, Services and systemd will not behave like they do on a server. Without a memory limit, the VM may use a large share of your RAM for its file cache, which is why .wslconfig exists.

You can tell from inside Linux that you are on WSL by reading the kernel string. Real tools do the same:

Bash Am I on WSL? Reading the kernel version string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

WSL 1 was a translation layer with no real kernel and is rarely what you want now; WSL 2 is the default and has full system-call compatibility, which is why Docker and most server software run well on it.

Linux in the cloud

A cloud instance is a virtual machine you rent by the hour or the second. You pick a provider (AWS, Google Cloud, Azure, DigitalOcean, Hetzner and many others), and the creation form always asks for the same few things:

Choice What it means
Image The operating system template, such as Ubuntu LTS, Debian or Rocky Linux.
Size vCPUs, RAM and disk. Start small: you can resize later.
Region Where the machine lives. Closer to your users means lower latency.
SSH key Your public key, installed for the default user so you never need a password.
Firewall Which ports are open. Allow SSH (22) from your address and nothing else until you need it.
User data An optional script or #cloud-config file run on first boot (more below).

When the instance is running you connect with the key pair you set up in SSH, scp and Working Remotely. The default user depends on the image: ubuntu on Ubuntu images, admin on Debian, ec2-user on Amazon Linux, root on some budget providers. The provider's console tells you.

CONSOLE
$ ssh -i ~/.ssh/id_ed25519 ubuntu@203.0.113.40
ubuntu@web-01:~$ sudo apt update && sudo apt upgrade -y

The first hour checklist

A fresh public server is scanned by bots within minutes, so do the basics early:

  1. Update the system (apt, dnf) and enable automatic security updates.
  2. Create your own user with sudo rights and your public key, as described in Users, Groups and sudo; stop using root over SSH.
  3. Harden SSH: password logins off, root login off.
  4. Turn on a firewall (the provider's security group, plus ufw or firewalld on the machine) that allows only the ports you serve.
  5. Check the disk and time: df -h, timedatectl, and snapshots or backups configured. See Disks, Mounts, Logs and Monitoring.

Doing this by hand on one server is fine. Doing it by hand on the fifth server is how mistakes creep in. That is what cloud-init is for.

Cost and cleanup

Cloud machines bill while they exist, not while you use them. A stopped instance may still bill for its disk and any attached IP address. When you are finished with an experiment, delete the instance, its volumes, snapshots and reserved addresses, and set a budget alert in the provider's billing page. Never leave a test server running with a default password or an open database port.

cloud-init: configure a server on first boot

cloud-init is the industry-standard first-boot agent. Most cloud images ship with it. On boot it asks the platform for the instance's metadata (hostname, network settings, SSH keys) and user data (whatever you supplied), and then applies them. Your user data is usually a YAML document that must start with the line #cloud-config:

YAML
#cloud-config
hostname: web-01
timezone: UTC
package_update: true
packages:
  - nginx
  - git
users:
  - name: ada
    groups: [sudo]
    shell: /bin/bash
    sudo: ALL=(ALL) NOPASSWD:ALL
    ssh_authorized_keys:
      - ssh-ed25519 AAAA...example ada@laptop
write_files:
  - path: /etc/motd
    content: |
      Managed by cloud-init. Do not edit by hand.
runcmd:
  - systemctl enable --now nginx
  - echo "provisioned" > /var/log/provisioned.txt

(Read-only: the NOPASSWD rule is convenient for a lab and a bad idea on shared systems.) A plain shell script that starts with #!/bin/bash is also accepted as user data and simply runs once, as root. The YAML form is better when you can use it, because modules such as packages and users describe the result and handle differences between distributions.

cloud-init runs in stages during boot:

flowchart LR
  A["local<br/>no network yet"] --> B["init<br/>network up, users, files"]
  B --> C["config<br/>packages and settings"]
  C --> D["final<br/>runcmd and scripts"]

The four cloud-init stages, each a systemd service that finishes before the next starts.

Roughly: early stages find the data source and set up users, keys and files; the config stage installs packages and applies settings; and the final stage runs your runcmd commands last, when everything else exists.

The most important design rule is that cloud-init is per instance. It records the instance ID and, once the work is done, does not repeat the "once per instance" modules on later reboots. A reboot must not reinstall packages or overwrite a config file you tuned by hand. We can model that behavior with a tiny interpreter that reads a runcmd list and keeps a marker per instance ID:

Bash A mini cloud-init: run once per instance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The marker file plays the role of cloud-init's own bookkeeping under /var/lib/cloud/. The real tool is far more capable, but the idea carries over: the server is configured by data you wrote down, applied exactly once per machine. That is also why cloning a configured VM into an image needs cloud-init clean, which forgets the instance so the clone configures itself again.

Debugging cloud-init

When a first boot does not do what you expected, check these on the server (read-only here):

CONSOLE
$ cloud-init status --long              # running, done, or error, and which module failed
$ sudo cat /var/log/cloud-init-output.log   # the output of your runcmd scripts
$ sudo less /var/log/cloud-init.log     # detailed log of every module
$ cloud-init schema --config-file user-data.yaml   # validate YAML before you boot

The usual causes of "nothing happened" are a missing #cloud-config first line, bad YAML indentation, and a runcmd command that failed silently because a package was not installed yet. Commands in runcmd run in a minimal environment as root, without your shell profile, so use full paths and test them as a plain script first (see Debugging Shell Scripts).

Instance metadata

Every instance can also ask the provider about itself over a link-local address, usually http://169.254.169.254/. The exact paths differ by provider; some, such as AWS, require a session token for the newer, safer version of the service. Scripts use it to learn their own instance ID, region or tags. Treat the metadata service as sensitive: anything on the machine that can reach it can read your instance's credentials, so firewall it from containers that do not need it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should you keep the source code of a project you build inside WSL 2 for the best speed?

    Files under /mnt/c cross the bridge to the Windows drive, which is slow for many small files. The Linux virtual disk is much faster and keeps normal Linux permissions.
  2. 2. Which command stops every running WSL virtual machine, so that a change in .wslconfig or wsl.conf takes effect?

    wsl --shutdown stops the WSL 2 VM; the next start reads the configuration again. --unregister would delete the distro and its files.
  3. 3. What must the first line of a cloud-init YAML user-data file be?

    cloud-init uses the first line to recognize the format. Without #cloud-config the file is not treated as a cloud-config document.
  4. 4. A configured VM is cloned and the clone does not run its first-boot setup. What is the likely reason?

    Per-instance modules run once per instance ID. A clone that keeps the old state looks like a reboot of the original, so the state must be cleaned before the image is saved.
  5. 5. Why is it a good idea to delete test cloud instances you no longer need?

    Disks, addresses and running machines keep costing money, and an unattended server with no updates is an easy target.

Summary

  • WSL 2 runs a real Linux kernel in a lightweight VM. Manage it with wsl --install, --list --verbose, --shutdown, --export and --import; --unregister deletes everything.
  • Windows drives appear as /mnt/c, Linux files as \\wsl.localhost\<distro>. Keep projects on the Linux side for speed; wslpath converts paths.
  • /etc/wsl.conf configures one distro (for example systemd=true), .wslconfig configures all WSL 2 VMs (memory, processors).
  • A cloud instance is a rented VM: choose image, size, region, SSH key and firewall, then do the first-hour hardening checklist and delete what you no longer use.
  • cloud-init applies user data (#cloud-config YAML or a script) on first boot, in four stages, once per instance; debug with cloud-init status --long and the logs under /var/log.
  • The metadata service at a link-local address tells an instance about itself and deserves protection.

Next: Rescue Mode and Recovery