puppet-enc/enc.py
Ben Vincent 814b4e59b4 fix: enc outputs *id001 in class/environment
- the slice notation [:] creates a shallow copy of the list
- when dumping the data, it will not use the anchors and aliases because it
treats the values in enc_role and classes as separate lists
2023-11-05 17:51:28 +11:00

61 lines
1.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""
External Node Classifier (ENC) for Puppet.
It reads in YAML files located at '/opt/puppetlabs/enc/data'.
If the environment specified in the YAML file is 'testing',
the environment is not included in the output.
"""
import sys
import yaml
def main():
# Get the hostname from the command line arguments
if len(sys.argv) != 2:
print("Usage: {} <hostname>".format(sys.argv[0]), file=sys.stderr)
sys.exit(1)
hostname = sys.argv[1]
# Construct the file path
file_path = "/opt/puppetlabs/enc/data/{}.yaml".format(hostname)
# Try to open and read the YAML file
try:
with open(file_path, "r") as f:
data = yaml.safe_load(f)
# Initialize 'parameters' if it doesn't exist
if "parameters" not in data:
data["parameters"] = {}
# Add 'enc_role' parameter with classes data
if "classes" in data:
data["parameters"]["enc_role"] = data["classes"][:]
# Copy the environment to the parameters, if it exists
if data.get("environment"):
data["parameters"]["enc_env"] = data["environment"][:]
# If the environment is 'testing', remove it
if data.get("environment") == "testing":
data.pop("environment", None)
# Print the YAML without the 'environment' if it was 'testing'
print(yaml.dump(data))
except IOError as e:
print("Could not open {}: {}".format(file_path, e), file=sys.stderr)
sys.exit(1)
except yaml.YAMLError as e:
print("Error in {}: {}".format(file_path, e), file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()