How Linux Handles Cloud-Init Configuration

When a Linux virtual machine boots for the first time in a cloud environment, the operating system relies on cloud-init to automate early system initialization. This article breaks down how the Linux OS detects cloud environments, processes metadata, and executes user-provided configuration scripts through specific boot stages managed by systemd, transforming a generic cloud image into a fully operational, secure instance.

Metadata Discovery and Datasource Detection

Cloud-init identifies its running environment by querying platform-specific datasources. During the earliest moments of boot, the Linux kernel boots, and cloud-init checks system hardware information—such as DMI/SMBIOS strings, hypervisor communication channels, or well-known link-local IP addresses (such as 169.254.169.254).

Once the hypervisor or cloud platform (such as AWS, OpenStack, Azure, or Google Cloud) is identified, cloud-init extracts two primary payloads:

The Four Systemd Boot Stages

Under modern Linux distributions, cloud-init hooks directly into the systemd initialization chain. Its execution is divided into four sequential phases, each gated by specific service units to guarantee operations occur in the correct order.

1. The Local Stage (cloud-init-local.service)

This stage runs before any network stack is activated and blocks the standard boot flow until local data is analyzed.

2. The Network Stage (cloud-init.service)

This stage executes immediately after local networking is online.

3. The Config Stage (cloud-config.service)

This stage handles intermediate configuration modules that depend on active storage and user accounts.

4. The Final Stage (cloud-final.service)

Running at the very end of the boot sequence (parallel with the login prompt target), this stage finalizes the instance setup.

User-Data Script Execution and State Tracking

Linux executes user scripts provided through user-data by saving them to temporary execution paths inside /var/lib/cloud/instance/scripts/ and executing them via a subshell with root privileges.

To prevent running these configurations repeatedly during subsequent reboots, cloud-init records state markers in /var/lib/cloud/instance/sem/ (semaphores). By default:

All execution logs, including stdout and stderr of user-supplied scripts, are routed to /var/log/cloud-init.log and /var/log/cloud-init-output.log, providing system administrators with a trace of the entire bootstrapping lifecycle.