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.
Python code
37 linesimport 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
#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
- Use `yaml.dump` instead of `json.dumps` since cloud-init commonly uses YAML format.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.