How to Generate a cloud-init User Data Mock in Python

Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 14 views 0 copies

Python code

37 lines
Python 3.9+
import json
from dataclasses import dataclass, asdict

@dataclass
class VMConfig:
    hostname: str
    cpus: int
    memory_mb: int
    ssh_key: str

def generate_cloud_init_mock(config: VMConfig) -> str:
    """Build a cloud-init user-data mock for a VM."""
    user_data = {
        "hostname": config.hostname,
        "users": [
            {
                "name": "admin",
                "sudo": "ALL=(ALL) NOPASSWD:ALL",
                "ssh_authorized_keys": [config.ssh_key],
            }
        ],
        "package_update": True,
        "packages": ["curl", "vim"],
    }
    user_data_str = f"#cloud-config\n{json.dumps(asdict(config))}\n" + json.dumps(user_data, indent=2)
    # Simulate provisioning by printing the mock payload
    print(user_data_str)
    return user_data_str

if __name__ == "__main__":
    demo = VMConfig(
        hostname="web-01",
        cpus=2,
        memory_mb=2048,
        ssh_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... mock-key"
    )
    generate_cloud_init_mock(demo)

Output

stdout
#cloud-config
{"hostname": "web-01", "cpus": 2, "memory_mb": 2048, "ssh_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... mock-key"}
{
  "hostname": "web-01",
  "users": [
    {
      "name": "admin",
      "sudo": "ALL=(ALL) NOPASSWD:ALL",
      "ssh_authorized_keys": [
        "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... mock-key"
      ]
    }
  ],
  "package_update": true,
  "packages": [
    "curl",
    "vim"
  ]
}

How it works

The VMConfig dataclass holds VM properties, and generate_cloud_init_mock builds a dictionary representing the cloud-init user-data config. It uses json.dumps to serialize the config into a string, prepending the #cloud-config header. This mock payload can be used to test provisioning scripts without actually launching a VM. The function prints the payload and returns it as a string for further use.

Common mistakes

  • Forgetting the `#cloud-config` header, which cloud-init requires at the top.
  • Using `json.dumps` on the whole dictionary without indentation, making it hard to read.
  • Including sensitive SSH keys in plain text; use secrets in production.

Variations

  1. Use `yaml.dump` instead of `json.dumps` since cloud-init commonly uses YAML format.
  2. Read the SSH key from a file rather than hardcoding it.

Real-world use cases

  • Testing VM provisioning automation in CI/CD pipelines without spawning actual cloud instances.
  • Generating cloud-init user data for development and staging environments to ensure consistency.
  • Validating configuration templates in infrastructure-as-code workflows before deployment.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.