SaltStack Top File首次执行Highstate时smtp*匹配规则不生效问题求助
I’ve run into a similar scenario before with Salt’s target matching on first minion startup, so let’s break down what might be going wrong here and how to fix it.
Your Setup Recap
You’ve configured a Top File that should apply sls_file_1/sls_file_2 to all minions, and sls_file_3/sls_file_4 to minions with hostnames starting with smtp*. You’ve added an ExecStartPre script to set the hostname and minion_id before the salt-minion service starts, but on first boot Highstate only runs the * targets.
Likely Root Causes & Fixes
1. Temporary vs. Persistent Hostname Mismatch
Your add_minion_id.sh uses the hostname command, which only sets the temporary runtime hostname—some systemd-based systems don’t immediately sync this with the /etc/hostname file for system-level hostname resolution. Salt’s grains (which drive target matching) might still pick up the old default hostname until the system fully recognizes the new one.
Fix: Replace the hostname $new_hostname line with hostnamectl set-hostname $new_hostname. This updates both the runtime and persistent hostname in one step, ensuring the system and Salt see the correct hostname immediately.
Modified snippet from your script:
# Replace hostname $new_hostname with this hostnamectl set-hostname $new_hostname echo $new_hostname > /etc/salt/minion_id echo $new_hostname > /etc/hostname
2. Salt Minion Cache Retaining Old Data
If this is a fresh provisioning, there might be leftover cache from the initial minion installation holding an old minion_id or grain data. Even if you set the new hostname, the minion might use cached values on first start.
Fix: Add a cache cleanup step to your ExecStartPre script to ensure the minion starts with a clean slate:
# Add this at the start of your script rm -rf /var/cache/salt/minion/*
3. Minion ID File Permissions
Ensure the /etc/salt/minion_id file has correct permissions so the salt-minion user can read it. If the file is owned by root with restrictive permissions, the minion might fall back to the default hostname.
Fix: Add permission setup to your script:
echo $new_hostname > /etc/salt/minion_id chown salt:salt /etc/salt/minion_id chmod 644 /etc/salt/minion_id
4. Verify Grain Values Post-Startup
To confirm the issue, after first boot run these commands on the smtp minion to check what Salt sees:
# Check the minion ID Salt is using salt-call grains.get id # Check the hostname grain salt-call grains.get hostname
If either returns the old default hostname instead of your smtp* name, that confirms the hostname/grain isn’t being picked up correctly at minion start.
Final Test
After applying these fixes, provision a new smtp minion and run Highstate. The smtp* targets should now execute alongside the * targets on first run.
内容的提问来源于stack exchange,提问作者Aishwarya Naidu

