Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › cloud automation

How to Use Cloud-Init Scripts to Set Up a New Linux VPS

By Freedom251 Team · · 10 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable way to automate a new Linux VPS is to pass cloud-init user-data when the instance is created. Cloud-init reads that data during first boot and can create an administrative user, install SSH keys and packages, write configuration files, set the hostname and locale, configure networking, and run commands. Choose an image that includes cloud-init, prepare valid YAML or an executable script, attach it through the provider’s creation workflow, and verify the result in the cloud-init logs before putting the server into service.

What cloud-init does on a new VPS

Cloud-init is the first-boot initialization system used by many Linux cloud images. The provider supplies user-data with the instance request; cloud-init processes that data through several boot stages and applies the requested changes inside the new virtual machine. Ubuntu describes it as the package responsible for early initialization of a cloud instance.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This makes cloud-init different from a script you run after logging in. It executes as part of provisioning, before you have completed normal administration, so it is well suited to repeatable server setup. A successful run can leave you with a named non-root account, an SSH key, installed software, files in known locations, enabled services, and a predictable hostname or locale.

  • Access: create a user, install its public key, lock password authentication, and grant the required sudo rights.
  • Software: refresh package metadata, upgrade packages when appropriate, and install a defined list such as nginx.
  • Configuration: write complete files with write_files rather than relying on fragile shell redirection.
  • Commands: use runcmd for late-stage actions such as enabling and starting a service.

Cloud-init is not a guarantee that every provider accepts every form of user-data. Image contents, the provider’s control panel or API, logging, and whether data can be changed later all matter.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Check image and provider support before creating the VPS

Use an image that contains cloud-init

Select a distribution image that includes and enables cloud-init. An image without the package will not automatically consume your user-data, even if the provider interface accepts a text field. DigitalOcean states that its latest Ubuntu and CentOS images support cloud-init; older, custom, or heavily modified images may behave differently.

For a cloud VPS, confirm the image notes and the provider’s user-data instructions before provisioning. Check the same points with any other provider you use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Is cloud-init installed and enabled in the selected image?
  • Does the control panel expose a startup-script or user-data field?
  • Does the API accept a user_data value, and does the CLI expose an equivalent option?
  • Where are console output and cloud-init logs available if SSH fails?
  • Can user-data be edited after creation, or must you rebuild the VPS?

DigitalOcean documents that user-data cannot be modified after a Droplet is created. Treat the file as versioned deployment input: review it, store it with your infrastructure configuration, and keep a known-good copy before you click Create.

Choose the right user-data format

Format Best use Important behavior
#cloud-config YAML Declarative users, packages, files, and services Keys such as users, packages, write_files, and runcmd must be valid YAML with correct indentation.
Executable user-data script Shell logic, branching, or a short provider-specific bootstrap Start with a valid shebang such as #!/bin/bash. A user-data script runs once per instance.
MIME multipart Combining cloud-config, scripts, and frequency-specific parts Lets you combine content types and use per-boot or per-once script frequencies when required.

Do not put shell commands directly into a cloud-config document without using a supported key. Cloud-config is parsed as YAML; a shell script is interpreted by its shebang. Mixing the two formats without a MIME wrapper commonly produces a file that cloud-init accepts but cannot execute as intended.

Create secure access before installing applications

Make access the first deliberate part of the configuration. Keep the distribution’s default user when you need provider-injected keys or recovery access, then add a named administrative account for normal work. SSH public-key authentication is safer than putting a password in user-data. Cloud-init warns that password hashes in intercepted cloud-config are a security risk.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Preserve the image default user when necessary

If you define the users list, include default when the image’s original account and the provider’s injected SSH key are still required. Omitting it can remove or bypass the account you expected to use for the first login.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a named non-root account

Give the account a fixed name, shell, group membership, and public key. Grant only the sudo rights the workload needs. The example below uses passwordless sudo for a deployment account because it is convenient for unattended administration; replace that rule with a narrower command allow-list when your policy requires it. Keep lock_passwd: true when key-only access is intended.

Use this starter cloud-config

Replace the account name and public key before creating the VPS. The document installs nginx, writes a small motd file, and enables the service after package installation.

#cloud-config
users:
  - default
  - name: deploy
    groups: [sudo]
    sudo: ["ALL=(ALL) NOPASSWD:ALL"]
    shell: /bin/bash
    lock_passwd: true
    ssh_authorized_keys:
      - ssh-ed25519 REPLACE_WITH_YOUR_PUBLIC_KEY

package_update: true
packages:
  - nginx

write_files:
  - path: /etc/motd.d/cloud-init
    permissions: '0644'
    content: |
      Provisioned by cloud-init.

runcmd:
  - [ systemctl, enable, --now, nginx ]

package_update: true refreshes package metadata before the package list is processed. Add package_upgrade: true only when upgrading all image packages during first boot is part of your change policy; an upgrade can lengthen provisioning and alter more than the application you intended to install.

write_files creates the file with the declared content and permissions. The block scalar preserves line breaks, while quoting '0644' prevents YAML from treating the mode as an unintended number. For any value containing a colon, hash, braces, or other YAML-sensitive characters, quote it or use a block scalar.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

The list form of runcmd passes arguments without an extra shell parsing layer. It is preferable when arguments contain shell metacharacters. Every entry still has to be valid YAML; a typo in indentation or punctuation can prevent the command from being generated.

Attach user-data when the VPS is created

Control panel

In the provider’s instance-creation form, select the supported Linux image, locate the Startup scripts or User data field, and paste the complete document beginning with #cloud-config. Review the key and account name, then create the VPS. Save the exact text you submitted so that the resulting machine can be compared with the intended configuration.

DigitalOcean API

DigitalOcean accepts the content through the user_data field in the Droplet-creation API request. Send the complete YAML or script as the field value; do not send a local filename unless the API specifically requires a file upload.

DigitalOcean CLI

With doctl, pass inline content with --user-data or read a file with --user-data-file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
doctl compute droplet create my-vps 
  --image ubuntu-XX-XX-x64 
  --region your-region 
  --size your-size 
  --user-data-file ./cloud-init.yaml

Substitute the image, region, and size identifiers used by your account. The important operational point is that the user-data attachment happens during creation; DigitalOcean says it cannot be modified afterward. If the first attempt is wrong, correct the file and provision a replacement or repair the machine manually.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Understand when each cloud-init section runs

Early boot and bootcmd

bootcmd is intended for early-boot actions. Use it only for work that truly has to happen before later initialization modules. Early boot may not yet have the network, mounts, or services your command assumes, so moving ordinary application setup there can make failures intermittent.

Final-stage commands and runcmd

runcmd writes a generated script; the scripts_user module executes that script during cloud-init’s final stage. Its module frequency is once per instance. Package installation and file creation normally occur before this point, which is why enabling nginx in the example belongs in runcmd.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One-time and recurring scripts

A user-data script is a single script executed once per instance. MIME multipart lets you combine parts and select frequency-specific per-boot or per-once scripts when a task must recur. Do not assume that rebooting will rerun ordinary user-data; design recurring work explicitly.

Design for safe reruns

Although cloud-init’s normal frequency is once per instance, you may rerun steps while debugging or after a partial failure. Make commands idempotent: test whether a package is installed, create users only when absent, write complete files rather than appending duplicate lines, and guard destructive operations. A command that deletes data or blindly edits configuration can turn a troubleshooting run into an outage.

Avoid temporary files under /tmp during initialization. Cloud-init documents a race with systemd-tmpfiles-clean; use /run for transient data that must survive long enough for the current boot sequence.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Verify the first boot before relying on the server

Do not treat a successful VPS creation response as proof that the configuration ran. Verification has two parts: inspect cloud-init’s own output, then test the resulting system from the outside.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Open the provider console. If SSH is unavailable, use the out-of-band console to determine whether the machine booted and whether the network came up.
  2. Read command output. Inspect /var/log/cloud-init-output.log. DigitalOcean documents grepping this file for userdata when checking whether user-data was processed.
  3. Read module-level diagnostics. Inspect /var/log/cloud-init.log for parser errors, failed modules, package-manager failures, and the order in which stages ran.
  4. Test the intended login. Connect with the private key corresponding to the public key in the YAML and log in as the named user, not root.
  5. Check the account and privileges. Confirm the user exists, belongs to the expected groups, has the intended shell, and can use only the sudo rights you granted.
  6. Check applications and files. Verify that nginx or other packages are installed, the file from write_files exists with the expected permissions, and the service is enabled and running.
  7. Check the service itself. A cloud-init success line only means the command completed; inspect the service’s own status and logs for configuration or port-binding errors.

The practical success test is a reachable SSH login followed by confirmation of users, packages, files, and services. Keep the logs with the deployment record when diagnosing a failed build.

Troubleshoot common cloud-init failures

Nothing changed after creation

  • Confirm that the selected image includes and enables cloud-init.
  • Confirm that user-data was attached to the creation request, not entered into a field that belongs to a later automation feature.
  • Check the provider console and both cloud-init logs for evidence that the data was received.
  • On providers that make user-data immutable after creation, rebuild with the corrected file rather than waiting for an edit to take effect.

Cloud-config reports a YAML error

  • Check indentation; YAML uses spaces and is sensitive to nesting.
  • Quote values containing colons, hashes, braces, or other syntax characters.
  • Use the list form of runcmd for commands whose arguments contain shell metacharacters.
  • Look in /var/log/cloud-init.log for the line and module that failed, then correct the source file and test on a new instance.

SSH access is locked out

  • Verify that the public key exactly matches the private key you are using and belongs to the intended account.
  • Retain default in users when the distribution account or provider-injected key is needed for recovery.
  • Check the account’s home directory, .ssh directory, and authorized-key permissions from the provider console.
  • Use the console to repair the account before making another remote change.

runcmd appears to have been skipped

Remember that runcmd executes late. A package or network failure earlier in boot can prevent the expected service action. Read both cloud-init logs and the affected service’s logs. Confirm that the YAML parsed and that the generated command had the arguments you intended.

A package installation failed

Check network connectivity, DNS resolution, repository availability, and package-manager output in /var/log/cloud-init-output.log and /var/log/cloud-init.log. Do not simply rerun a failed install if the surrounding commands are destructive. First make the operation safe and idempotent, then repair or rebuild the instance.

The provider behaves differently than expected

Compare the provider’s supported images, control-panel field, API and CLI syntax, logging locations, SSH-key injection behavior, and user-data mutability. DigitalOcean documents these differences explicitly, and equivalent options are not guaranteed across providers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a repeatable provisioning workflow

  1. Version the file. Store the cloud-config or script with your infrastructure files and review changes like code. Keep secrets out of user-data whenever possible because provider systems and logs may expose it.
  2. Choose the image deliberately. Record the distribution and image release, and confirm cloud-init support before provisioning.
  3. Bootstrap access. Preserve the default account if required, create the named non-root user, install its SSH key, and apply the minimum sudo policy.
  4. Install only the required base packages. Use package_update, optional package_upgrade, and packages consistently.
  5. Write configuration deterministically. Use write_files with explicit permissions and complete contents.
  6. Perform late actions. Put service enablement and start commands in runcmd, using valid YAML and safe argument forms.
  7. Provision once and inspect. Attach the file through the provider’s supported interface, then read both cloud-init logs before making application-level assumptions.
  8. Record the result. Confirm SSH, users, packages, files, and services, and retain the exact user-data used for that machine.

Cloud-init limitations to plan for

  • It is image-dependent. A provider may accept user-data while the selected image lacks the software needed to process it.
  • It is normally first-boot automation. Ordinary user-data does not automatically run again after every reboot.
  • It is sensitive to ordering. Early commands, package installation, file creation, and final-stage commands run at different points.
  • It is not a secret store. Password hashes and other sensitive values in intercepted user-data create a security risk.
  • It is provider-dependent at the edges. Injection methods, logs, key handling, and editability vary even when the cloud-config syntax is the same.

Used with those constraints in mind, cloud-init turns a blank Linux VPS into a documented, repeatable baseline without requiring an operator to race through manual setup over an initial root session.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

cloud automationcloud-initLinux server administrationLinux VPSSSH keysVPS setup

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.