cloud-init

On this page 6

cloud-init is the industry-standard open-source tool for early initialization of cloud instances: on first boot it reads metadata and user data supplied by the platform and turns a generic machine image into a configured server with its hostname, users, SSH keys, packages, files and startup commands in place. In infrastructure as code workflows it is the bridge between a provisioning tool that creates a virtual machine and the software that must run inside it.

Originally developed by Canonical for Ubuntu on Amazon EC2, cloud-init now ships in most Linux distribution cloud images and supports dozens of data sources, including AWS, Azure, Google Cloud, OpenStack, Oracle Cloud, VMware and local NoCloud media. Cloud platforms treat it as the default answer to the question of how a fresh instance learns what it should become.

How cloud-init runs during the boot sequence

cloud-init works as a set of systemd services that run in fixed stages during boot, each with a defined place relative to networking. Splitting the work this way lets it configure the network itself before later modules download packages or contact external services.

The table below lists the stages in execution order and the work each one performs.

StageWhen it runsMain work
Detect (generator)Very early, before services startDecides whether cloud-init should run at all
LocalBefore networking is upFinds local data sources and writes network configuration
NetworkAfter networking is availableFetches metadata, runs disk setup and mounts
ConfigMid bootRuns modules such as users, NTP and locale
FinalLate boot, like a traditional rc.localInstalls packages, runs user scripts and configuration management
Boot stages of cloud-init

The data source is the platform-specific channel that delivers the inputs. On many public clouds it is a link-local metadata service at 169.254.169.254; on others it is an attached configuration drive or a disk labeled cidata. From that source cloud-init obtains instance metadata such as the instance ID and region, vendor data from the platform and the user data written by the operator.

A crucial behavior is the per-instance semantics. cloud-init records the instance ID under /var/lib/cloud, and most modules run only once per instance. A reboot does not repeat them, but launching a new instance from the same image does, because the instance ID changes.

User data formats and the cloud-config syntax

User data is the operator-controlled input, and cloud-init recognizes its format from the first line. The most common format is cloud-config, a YAML document beginning with `#cloud-config` that declares desired state through module keys such as users, packages, write_files and runcmd.

The following table compares the supported formats and when each is appropriate.

FormatFirst line or markerTypical use
Cloud-config#cloud-configDeclarative setup of users, packages and files
Shell script#!/bin/bash or another shebangImperative commands run once in the final stage
MIME multipartMIME headersCombining cloud-config with several scripts
Include file#includeFetching user data from listed URLs
Jinja template## template: jinjaInserting instance metadata into configuration
Boothook#cloud-boothookVery early commands on every boot
Common user data formats

Most platforms cap user data at about 16 KB, sometimes after base64 encoding, so larger setups compress the payload or fetch a configuration management bootstrap rather than embedding everything. The command cloud-init schema --system validates the cloud-config against the published schema and catches YAML indentation errors before they reach production.

cloud-init within infrastructure as code

cloud-init is not an infrastructure as code tool on its own; it is the in-guest configuration layer that provisioning tools hand data to. Terraform, OpenTofu, Pulumi and AWS CloudFormation all expose a user_data or equivalent argument whose value cloud-init consumes, which keeps instance configuration versioned alongside the infrastructure definition.

The comparison below places cloud-init next to neighboring tools in the same toolchain.

ToolPrimary jobWhen it actsRelationship to cloud-init
cloud-initConfigure a new instanceFirst bootReference point
TerraformCreate cloud resourcesBefore the instance existsPasses user data to cloud-init
PackerBuild machine imagesImage build timeBakes software so cloud-init does less
AnsibleConfigure systems repeatedlyAny time after bootOften bootstrapped or replaced by cloud-init
Chef or PuppetContinuous configuration managementAgent runs on a schedulecloud-init installs and registers the agent
cloud-init and related tools

The modern pattern under immutable infrastructure is to bake heavy dependencies into an image with Packer and keep cloud-init for instance-specific details such as hostnames, secrets retrieval and service registration. This shortens boot time and reduces exposure to package mirror outages during scaling events.

Debugging and safe operation

Most cloud-init problems are diagnosed from two log files and one status command. The file /var/log/cloud-init.log records module-level detail, /var/log/cloud-init-output.log captures the standard output of scripts, and cloud-init status --long reports whether the run finished, failed or is still in progress.

The table maps frequent symptoms to their usual causes and fixes.

SymptomLikely causeFix
User data silently ignoredMissing #cloud-config header or invalid YAMLValidate with the schema command
Script ran on first boot onlyPer-instance module semanticsUse per-boot scripts or a systemd unit
Cloned image skips configurationStale instance data in /var/lib/cloudRun cloud-init clean before capturing
Package installation failsNetwork or mirror not reachable yetBake packages into the image or retry
Secrets visible to any processCredentials placed in user dataFetch secrets from a secrets manager at boot
Common cloud-init failures

Security deserves explicit attention. User data is not a secret store: on many platforms any local process able to reach the metadata service can read it, and it often appears in console and API output. Enforcing IMDSv2 session tokens on AWS and storing credentials in a dedicated secrets manager reduce this exposure considerably.

Explained without jargon

When a company rents a new server in the cloud, it starts as a blank, generic copy of an operating system. cloud-init is the setup assistant that runs the first time the server switches on. It reads a short note attached to the server and follows it: create these accounts, install these programs, write these settings, start these services.

It is similar to a new employee arriving on day one with a checklist taped to the desk. Nobody has to stand beside the server and type commands. The main point: one written checklist turns blank servers into ready-to-work machines, however many there are.

A typical use case

A platform team runs a web application on an auto scaling group of Ubuntu instances. Terraform defines the group and passes a cloud-config file of about 60 lines as user data. On each launch, cloud-init sets the hostname from instance metadata, creates a deployment user with an approved SSH key, writes an Nginx site file, fetches database credentials from a secrets manager and starts the application service.

Heavy dependencies such as the language runtime are already baked into the image with Packer, so instances become healthy in under two minutes instead of ten. When traffic doubles on a Monday morning, new instances join the load balancer automatically. The outcome is consistent, reproducible servers that no engineer configures by hand, and every configuration change goes through code review in the same repository as the infrastructure.