Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
VGSOURCES
Get listed

cloud-configPATCH 2026.10.15

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

By VGSources Team 10 min read

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

Cloud-init can turn a fresh Linux VPS into a configured server during its first boot. Supply user-data when you launch the instance, use a #cloud-config YAML document for users, packages and files, and reserve runcmd or a shebang-based script for commands that must run after those resources exist.

The reliable workflow is: confirm the image has cloud-init enabled, build and validate the YAML, launch one test instance, inspect cloud-init’s status and logs, and verify the account, key, files, packages and services. Most modules run once per instance, so a reboot is not a general-purpose way to apply changed user-data.

As an Amazon Associate I earn from qualifying purchases.

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

What cloud-init does when a VPS starts

Cloud-init is the guest-side service that consumes user-data supplied by a cloud or virtualization platform. The platform must attach that data to the instance at launch, and the selected Linux image must include an installed and enabled cloud-init service. The console field, metadata endpoint and datasource differ by provider, so a script that works on one VPS platform may require a different launch setting on another.

There are two common user-data formats:

  • Cloud-config: a YAML document whose first line is #cloud-config. It declares users, packages, files, SSH keys and commands through cloud-init modules.
  • Executable user-data script: a text file beginning with a shebang such as #!/bin/sh. Cloud-init runs it through the final-stage cc_scripts_user module.

Cloud-config is usually the maintainable default because each operation is visible in a named section. A shell script is useful when you already have imperative setup logic or need shell control flow that does not map cleanly to a module.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses | Anti UV Ray, For Computers & Gaming, Square Frame, Eyewear for Men and Women
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Why first-boot timing matters

Cloud-init processes modules in stages. A command in runcmd is not executed at the instant cloud-init parses the YAML. The runcmd module writes a script, and the later scripts_user step executes that script during the final stage. A service-start command can therefore run after package installation and file creation, but still later than an interactive SSH login attempt made during boot.

Why a reboot usually does not repeat setup

Most cloud-init modules are designed for once-per-instance execution. Restarting the VPS does not normally replay every user-data module. If you change the configuration, use the provider’s documented clean-and-rerun procedure only when you understand its effect, or build a replacement instance and test the new data there.

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

Cloud-config or a shell script?

Approach Input format Strength Execution behavior Main risk
Cloud-config YAML beginning with #cloud-config Declarative users, packages, files and commands Individual modules run in cloud-init stages; runcmd writes a later script YAML quoting and provider-specific assumptions can cause failures
User-data shell script Executable text beginning with a shebang Familiar shell logic, branching and loops Normally runs once in the final stage through cc_scripts_user Ordering, idempotence and shell error handling are your responsibility

For a repeatable VPS bootstrap, use cloud-config for accounts, SSH keys, package installation and deterministic files. Add short, idempotent commands to runcmd. Choose a shell script when the setup genuinely needs shell logic, but keep it small and make its assumptions explicit.

Prerequisites before you write user-data

  • Choose an image that has cloud-init installed and enabled. A plain image without the service cannot consume your YAML.
  • Find the provider’s launch field for user-data and confirm whether it accepts raw text, a file upload or a datasource-specific format.
  • Identify the distribution’s package names, default login account, service names and SSH daemon paths. These vary across distributions.
  • Have an SSH public key ready. Prefer key-based access to embedding a plaintext password.
  • Decide which files must persist after boot. Use a persistent path for those files; use /run only for intentionally temporary runtime data.
  • Keep credentials and other secrets out of user-data whenever possible. User-data can be exposed through provider consoles, metadata or logs.

Build a cloud-config file step by step

Start with the header and package declarations

The first line must identify the document as cloud-config. Set package_update: true when the image’s package indexes should be refreshed, then list packages under packages. This is preferable to embedding a long package-manager command in a shell block.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Create the administrative login safely

Under users, include default when you need the distribution’s normal account and any SSH keys injected by the image or provider to remain available. Add a separate deployment account with its groups, shell, sudo rule and public key. The example below grants passwordless sudo to that account; use the least privilege appropriate for your environment.

Write configuration files deterministically

write_files creates a file with an exact path, permission mode and content. It is suitable for service configuration, notices and small environment files. Do not place a file that must survive setup in /tmp: cleanup services can remove it while cloud-init is still running.

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.

Run only the commands that need ordering

Use runcmd for enabling or starting a service and for small post-install tasks. List-form commands preserve argument boundaries and avoid unnecessary shell parsing. String-form commands are interpreted by sh, which is useful for pipes, redirection or shell operators but requires careful quoting.

#cloud-config
package_update: true
packages:
  - nginx
users:
  - default
  - name: deploy
    groups: [sudo]
    shell: /bin/bash
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    ssh_authorized_keys:
      - ssh-ed25519 AAAA...replace-with-your-public-key
write_files:
  - path: /etc/motd.d/cloud-init
    permissions: '0644'
    content: |
      Provisioned by cloud-init
runcmd:
  - [systemctl, enable, --now, nginx]
  - [sh, -c, 'echo ready >/var/lib/cloud-init-ready']

Replace the example public key with your own complete key. Replace nginx with the package and service your VPS actually uses. The final command writes a marker only after the preceding commands reach the runcmd stage; it is a simple way to check that the section ran.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men | Office Gifts for Women, iPhone Stand, Gadgets for Men, Office Decor, Gaming Desk Accessories for Samsung Fold 8, Switch, iPad
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

How to run a cloud-init script when your VPS starts

  1. Confirm support. Check the image documentation or the running image for an enabled cloud-init service. Verify that your provider passes launch-time user-data to that image’s datasource.
  2. Prepare the document. Save the YAML as a plain-text file beginning with #cloud-config. Keep the provider’s user-data field separate from any later configuration-management system.
  3. Add the minimum bootstrap. Define the required login account and SSH key, then add package_update, packages, write_files and runcmd only as needed.
  4. Validate before launch. Parse the YAML with a trusted validator and inspect indentation. Quote values containing a colon, braces, shell operators or leading zeroes so YAML does not reinterpret them.
  5. Launch a disposable test instance. Use the provider’s documented user-data control and wait for the first boot to finish. Do not begin with a production VPS that contains irreplaceable data.
  6. Check cloud-init itself. Inspect status and the two standard logs: /var/log/cloud-init.log and /var/log/cloud-init-output.log. A status command such as cloud-init status --wait can help you wait for completion when it is available on the image.
  7. Verify the result. Log in with the intended account and key; confirm package versions, file ownership and modes, the marker file, and the service’s enabled and active state.
  8. Promote only after verification. Once the test instance matches the intended result, reuse the validated user-data for the production launch and record the image, distribution and provider assumptions alongside it.

What should go in cloud-config?

Users and SSH keys

Use the users module for account creation, group membership, login shell, sudo policy and authorized keys. Include default when retaining the image’s standard user and provider-injected keys matters. Omitting it can leave you with a newly created account but no expected default login path.

Packages

Put normal software installation under packages. Cloud-init can update package indexes first with package_update: true. Package names differ by distribution, so document the target image and do not assume that a package name or service unit is universal.

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

Files

Use write_files when the file’s contents, path and permissions should be reproducible. Choose locations under /etc, /var/lib or another persistent filesystem according to what the service expects. Avoid /tmp for cloud-init-managed files because a system cleanup job can race with the bootstrap process.

Commands

Use list-form runcmd entries such as [systemctl, enable, --now, service] when no shell interpretation is needed. Use a string only when you intentionally need shell syntax. Quote YAML-sensitive text, especially values containing a colon; otherwise the parser can treat part of the value as structure instead of data.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Why did runcmd run late or only once?

The apparent delay is expected. Cloud-init first parses the configuration and writes the runcmd script; the final-stage scripts module runs that script later in boot. Package installation and file creation can therefore precede the command, while network initialization or other modules may still affect the exact timing.

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

“Only once” is also normal. The final-stage user-data script and many cloud-init modules are guarded by per-instance state. A reboot is not equivalent to a fresh launch. To apply a changed command, either use the platform’s supported clean-and-rerun process or rebuild the VPS. Test that process on a disposable instance because cleaning instance state can affect other initialization data.

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

Make the setup portable and safe to rerun

Parameterize distribution assumptions

Default usernames, package names, service names and SSH daemon locations vary across distributions. Keep those values in clearly identified sections, select an image deliberately, and avoid presenting one distribution’s paths as universal. If the same bootstrap targets multiple images, use separate validated variants rather than silently guessing.

Prefer naturally idempotent operations

Package declarations, writing a file to a fixed path and enabling a named service are easier to reason about than an unbounded shell script. For custom commands, use marker files or checks so a rerun does not duplicate users, append the same line repeatedly or overwrite data unexpectedly. The marker-file pattern in the example is useful for observation, not a substitute for checking the actual service state.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Use Jinja only with known instance data

Cloud-init can render Jinja templates from instance-data. A variable that does not exist for the target datasource produces a warning and a CI_MISSING_JINJA_VAR/... marker. Test every variable name against the target image and datasource before relying on rendered values. A template that silently assumes one provider’s metadata can fail when moved to another.

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

Security decisions for user-data

  • Use SSH public keys instead of plaintext passwords whenever the image and provider support them.
  • Do not hard-code long-lived API tokens, private keys or database passwords in user-data. Prefer a later secret-delivery mechanism appropriate to the platform.
  • Limit sudo rules to the accounts and commands that need them. The example’s NOPASSWD rule is convenient for automation but grants broad authority.
  • Review file permissions in write_files. A configuration containing credentials should not use a world-readable mode.
  • Remember that cloud-init logs can contain command output. Avoid echoing secrets and inspect log access controls on the finished VPS.

Troubleshooting common failures

Symptom Likely cause What to check or change
No account, package or file appears User-data was not passed, or the image lacks enabled cloud-init Confirm the provider’s launch field, datasource support and cloud-init service before changing YAML
YAML is rejected or later keys are ignored Indentation or an unquoted YAML-sensitive value Validate the document; quote colons, braces, shell operators and leading zeroes
The command appears to run late runcmd is executed in the final stage, not while YAML is parsed Wait for cloud-init completion and inspect both log files before judging timing
A reboot does not apply edited user-data Per-instance execution state prevents a normal rerun Use the provider’s clean-and-rerun procedure or rebuild the instance
The expected default login no longer works The users list replaced the image’s default-user handling Include default when retaining the normal account and injected keys is required
A file disappears during setup It was written under /tmp and cleaned by a system timer Move persistent content to a durable path; reserve /run for intentional runtime files
A service fails to start Wrong package name, unit name, path or distribution assumption Check the target distribution’s package and service names, then inspect cloud-init output and service status
Template output contains a missing-variable marker Jinja referenced data unavailable from that datasource Verify the variable against the target instance-data schema or remove the template dependency

Adapting the pattern for a game-server VPS

The same bootstrap sequence works when the VPS will host a game service: create the administrative account, install the distribution’s required packages, write configuration files, and enable the service after installation. Keep the game daemon’s package name, unit name, data directory and required permissions explicit for the chosen distribution. Do not assume that a command or path from one image is portable to another.

For a large or stateful game installation, keep user-data focused on the base operating environment. Fetching extensive game assets, secrets or changing world data in a one-shot first-boot script makes failures harder to recover from. Use cloud-init to establish a predictable starting point, then let a service-specific deployment process manage content that changes independently of the VPS image.

Final launch checklist

  • The selected image includes enabled cloud-init and the provider passes user-data to it.
  • The file begins with #cloud-config and passes YAML validation.
  • The intended account, SSH key and sudo policy are explicit; default is present when required.
  • Packages are listed under packages, with the correct names for the target distribution.
  • Persistent files use durable paths and have deliberate permissions.
  • runcmd uses list form unless shell parsing is intentional.
  • Secrets are kept out of user-data and command output where possible.
  • A test instance has been checked through cloud-init status, both logs, account access, package versions, file modes and service state.
  • The team knows that most modules are once per instance and has a documented rebuild or clean-and-rerun plan.

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-configcloud-initLinux administrationLinux VPSServer Automation

Leave a reply

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

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.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.