Configure a virtual machine at first boot with cloud-init

Pass cloud-init user data when you create a virtual machine to install packages, write files, and run commands on its first boot.

User data is a configuration or a script that cloud-init runs when an instance boots for the first time. Use it to install packages, write files, and run commands without signing in to the instance.

Before you begin

  • Use an image that runs cloud-init. Without it, the instance doesn't get your user data or its SSH keys.
  • Prepare your user data as text in one of these formats:
    • A cloud-config document whose first line is #cloud-config.
    • A shell script whose first line starts with #!, such as #!/bin/bash.
  • Plan ahead: you can set user data only when you create an instance, and the platform refuses to change it on an existing instance. To use different user data, create a new instance.

Add user data

In the creation wizard, go to the Advanced step.

In User data (cloud-init), paste your user data. To load it from a text file instead, select Load from file.

Complete the wizard, and create the instance. See Create a virtual machine.

  • Paste plain text. The platform encodes the user data in Base64 for you.
  • Load from file replaces the field's content with the file's text, which you can still edit. A file that isn't text, such as an image or a program, is refused.
  • The wizard doesn't keep user data in its draft. If you reload the wizard, enter the user data again.
  • The REST equivalent on the review step includes your user data in plain text. Keep that in mind if your user data contains secrets.

Examples

This cloud-config document updates the package index, installs nginx, and makes sure that the service runs:

Install nginx
#cloud-config
package_update: true
packages:
  - nginx
runcmd:
  - systemctl enable --now nginx

This cloud-config document writes a configuration file:

Write a file
#cloud-config
write_files:
  - path: /etc/myapp/config.json
    permissions: "0644"
    content: |
      {"environment": "production"}

This shell script writes a message of the day:

Run a script
#!/bin/bash
echo "Provisioned on $(date -u)" > /etc/motd

For every cloud-config option, see the cloud-init documentation.

User data and sign-in settings

Your user data doesn't need to contain the SSH keys or the administrator account. The platform sets them up from what you select in the creation wizard.

Check the result

Sign in to the instance. See Connect to a virtual machine.

Run cloud-init status --long to see whether cloud-init has finished and whether it reported errors.

If you can't sign in, download the serial console log on the instance's Connect tab to review the boot output. See Download the serial console log.

On this page