1 require 'puppet/util/execution'
7 module Puppet::Parser::Functions
8 newfunction(:validate_cmd, :doc => <<-'DOC') do |args|
9 Perform validation of a string with an external command.
10 The first argument of this function should be a string to
11 test, and the second argument should be a path to a test command
12 taking a % as a placeholder for the file path (will default to the end).
13 If the command, launched against a tempfile containing the passed string,
14 returns a non-null value, compilation will abort with a parse error.
16 If a third argument is specified, this will be the error message raised and
19 A helpful error message can be returned like this:
23 # Defaults to end of path
24 validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
27 validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
30 if (args.length < 2) || (args.length > 3)
31 raise Puppet::ParseError, "validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)"
34 msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}"
39 # Test content in a temporary file
40 tmpfile = Tempfile.new('validate_cmd')
42 tmpfile.write(content)
45 check_with_correct_location = if checkscript =~ %r{\s%(\s|$)}
46 checkscript.gsub(%r{%}, tmpfile.path)
48 "#{checkscript} #{tmpfile.path}"
51 if Puppet::Util::Execution.respond_to?('execute')
52 Puppet::Util::Execution.execute(check_with_correct_location)
54 Puppet::Util.execute(check_with_correct_location)
56 rescue Puppet::ExecutionFailure => detail
58 raise Puppet::ParseError, msg
59 rescue StandardError => detail
60 msg += "\n#{detail.class.name} #{detail}"
61 raise Puppet::ParseError, msg