You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Web表单值构建Linux/WHM/cPanel子域名的Puppet脚本开发咨询

Great question! Let's break this down into two clear parts: building a web-form driven script for WHM/cPanel, and then exploring how Puppet fits into the picture.

1. Web Form-Driven Subdomain Creation Script for WHM/cPanel

The safest way to handle this is to leverage WHM's official API instead of manually editing server files—this avoids breaking cPanel's internal state. Here's a step-by-step approach:

Step 1: Build the Web Form

Start with a simple HTML form to collect necessary details (adjust fields based on your needs):

<form action="create-subdomain.php" method="POST">
  <label for="subdomain">Subdomain Name:</label>
  <input type="text" id="subdomain" name="subdomain" required>
  
  <label for="rootdomain">Root Domain (optional):</label>
  <input type="text" id="rootdomain" name="rootdomain" value="yourmaindomain.com">
  
  <button type="submit">Create Subdomain</button>
</form>

Step 2: Backend Script (PHP Example)

Write a backend script to validate input, call the WHM API, and return feedback. Make sure to use a WHM API token (create one in WHM > Manage API Tokens) with only the permissions needed (e.g., create_subdomain):

<?php
// Validate input first
$subdomain = $_POST['subdomain'] ?? '';
$rootdomain = $_POST['rootdomain'] ?? 'yourmaindomain.com';

// Basic input sanitization
if (!preg_match('/^[a-zA-Z0-9-]+$/', $subdomain)) {
    die("Invalid subdomain format—use only letters, numbers, and hyphens.");
}

// WHM API credentials (store these in environment variables or a secure config file, NOT hard-coded!)
$whmHost = 'your-server-ip';
$whmUser = 'root'; // Or a reseller user with permissions
$apiToken = getenv('WHM_API_TOKEN');

// Call WHM API to create subdomain
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$whmHost:2087/json-api/create_subdomain?api.version=1&domain=$subdomain.$rootdomain&rootdomain=$rootdomain");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // Disable only if you trust the server; use valid certs in production
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: whm $whmUser:$apiToken"
]);

$response = curl_exec($ch);
curl_close($ch);

$responseData = json_decode($response, true);

if ($responseData['metadata']['result'] == 1) {
    echo "Success! Subdomain $subdomain.$rootdomain created.";
} else {
    echo "Error: " . $responseData['metadata']['reason'];
}
?>

Critical Security Notes

  • Never hard-code API tokens: Use environment variables or a secure, non-web-accessible config file.
  • Filter and validate all input: Prevent injection attacks or invalid domain names.
  • Use HTTPS: Ensure the form and script are served over HTTPS to protect credentials and data.
  • Restrict script access: Use .htaccess or server config to limit who can access the backend script.
2. Using Puppet to Create Subdomains from Web Form Values

Absolutely—you can integrate Puppet into this workflow, but since Puppet operates on a pull-based model, you'll need a middle layer to bridge the web form and Puppet's configuration system. Here's how:

Step 1: Capture Form Data to a Central Source

When the web form is submitted, store the subdomain details in a Puppet-accessible location. Options include:

  • A database (MySQL/PostgreSQL) that Puppet can query via custom facts.
  • A JSON/YAML file hosted on the Puppet master or a shared storage service.
  • A CMDB (Configuration Management Database) that Puppet integrates with.

Step 2: Fetch Data in Puppet

Create a custom fact (using Ruby) or use Hiera to pull the list of pending subdomains from your central source. For example, a custom fact might query the database and return an array of subdomains to create.

Step 3: Puppet Module for Subdomain Creation

Write a Puppet module that uses the WHM API to create subdomains. You can use the exec resource to call the WHM CLI command:

class subdomain_manager {
  $pending_subdomains = lookup('pending_subdomains', Array[String], 'first', [])
  
  $pending_subdomains.each |$subdomain| {
    # Split subdomain into name and root domain (adjust logic based on your data)
    $parts = split($subdomain, '\.')
    $sub_name = $parts[0]
    $root_domain = join($parts[1,-1], '.')
    
    exec { "create-subdomain-${subdomain}":
      command => "whmapi1 create_subdomain domain=${subdomain} rootdomain=${root_domain}",
      path    => '/usr/bin:/usr/sbin',
      unless  => "whmapi1 list_subdomains | grep -q ${subdomain}",
      user    => 'root',
    }
  }
}

Step 4: Trigger Puppet Runs

Since Puppet agents pull configs on a schedule (default every 30 minutes), you have two options for near-real-time creation:

  • Shorten the agent run interval (not ideal for large fleets, but works for small setups).
  • Use a webhook to trigger a Puppet agent run on the target server immediately after the form is submitted.

Key Considerations

  • Permissions: Ensure the Puppet agent user has access to the WHM API or sufficient sudo privileges to run whmapi1.
  • Idempotency: The unless clause in the exec resource ensures Puppet doesn't recreate the same subdomain repeatedly.
  • Data Validation: Add checks in Puppet to ensure the subdomain data is valid before attempting creation.

内容的提问来源于stack exchange,提问作者Pramodya Mendis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:28:14