repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/generate.rb
lib/puppet/face/generate.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/generate/type' # Create the Generate face Puppet::Face.define(:generate, '0.1.0') do copyright 'Puppet Inc.', 2016 license _('Apache 2 license; see COPYING') summary _('Generates Puppet code from Ruby definitions.') action(:types) do summary _('Generates Puppet code for custom types') description <<-'EOT' Generates definitions for custom resource types using Puppet code. Types defined in Puppet code can be used to isolate custom type definitions between different environments. EOT examples <<-'EOT' Generate Puppet type definitions for all custom resource types in the current environment: $ puppet generate types Generate Puppet type definitions for all custom resource types in the specified environment: $ puppet generate types --environment development EOT option '--format ' + _('<format>') do summary _('The generation output format to use. Supported formats: pcore.') default_to { 'pcore' } before_action do |_, _, options| raise ArgumentError, _("'%{format}' is not a supported format for type generation.") % { format: options[:format] } unless ['pcore'].include?(options[:format]) end end option '--force' do summary _('Forces the generation of output files (skips up-to-date checks).') default_to { false } end when_invoked do |options| generator = Puppet::Generate::Type inputs = generator.find_inputs(options[:format].to_sym) environment = Puppet.lookup(:current_environment) # get the common output directory (in <envroot>/.resource_types) - create it if it does not exists # error if it exists and is not a directory # path_to_env = environment.configuration.path_to_env outputdir = File.join(path_to_env, '.resource_types') if Puppet::FileSystem.exist?(outputdir) && !Puppet::FileSystem.directory?(outputdir) raise ArgumentError, _("The output directory '%{outputdir}' exists and is not a directory") % { outputdir: outputdir } end Puppet::FileSystem.mkpath(outputdir) generator.generate(inputs, outputdir, options[:force]) exit(1) if generator.bad_input? nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/node.rb
lib/puppet/face/node.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/face' Puppet::Indirector::Face.define(:node, '0.0.1') do copyright "Puppet Inc.", 2011 license _("Apache 2 license; see COPYING") summary _("View and manage node definitions.") description <<-'EOT' This subcommand interacts with node objects, which are used by Puppet to build a catalog. A node object consists of the node's facts, environment, node parameters (exposed in the parser as top-scope variables), and classes. EOT deactivate_action(:destroy) deactivate_action(:search) deactivate_action(:save) find = get_action(:find) find.summary _("Retrieve a node object.") find.arguments _("<host>") # TRANSLATORS the following are specific names and should not be translated `classes`, `environment`, `expiration`, `name`, `parameters`, Puppet::Node find.returns _(<<-'EOT') A hash containing the node's `classes`, `environment`, `expiration`, `name`, `parameters` (its facts, combined with any ENC-set parameters), and `time`. When used from the Ruby API: a Puppet::Node object. RENDERING ISSUES: Rendering as string and json are currently broken; node objects can only be rendered as yaml. EOT find.examples <<-'EOT' Retrieve an "empty" (no classes, no ENC-imposed parameters, and an environment of "production") node: $ puppet node find somenode.puppetlabs.lan --terminus plain --render-as yaml Retrieve a node using the Puppet Server's configured ENC: $ puppet node find somenode.puppetlabs.lan --terminus exec --run_mode server --render-as yaml Retrieve the same node from the Puppet Server: $ puppet node find somenode.puppetlabs.lan --terminus rest --render-as yaml EOT end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/plugin.rb
lib/puppet/face/plugin.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/configurer/plugin_handler' Puppet::Face.define(:plugin, '0.0.1') do copyright "Puppet Inc.", 2011 license _("Apache 2 license; see COPYING") summary _("Interact with the Puppet plugin system.") description <<-'EOT' This subcommand provides network access to the puppet master's store of plugins. The puppet master serves Ruby code collected from the `lib` directories of its modules. These plugins can be used on agent nodes to extend Facter and implement custom types and providers. Plugins are normally downloaded by puppet agent during the course of a run. EOT action :download do summary _("Download plugins from the puppet master.") description <<-'EOT' Downloads plugins from the configured puppet master. Any plugins downloaded in this way will be used in all subsequent Puppet activity. This action modifies files on disk. EOT returns _(<<-'EOT') A list of the files downloaded, or a confirmation that no files were downloaded. When used from the Ruby API, this action returns an array of the files downloaded, which will be empty if none were retrieved. EOT examples <<-'EOT' Retrieve plugins from the puppet master: $ puppet plugin download Retrieve plugins from the puppet master (API example): $ Puppet::Face[:plugin, '0.0.1'].download EOT when_invoked do |_options| remote_environment_for_plugins = Puppet::Node::Environment.remote(Puppet[:environment]) begin handler = Puppet::Configurer::PluginHandler.new handler.download_plugins(remote_environment_for_plugins) ensure Puppet.runtime[:http].close end end when_rendering :console do |value| if value.empty? then _("No plugins downloaded.") else _("Downloaded these plugins: %{plugins}") % { plugins: value.join(', ') } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/parser.rb
lib/puppet/face/parser.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/parser' Puppet::Face.define(:parser, '0.0.1') do copyright "Puppet Inc.", 2014 license _("Apache 2 license; see COPYING") summary _("Interact directly with the parser.") action :validate do summary _("Validate the syntax of one or more Puppet manifests.") arguments _("[<manifest>] [<manifest> ...]") returns _("Nothing, or the first syntax error encountered.") description <<-'EOT' This action validates Puppet DSL syntax without compiling a catalog or syncing any resources. If no manifest files are provided, it will validate the default site manifest. When validating multiple issues per file are reported up to the settings of max_error, and max_warnings. The processing stops after having reported issues for the first encountered file with errors. EOT examples <<-'EOT' Validate the default site manifest at /etc/puppetlabs/puppet/manifests/site.pp: $ puppet parser validate Validate two arbitrary manifest files: $ puppet parser validate init.pp vhost.pp Validate from STDIN: $ cat init.pp | puppet parser validate EOT when_invoked do |*args| files = args.slice(0..-2) parse_errors = {} if files.empty? if !STDIN.tty? Puppet[:code] = STDIN.read error = validate_manifest(nil) parse_errors['STDIN'] = error if error else manifest = Puppet.lookup(:current_environment).manifest files << manifest Puppet.notice _("No manifest specified. Validating the default manifest %{manifest}") % { manifest: manifest } end end missing_files = [] files.each do |file| if Puppet::FileSystem.exist?(file) error = validate_manifest(file) parse_errors[file] = error if error else missing_files << file end end unless missing_files.empty? raise Puppet::Error, _("One or more file(s) specified did not exist:\n%{files}") % { files: missing_files.collect { |f| " " * 3 + f + "\n" } } end parse_errors end when_rendering :console do |errors| unless errors.empty? errors.each { |_, error| Puppet.log_exception(error) } exit(1) end # Prevent face_base renderer from outputting "null" exit(0) end when_rendering :json do |errors| unless errors.empty? ignore_error_keys = [:arguments, :environment, :node] data = errors.to_h do |file, error| file_errors = error.to_h.reject { |k, _| ignore_error_keys.include?(k) } [file, file_errors] end puts Puppet::Util::Json.dump(Puppet::Pops::Serialization::ToDataConverter.convert(data, rich_data: false, symbol_as_string: true), :pretty => true) exit(1) end # Prevent face_base renderer from outputting "null" exit(0) end end action(:dump) do summary _("Outputs a dump of the internal parse tree for debugging") arguments "[--format <old|pn|json>] [--pretty] { -e <source> | [<templates> ...] } " returns _("A dump of the resulting AST model unless there are syntax or validation errors.") description <<-'EOT' This action parses and validates the Puppet DSL syntax without compiling a catalog or syncing any resources. The output format can be controlled using the --format <old|pn|json> where: * 'old' is the default, but now deprecated format which is not API. * 'pn' is the Puppet Extended S-Expression Notation. * 'json' outputs the same graph as 'pn' but with JSON syntax. The output will be "pretty printed" when the option --pretty is given together with --format 'pn' or 'json'. This option has no effect on the 'old' format. The command accepts one or more manifests (.pp) files, or an -e followed by the puppet source text. If no arguments are given, the stdin is read (unless it is attached to a terminal) The output format of the dumped tree is intended for debugging purposes and is not API, it may change from time to time. EOT option "--e " + _("<source>") do default_to { nil } summary _("dump one source expression given on the command line.") end option("--[no-]validate") do summary _("Whether or not to validate the parsed result, if no-validate only syntax errors are reported") end option('--format ' + _('<old, pn, or json>')) do summary _("Get result in 'old' (deprecated format), 'pn' (new format), or 'json' (new format in JSON).") end option('--pretty') do summary _('Pretty print output. Only applicable together with --format pn or json') end when_invoked do |*args| require_relative '../../puppet/pops' options = args.pop if options[:e] dump_parse(options[:e], 'command-line-string', options, false) elsif args.empty? if !STDIN.tty? dump_parse(STDIN.read, 'stdin', options, false) else raise Puppet::Error, _("No input to parse given on command line or stdin") end else files = args available_files = files.select do |file| Puppet::FileSystem.exist?(file) end missing_files = files - available_files dumps = available_files.collect do |file| dump_parse(Puppet::FileSystem.read(file, :encoding => 'utf-8'), file, options) end.join("") if missing_files.empty? dumps else dumps + _("One or more file(s) specified did not exist:\n") + missing_files.collect { |f| " #{f}" }.join("\n") end end end end def dump_parse(source, filename, options, show_filename = true) output = ''.dup evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new begin if options[:validate] parse_result = evaluating_parser.parse_string(source, filename) else # side step the assert_and_report step parse_result = evaluating_parser.parser.parse_string(source) end if show_filename output << "--- #{filename}" end fmt = options[:format] if fmt.nil? || fmt == 'old' output << Puppet::Pops::Model::ModelTreeDumper.new.dump(parse_result) << "\n" else require_relative '../../puppet/pops/pn' pn = Puppet::Pops::Model::PNTransformer.transform(parse_result) case fmt when 'json' options[:pretty] ? JSON.pretty_unparse(pn.to_data) : JSON.dump(pn.to_data) else pn.format(options[:pretty] ? Puppet::Pops::PN::Indent.new(' ') : nil, output) end end rescue Puppet::ParseError => detail if show_filename Puppet.err("--- #{filename}") end Puppet.err(detail.message) "" end end # @api private def validate_manifest(manifest = nil) env = Puppet.lookup(:current_environment) loaders = Puppet::Pops::Loaders.new(env) Puppet.override({ :loaders => loaders }, _('For puppet parser validate')) do validation_environment = manifest ? env.override_with(:manifest => manifest) : env validation_environment.check_for_reparse validation_environment.known_resource_types.clear rescue Puppet::ParseError => parse_error return parse_error end nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/catalog.rb
lib/puppet/face/catalog.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/face' Puppet::Indirector::Face.define(:catalog, '0.0.1') do copyright "Puppet Inc.", 2011 license "Apache 2 license; see COPYING" summary _("Compile, save, view, and convert catalogs.") description <<-'EOT' This subcommand deals with catalogs, which are compiled per-node artifacts generated from a set of Puppet manifests. By default, it interacts with the compiling subsystem and compiles a catalog using the default manifest and `certname`, but you can change the source of the catalog with the `--terminus` option. You can also choose to print any catalog in 'dot' format (for easy graph viewing with OmniGraffle or Graphviz) with '--render-as dot'. EOT short_description <<-'EOT' This subcommand deals with catalogs, which are compiled per-node artifacts generated from a set of Puppet manifests. By default, it interacts with the compiling subsystem and compiles a catalog using the default manifest and `certname`; use the `--terminus` option to change the source of the catalog. EOT deactivate_action(:destroy) deactivate_action(:search) action(:find) do summary _("Retrieve the catalog for the node from which the command is run.") arguments "<certname>, <facts>" option("--facts_for_catalog") do summary _("Not implemented for the CLI; facts are collected internally.") end returns <<-'EOT' A serialized catalog. When used from the Ruby API, returns a Puppet::Resource::Catalog object. EOT when_invoked do |*args| # Default the key to Puppet[:certname] if none is supplied if args.length == 1 key = Puppet[:certname] else key = args.shift end call_indirection_method :find, key, args.first end end action(:apply) do summary "Find and apply a catalog." description <<-'EOT' Finds and applies a catalog. This action takes no arguments, but the source of the catalog can be managed with the `--terminus` option. EOT returns <<-'EOT' Nothing. When used from the Ruby API, returns a Puppet::Transaction::Report object. EOT examples <<-'EOT' Apply the locally cached catalog: $ puppet catalog apply --terminus yaml Retrieve a catalog from the master and apply it, in one step: $ puppet catalog apply --terminus rest API example: # ... Puppet::Face[:catalog, '0.0.1'].download # (Termini are singletons; catalog.download has a side effect of # setting the catalog terminus to yaml) report = Puppet::Face[:catalog, '0.0.1'].apply # ... EOT when_invoked do |_options| catalog = Puppet::Face[:catalog, "0.0.1"].find(Puppet[:certname]) or raise "Could not find catalog for #{Puppet[:certname]}" catalog = catalog.to_ral report = Puppet::Transaction::Report.new report.configuration_version = catalog.version report.environment = Puppet[:environment] Puppet::Util::Log.newdestination(report) begin benchmark(:notice, "Finished catalog run in %{seconds} seconds") do catalog.apply(:report => report) end rescue => detail Puppet.log_exception(detail, "Failed to apply catalog: #{detail}") end report.finalize_report report end end action(:compile) do summary _("Compile a catalog.") description <<-'EOT' Compiles a catalog locally for a node, requiring access to modules, node classifier, etc. EOT examples <<-'EOT' Compile catalog for node 'mynode': $ puppet catalog compile mynode --codedir ... EOT returns <<-'EOT' A serialized catalog. EOT when_invoked do |*args| Puppet.settings.preferred_run_mode = :server Puppet::Face[:catalog, :current].find(*args) end end action(:download) do summary "Download this node's catalog from the puppet master server." description <<-'EOT' Retrieves a catalog from the puppet master and saves it to the local yaml cache. This action always contacts the puppet master and will ignore alternate termini. The saved catalog can be used in any subsequent catalog action by specifying '--terminus yaml' for that action. EOT returns "Nothing." notes <<-'EOT' When used from the Ruby API, this action has a side effect of leaving Puppet::Resource::Catalog.indirection.terminus_class set to yaml. The terminus must be explicitly re-set for subsequent catalog actions. EOT examples <<-'EOT' Retrieve and store a catalog: $ puppet catalog download API example: Puppet::Face[:plugin, '0.0.1'].download Puppet::Face[:facts, '0.0.1'].upload Puppet::Face[:catalog, '0.0.1'].download # ... EOT when_invoked do |_options| Puppet::Resource::Catalog.indirection.terminus_class = :rest Puppet::Resource::Catalog.indirection.cache_class = nil facts = Puppet::Face[:facts, '0.0.1'].find(Puppet[:certname]) catalog = nil retrieval_duration = thinmark do catalog = Puppet::Face[:catalog, '0.0.1'].find(Puppet[:certname], { facts_for_catalog: facts }) end catalog.retrieval_duration = retrieval_duration catalog.write_class_file Puppet::Resource::Catalog.indirection.terminus_class = :yaml Puppet::Face[:catalog, "0.0.1"].save(catalog) Puppet.notice "Saved catalog for #{Puppet[:certname]} to #{Puppet::Resource::Catalog.indirection.terminus.path(Puppet[:certname])}" nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/epp.rb
lib/puppet/face/epp.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/pops' require_relative '../../puppet/parser/files' require_relative '../../puppet/file_system' Puppet::Face.define(:epp, '0.0.1') do copyright "Puppet Inc.", 2014 license _("Apache 2 license; see COPYING") summary _("Interact directly with the EPP template parser/renderer.") action(:validate) do summary _("Validate the syntax of one or more EPP templates.") arguments _("[<template>] [<template> ...]") returns _("Nothing, or encountered syntax errors.") description <<-'EOT' This action validates EPP syntax without producing any output. When validating, multiple issues per file are reported up to the settings of max_error, and max_warnings. The processing stops after having reported issues for the first encountered file with errors unless the option --continue_on_error is given. Files can be given using the `modulename/template.epp` style to lookup the template from a module, or be given as a reference to a file. If the reference to a file can be resolved against a template in a module, the module version wins - in this case use an absolute path to reference the template file if the module version is not wanted. Exits with 0 if there were no validation errors. EOT option("--[no-]continue_on_error") do summary _("Whether or not to continue after errors are reported for a template.") end examples <<-'EOT' Validate the template 'template.epp' in module 'mymodule': $ puppet epp validate mymodule/template.epp Validate two arbitrary template files: $ puppet epp validate mymodule/template1.epp yourmodule/something.epp Validate a template somewhere in the file system: $ puppet epp validate /tmp/testing/template1.epp Validate a template against a file relative to the current directory: $ puppet epp validate template1.epp $ puppet epp validate ./template1.epp Validate from STDIN: $ cat template.epp | puppet epp validate Continue on error to see errors for all templates: $ puppet epp validate mymodule/template1.epp mymodule/template2.epp --continue_on_error EOT when_invoked do |*args| options = args.pop # pass a dummy node, as facts are not needed for validation options[:node] = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {})) compiler = create_compiler(options) status = true # no validation error yet files = args if files.empty? if !STDIN.tty? tmp = validate_template_string(STDIN.read) status &&= tmp else # This is not an error since a validate of all files in an empty # directory should not be treated as a failed validation. Puppet.notice _("No template specified. No action taken") end end missing_files = [] files.each do |file| break if !status && !options[:continue_on_error] template_file = effective_template(file, compiler.environment) if template_file tmp = validate_template(template_file) status &&= tmp else missing_files << file end end if !missing_files.empty? raise Puppet::Error, _("One or more file(s) specified did not exist:\n%{missing_files_list}") % { missing_files_list: missing_files.map { |f| " #{f}" }.join("\n") } else # Exit with 1 if there were errors raise Puppet::Error, _("Errors while validating epp") unless status end end end action(:dump) do summary _("Outputs a dump of the internal template parse tree for debugging") arguments "[--format <old|pn|json>] [--pretty] { -e <source> | [<templates> ...] } " returns _("A dump of the resulting AST model unless there are syntax or validation errors.") description <<-'EOT' The dump action parses and validates the EPP syntax and dumps the resulting AST model in a human readable (but not necessarily an easy to understand) format. The output format can be controlled using the --format <old|pn|json> where: * 'old' is the default, but now deprecated format which is not API. * 'pn' is the Puppet Extended S-Expression Notation. * 'json' outputs the same graph as 'pn' but with JSON syntax. The output will be "pretty printed" when the option --pretty is given together with --format 'pn' or 'json'. This option has no effect on the 'old' format. The command accepts one or more templates (.epp) files, or an -e followed by the template source text. The given templates can be paths to template files, or references to templates in modules when given on the form <modulename>/<template-name>.epp. If no arguments are given, the stdin is read (unless it is attached to a terminal) If multiple templates are given, they are separated with a header indicating the name of the template. This can be suppressed with the option --no-header. The option --[no-]header has no effect when a single template is dumped. When debugging the epp parser itself, it may be useful to suppress the validation step with the `--no-validate` option to observe what the parser produced from the given source. This command ignores the --render-as setting/option. EOT option("--e " + _("<source>")) do default_to { nil } summary _("Dump one epp source expression given on the command line.") end option("--[no-]validate") do summary _("Whether or not to validate the parsed result, if no-validate only syntax errors are reported.") end option('--format ' + _('<old, pn, or json>')) do summary _("Get result in 'old' (deprecated format), 'pn' (new format), or 'json' (new format in JSON).") end option('--pretty') do summary _('Pretty print output. Only applicable together with --format pn or json') end option("--[no-]header") do summary _("Whether or not to show a file name header between files.") end when_invoked do |*args| require_relative '../../puppet/pops' options = args.pop # pass a dummy node, as facts are not needed for dump options[:node] = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {})) options[:header] = options[:header].nil? ? true : options[:header] options[:validate] = options[:validate].nil? ? true : options[:validate] compiler = create_compiler(options) # Print to a buffer since the face needs to return the resulting string # and the face API is "all or nothing" # buffer = StringIO.new if options[:e] buffer.print dump_parse(options[:e], 'command-line-string', options, false) elsif args.empty? if !STDIN.tty? buffer.print dump_parse(STDIN.read, 'stdin', options, false) else raise Puppet::Error, _("No input to parse given on command line or stdin") end else templates, missing_files = args.each_with_object([[], []]) do |file, memo| template_file = effective_template(file, compiler.environment) if template_file.nil? memo[1] << file else memo[0] << template_file end end show_filename = templates.count > 1 templates.each do |file| buffer.print dump_parse(Puppet::FileSystem.read(file, :encoding => 'utf-8'), file, options, show_filename) end unless missing_files.empty? raise Puppet::Error, _("One or more file(s) specified did not exist:\n%{missing_files_list}") % { missing_files_list: missing_files.collect { |f| " #{f}" }.join("\n") } end end buffer.string end end action(:render) do summary _("Renders an epp template as text") arguments "-e <source> | [<templates> ...] " returns _("A rendered result of one or more given templates.") description <<-'EOT' This action renders one or more EPP templates. The command accepts one or more templates (.epp files), given the same way as templates are given to the puppet `epp` function (a full path, or a relative reference on the form '<modulename>/<template-name>.epp'), or as a relative path.args In case the given path matches both a modulename/template and a file, the template from the module is used. An inline_epp equivalent can also be performed by giving the template after an -e, or by piping the EPP source text to the command. Values to the template can be defined using the Puppet Language on the command line with `--values` or in a .pp or .yaml file referenced with `--values_file`. If specifying both the result is merged with --values having higher precedence. The --values option allows a Puppet Language sequence of expressions to be defined on the command line the same way as it may be given in a .pp file referenced with `--values_file`. It may set variable values (that become available in the template), and must produce either `undef` or a `Hash` of values (the hash may be empty). Producing `undef` simulates that the template is called without an arguments hash and thus only references variables in its outer scope. When a hash is given, a template is limited to seeing only the global scope. It is thus possible to simulate the different types of calls to the `epp` and `inline_epp` functions, with or without a given hash. Note that if variables are given, they are always available in this simulation - to test that the template only references variables given as arguments, produce a hash in --values or the --values_file, do not specify any variables that are not global, and turn on --strict_variables setting. If multiple templates are given, the same set of values are given to each template. If both --values and --value_file are used, the --values are merged on top of those given in the file. When multiple templates are rendered, a separating header is output between the templates showing the name of the template before the output. The header output can be turned off with `--no-header`. This also concatenates the template results without any added newline separators. Facts from the node where the command is being run are used by default.args Facts can be obtained for other nodes if they have called in, and reported their facts by using the `--node <nodename>` flag. Overriding node facts as well as additional facts can be given in a .yaml or .json file and referencing it with the --facts option. (Values can be obtained in yaml format directly from `facter`, or from puppet for a given node). Note that it is not possible to simulate the reserved variable name `$facts` in any other way. Note that it is not possible to set variables using the Puppet Language that have the same names as facts as this result in an error; "attempt to redefine a variable" since facts are set first. Exits with 0 if there were no validation errors. On errors, no rendered output is produced for that template file. When designing EPP templates, it is strongly recommended to define all template arguments in the template, and to give them in a hash when calling `epp` or `inline_epp` and to use as few global variables as possible, preferably only the $facts hash. This makes templates more free standing and are easier to reuse, and to test. EOT examples <<-'EOT' Render the template in module 'mymodule' called 'mytemplate.epp', and give it two arguments `a` and `b`: $ puppet epp render mymodule/mytemplate.epp --values '{a => 10, b => 20}' Render a template using an absolute path: $ puppet epp render /tmp/testing/mytemplate.epp --values '{a => 10, b => 20}' Render a template with data from a .pp file: $ puppet epp render /tmp/testing/mytemplate.epp --values_file mydata.pp Render a template with data from a .pp file and override one value on the command line: $ puppet epp render /tmp/testing/mytemplate.epp --values_file mydata.pp --values '{a=>10}' Render from STDIN: $ cat template.epp | puppet epp render --values '{a => 10, b => 20}' Set variables in a .pp file and render a template that uses variable references: # data.pp file $greeted = 'a global var' undef $ puppet epp render -e 'hello <%= $greeted %>' --values_file data.pp Render a template that outputs a fact: $ facter --yaml > data.yaml $ puppet epp render -e '<% $facts[osfamily] %>' --facts data.yaml EOT option("--node " + _("<node_name>")) do summary _("The name of the node for which facts are obtained. Defaults to facts for the local node.") end option("--e " + _("<source>")) do default_to { nil } summary _("Render one inline epp template given on the command line.") end option("--values " + _("<values_hash>")) do summary _("A Hash in Puppet DSL form given as arguments to the template being rendered.") end option("--values_file " + _("<pp_or_yaml_file>")) do summary _("A .pp or .yaml file that is processed to produce a hash of values for the template.") end option("--facts " + _("<facts_file>")) do summary _("A .yaml or .json file containing a hash of facts made available in $facts and $trusted") end option("--[no-]header") do summary _("Whether or not to show a file name header between rendered results.") end when_invoked do |*args| options = args.pop options[:header] = options[:header].nil? ? true : options[:header] compiler = create_compiler(options) compiler.with_context_overrides('For rendering epp') do # Print to a buffer since the face needs to return the resulting string # and the face API is "all or nothing" # buffer = StringIO.new status = true if options[:e] buffer.print render_inline(options[:e], compiler, options) elsif args.empty? if !STDIN.tty? buffer.print render_inline(STDIN.read, compiler, options) else raise Puppet::Error, _("No input to process given on command line or stdin") end else show_filename = args.count > 1 file_nbr = 0 args.each do |file| buffer.print render_file(file, compiler, options, show_filename, file_nbr += 1) rescue Puppet::ParseError => detail Puppet.err(detail.message) status = false end end raise Puppet::Error, _("error while rendering epp") unless status buffer.string end end end def dump_parse(source, filename, options, show_filename = true) output = ''.dup evaluating_parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new begin if options[:validate] parse_result = evaluating_parser.parse_string(source, filename) else # side step the assert_and_report step parse_result = evaluating_parser.parser.parse_string(source) end if show_filename && options[:header] output << "--- #{filename}\n" end fmt = options[:format] if fmt.nil? || fmt == 'old' output << Puppet::Pops::Model::ModelTreeDumper.new.dump(parse_result) << "\n" else require_relative '../../puppet/pops/pn' pn = Puppet::Pops::Model::PNTransformer.transform(parse_result) case fmt when 'json' options[:pretty] ? JSON.pretty_unparse(pn.to_data) : JSON.dump(pn.to_data) else pn.format(options[:pretty] ? Puppet::Pops::PN::Indent.new(' ') : nil, output) end end rescue Puppet::ParseError => detail if show_filename Puppet.err("--- #{filename}") end Puppet.err(detail.message) "" end end def get_values(compiler, options) template_values = nil values_file = options[:values_file] if values_file begin case values_file when /\.yaml$/ template_values = Puppet::Util::Yaml.safe_load_file(values_file, [Symbol]) when /\.pp$/ evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new template_values = evaluating_parser.evaluate_file(compiler.topscope, values_file) else Puppet.err(_("Only .yaml or .pp can be used as a --values_file")) end rescue => e Puppet.err(_("Could not load --values_file %{error}") % { error: e.message }) end unless template_values.nil? || template_values.is_a?(Hash) Puppet.err(_("--values_file option must evaluate to a Hash or undef/nil, got: '%{template_class}'") % { template_class: template_values.class }) end end values = options[:values] if values evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new result = evaluating_parser.evaluate_string(compiler.topscope, values, 'values-hash') case result when nil template_values when Hash template_values.nil? ? result : template_values.merge(result) else Puppet.err(_("--values option must evaluate to a Hash or undef, got: '%{values_class}'") % { values_class: result.class }) end else template_values end end def render_inline(epp_source, compiler, options) template_args = get_values(compiler, options) result = Puppet::Pops::Evaluator::EppEvaluator.inline_epp(compiler.topscope, epp_source, template_args) if result.instance_of?(Puppet::Pops::Types::PSensitiveType::Sensitive) result.unwrap else result end end def render_file(epp_template_name, compiler, options, show_filename, file_nbr) template_args = get_values(compiler, options) output = ''.dup begin if show_filename && options[:header] output << "\n" unless file_nbr == 1 output << "--- #{epp_template_name}\n" end # Change to an absolute file only if reference is to a an existing file. Note that an absolute file must be used # or the template must be found on the module path when calling the epp evaluator. template_file = Puppet::Parser::Files.find_template(epp_template_name, compiler.environment) if template_file.nil? && Puppet::FileSystem.exist?(epp_template_name) epp_template_name = File.expand_path(epp_template_name) end result = Puppet::Pops::Evaluator::EppEvaluator.epp(compiler.topscope, epp_template_name, compiler.environment, template_args) if result.instance_of?(Puppet::Pops::Types::PSensitiveType::Sensitive) output << result.unwrap else output << result end rescue Puppet::ParseError => detail Puppet.err("--- #{epp_template_name}") if show_filename raise detail end output end # @api private def validate_template(template) parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new() parser.parse_file(template) true rescue => detail Puppet.log_exception(detail) false end # @api private def validate_template_string(source) parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new() parser.parse_string(source, '<stdin>') true rescue => detail Puppet.log_exception(detail) false end # @api private def create_compiler(options) if options[:node] node = options[:node] else node = Puppet[:node_name_value] # If we want to lookup the node we are currently on # we must returning these settings to their default values Puppet.settings[:facts_terminus] = 'facter' Puppet.settings[:node_cache_terminus] = nil end unless node.is_a?(Puppet::Node) node = Puppet::Node.indirection.find(node) # Found node must be given the environment to use in some cases, use the one configured # or given on the command line node.environment = Puppet[:environment] end fact_file = options[:facts] if fact_file if fact_file.is_a?(Hash) # when used via the Face API given_facts = fact_file elsif fact_file.end_with?("json") given_facts = Puppet::Util::Json.load(Puppet::FileSystem.read(fact_file, :encoding => 'utf-8')) else given_facts = Puppet::Util::Yaml.safe_load_file(fact_file) end unless given_facts.instance_of?(Hash) raise _("Incorrect formatted data in %{fact_file} given via the --facts flag") % { fact_file: fact_file } end # It is difficult to add to or modify the set of facts once the node is created # as changes does not show up in parameters. Rather than manually patching up # a node and risking future regressions, a new node is created from scratch node = Puppet::Node.new(node.name, :facts => Puppet::Node::Facts.new("facts", node.facts.values.merge(given_facts))) node.environment = Puppet[:environment] node.merge(node.facts.values) end compiler = Puppet::Parser::Compiler.new(node) # configure compiler with facts and node related data # Set all global variables from facts compiler.send(:set_node_parameters) # pretend that the main class (named '') has been evaluated # since it is otherwise not possible to resolve top scope variables # using '::' when rendering. (There is no harm doing this for the other actions) # compiler.topscope.class_set('', compiler.topscope) compiler end # Produces the effective template file from a module/template or file reference # @api private def effective_template(file, env) template_file = Puppet::Parser::Files.find_template(file, env) if !template_file.nil? template_file elsif Puppet::FileSystem.exist?(file) file else nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/help.rb
lib/puppet/face/help.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/application/face_base' require_relative '../../puppet/util/constant_inflector' require 'pathname' require 'erb' Puppet::Face.define(:help, '0.0.1') do copyright "Puppet Inc.", 2011 license _("Apache 2 license; see COPYING") summary _("Display Puppet help.") action(:help) do summary _("Display help about Puppet subcommands and their actions.") arguments _("[<subcommand>] [<action>]") returns _("Short help text for the specified subcommand or action.") examples _(<<-'EOT') Get help for an action: $ puppet help EOT option "--version " + _("VERSION") do summary _("The version of the subcommand for which to show help.") end option "--ronn" do summary _("Whether to render the help text in ronn format.") default_to { false } end default when_invoked do |*args| options = args.pop unless options[:ronn] if default_case?(args) || help_for_help?(args) return erb('global.erb').result(binding) end end if args.length > 2 # TRANSLATORS 'puppet help' is a command line and should not be translated raise ArgumentError, _("The 'puppet help' command takes two (optional) arguments: a subcommand and an action") end version = :current if options.has_key? :version if options[:version].to_s !~ /^current$/i version = options[:version] elsif args.length == 0 raise ArgumentError, _("Supplying a '--version' only makes sense when a Faces subcommand is given") # TRANSLATORS '--version' is a command line option and should not be translated end end facename, actionname = args if legacy_applications.include? facename if actionname raise ArgumentError, _("The legacy subcommand '%{sub_command}' does not support supplying an action") % { sub_command: facename } end # legacy apps already emit ronn output return render_application_help(facename) elsif options[:ronn] render_face_man(facename || :help) # Calling `puppet help <app> --ronn` normally calls this action with # <app> as the first argument in the `args` array. However, if <app> # happens to match the name of an action, like `puppet help help # --ronn`, then face_base "eats" the argument and `args` will be # empty. Rather than force users to type `puppet help help help # --ronn`, default the facename to `:help` else render_face_help(facename, actionname, version) end end end def default_case?(args) args.empty? end def help_for_help?(args) args.length == 1 && args.first == 'help' end def render_face_man(facename) # set 'face' as it's used in the erb processing. face = Puppet::Face[facename.to_sym, :current] # avoid unused variable warning _face = face erb('man.erb').result(binding) end def render_application_help(applicationname) Puppet::Application[applicationname].help rescue StandardError, LoadError => detail message = [] message << _('Could not load help for the application %{application_name}.') % { application_name: applicationname } message << _('Please check the error logs for more information.') message << '' message << _('Detail: "%{detail}"') % { detail: detail.message } fail ArgumentError, message.join("\n"), detail.backtrace end def render_face_help(facename, actionname, version) face, action = load_face_help(facename, actionname, version) template_for(face, action).result(binding) rescue StandardError, LoadError => detail message = [] message << _('Could not load help for the face %{face_name}.') % { face_name: facename } message << _('Please check the error logs for more information.') message << '' message << _('Detail: "%{detail}"') % { detail: detail.message } fail ArgumentError, message.join("\n"), detail.backtrace end def load_face_help(facename, actionname, version) face = Puppet::Face[facename.to_sym, version] if actionname action = face.get_action(actionname.to_sym) unless action fail ArgumentError, _("Unable to load action %{actionname} from %{face}") % { actionname: actionname, face: face } end end [face, action] end def template_for(face, action) if action.nil? erb('face.erb') else erb('action.erb') end end def erb(name) template = (Pathname(__FILE__).dirname + "help" + name) erb = Puppet::Util.create_erb(template.read) erb.filename = template.to_s erb end # Return a list of applications that are not simply just stubs for Faces. def legacy_applications Puppet::Application.available_application_names.reject do |appname| is_face_app?(appname) or exclude_from_docs?(appname) end.sort end def generate_summary(appname) if is_face_app?(appname) begin face = Puppet::Face[appname, :current] # Add deprecation message to summary if the face is deprecated summary = face.deprecated? ? face.summary + ' ' + _("(Deprecated)") : face.summary [appname, summary, ' '] rescue StandardError, LoadError error_message = _("!%{sub_command}! Subcommand unavailable due to error.") % { sub_command: appname } error_message += ' ' + _("Check error logs.") [error_message, '', ' '] end else begin summary = Puppet::Application[appname].summary if summary.empty? summary = horribly_extract_summary_from(appname) end [appname, summary, ' '] rescue StandardError, LoadError error_message = _("!%{sub_command}! Subcommand unavailable due to error.") % { sub_command: appname } error_message += ' ' + _("Check error logs.") [error_message, '', ' '] end end end # Return a list of all applications (both legacy and Face applications), along with a summary # of their functionality. # @return [Array] An Array of Arrays. The outer array contains one entry per application; each # element in the outer array is a pair whose first element is a String containing the application # name, and whose second element is a String containing the summary for that application. def all_application_summaries available_application_names_special_sort().inject([]) do |result, appname| next result if exclude_from_docs?(appname) if appname == COMMON || appname == SPECIALIZED || appname == BLANK result << appname else result << generate_summary(appname) end end end COMMON = 'Common:' SPECIALIZED = 'Specialized:' BLANK = "\n" COMMON_APPS = %w[apply agent config help lookup module resource] def available_application_names_special_sort full_list = Puppet::Application.available_application_names a_list = full_list & COMMON_APPS a_list = a_list.sort also_ran = full_list - a_list also_ran = also_ran.sort [[COMMON], a_list, [BLANK], [SPECIALIZED], also_ran].flatten(1) end def common_app_summaries COMMON_APPS.map do |appname| generate_summary(appname) end end def specialized_app_summaries specialized_apps = Puppet::Application.available_application_names - COMMON_APPS specialized_apps.filter_map do |appname| generate_summary(appname) unless exclude_from_docs?(appname) end end def horribly_extract_summary_from(appname) help = Puppet::Application[appname].help.split("\n") # Now we find the line with our summary, extract it, and return it. This # depends on the implementation coincidence of how our pages are # formatted. If we can't match the pattern we expect we return the empty # string to ensure we don't blow up in the summary. --daniel 2011-04-11 while line = help.shift # rubocop:disable Lint/AssignmentInCondition md = /^puppet-#{appname}\([^)]+\) -- (.*)$/.match(line) if md return md[1] end end '' end # This should absolutely be a private method, but for some reason it appears # that you can't use the 'private' keyword inside of a Face definition. # See #14205. # private :horribly_extract_summary_from def exclude_from_docs?(appname) %w[face_base indirection_base report status].include? appname end # This should absolutely be a private method, but for some reason it appears # that you can't use the 'private' keyword inside of a Face definition. # See #14205. # private :exclude_from_docs? def is_face_app?(appname) clazz = Puppet::Application.find(appname) clazz.ancestors.include?(Puppet::Application::FaceBase) end # This should probably be a private method, but for some reason it appears # that you can't use the 'private' keyword inside of a Face definition. # See #14205. # private :is_face_app? end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/facts.rb
lib/puppet/face/facts.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/face' require_relative '../../puppet/node/facts' Puppet::Indirector::Face.define(:facts, '0.0.1') do copyright "Puppet Inc.", 2011 license _("Apache 2 license; see COPYING") summary _("Retrieve and store facts.") description <<-'EOT' This subcommand manages facts, which are collections of normalized system information used by Puppet. It can read facts directly from the local system (with the default `facter` terminus). EOT find = get_action(:find) find.summary _("Retrieve a node's facts.") find.arguments _("[<node_certname>]") find.returns <<-'EOT' A hash containing some metadata and (under the "values" key) the set of facts for the requested node. When used from the Ruby API: A Puppet::Node::Facts object. RENDERING ISSUES: Facts cannot currently be rendered as a string; use yaml or json. EOT find.notes <<-'EOT' When using the `facter` terminus, the host argument is ignored. EOT find.examples <<-'EOT' Get facts from the local system: $ puppet facts find EOT deactivate_action(:destroy) deactivate_action(:search) action(:upload) do summary _("Upload local facts to the puppet master.") description <<-'EOT' Reads facts from the local system using the `facter` terminus, then saves the returned facts using the rest terminus. EOT returns "Nothing." notes <<-'EOT' This action requires that the Puppet Server's `auth.conf` file allow `PUT` or `save` access to the `/puppet/v3/facts` API endpoint. For details on configuring Puppet Server's `auth.conf`, see: <https://puppet.com/docs/puppetserver/latest/config_file_auth.html> EOT examples <<-'EOT' Upload facts: $ puppet facts upload EOT render_as :json when_invoked do |_options| # Use `agent` sections settings for certificates, Puppet Server URL, # etc. instead of `user` section settings. Puppet.settings.preferred_run_mode = :agent Puppet::Node::Facts.indirection.terminus_class = :facter facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) unless Puppet[:node_name_fact].empty? Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]] facts.name = Puppet[:node_name_value] end client = Puppet.runtime[:http] session = client.create_session puppet = session.route_to(:puppet) Puppet.notice(_("Uploading facts for '%{node}' to '%{server}'") % { node: Puppet[:node_name_value], server: puppet.url.hostname }) puppet.put_facts(Puppet[:node_name_value], facts: facts, environment: Puppet.lookup(:current_environment).name.to_s) nil end end action(:show) do summary _("Retrieve current node's facts.") arguments _("[<facts>]") description <<-'EOT' Reads facts from the local system using `facter` terminus. A query can be provided to retrieve just a specific fact or a set of facts. EOT returns "The output of facter with added puppet specific facts." notes <<-'EOT' EOT examples <<-'EOT' retrieve facts: $ puppet facts show os EOT default true option("--config-file " + _("<path>")) do default_to { nil } summary _("The location of the config file for Facter.") end option("--custom-dir " + _("<path>")) do default_to { nil } summary _("The path to a directory that contains custom facts.") end option("--external-dir " + _("<path>")) do default_to { nil } summary _("The path to a directory that contains external facts.") end option("--no-block") do summary _("Disable fact blocking mechanism.") end option("--no-cache") do summary _("Disable fact caching mechanism.") end option("--show-legacy") do summary _("Show legacy facts when querying all facts.") end option("--value-only") do summary _("Show only the value when the action is called with a single query") end option("--timing") do summary _("Show how much time it took to resolve each fact.") end when_invoked do |*args| options = args.pop Puppet.settings.preferred_run_mode = :agent Puppet::Node::Facts.indirection.terminus_class = :facter if options[:value_only] && !args.count.eql?(1) options[:value_only] = nil Puppet.warning("Incorrect use of --value-only argument; it can only be used when querying for a single fact!") end options[:user_query] = args options[:resolve_options] = true result = Puppet::Node::Facts.indirection.find(Puppet.settings[:certname], options) if options[:value_only] result.values.values.first else result.values end end when_rendering :console do |result| # VALID_TYPES = [Integer, Float, TrueClass, FalseClass, NilClass, Symbol, String, Array, Hash].freeze # from https://github.com/puppetlabs/facter/blob/4.0.49/lib/facter/custom_facts/util/normalization.rb#L8 case result when Array, Hash # JSON < 2.8.0 would pretty print empty arrays and hashes with newlines # Maintain that behavior for our users for now if result.is_a?(Array) && result.empty? "[\n\n]" elsif result.is_a?(Hash) && result.empty? "{\n}" else Puppet::Util::Json.dump(result, :pretty => true) end else # one of VALID_TYPES above result end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/config.rb
lib/puppet/face/config.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/settings/ini_file' Puppet::Face.define(:config, '0.0.1') do extend Puppet::Util::Colors copyright "Puppet Inc.", 2011 license _("Apache 2 license; see COPYING") summary _("Interact with Puppet's settings.") description "This subcommand can inspect and modify settings from Puppet's 'puppet.conf' configuration file. For documentation about individual settings, see https://puppet.com/docs/puppet/latest/configuration.html." DEFAULT_SECTION_MARKER = Object.new DEFAULT_SECTION = "main" option "--section " + _("SECTION_NAME") do default_to { DEFAULT_SECTION_MARKER } # Sentinel object for default detection during commands summary _("The section of the configuration file to interact with.") description <<-EOT The section of the puppet.conf configuration file to interact with. The three most commonly used sections are 'main', 'server', and 'agent'. 'Main' is the default, and is used by all Puppet applications. Other sections can override 'main' values for specific applications --- the 'server' section affects Puppet Server, and the 'agent' section affects puppet agent. Less commonly used is the 'user' section, which affects puppet apply. Any other section will be treated as the name of a legacy environment (a deprecated feature), and can only include the 'manifest' and 'modulepath' settings. EOT end action(:print) do summary _("Examine Puppet's current settings.") arguments _("all | <setting> [<setting> ...]") description <<-'EOT' Prints the value of a single setting or a list of settings. This action is a replacement interface to the information available with `puppet <subcommand> --configprint`. EOT notes <<-'EOT' By default, this action reads the general configuration in the 'main' section. Use the '--section' and '--environment' flags to examine other configuration domains. EOT examples <<-'EOT' Get puppet's runfile directory: $ puppet config print rundir Get a list of important directories from the server's config: $ puppet config print all --section server | grep -E "(path|dir)" EOT when_invoked do |*args| options = args.pop @default_section = false if options[:section] == DEFAULT_SECTION_MARKER options[:section] = DEFAULT_SECTION @default_section = true end if Puppet::Util::Log.sendlevel?(:info) warn_default_section(options[:section]) if @default_section report_section_and_environment(options[:section], Puppet.settings[:environment]) end names = if args.empty? || args == ['all'] :all else args end Puppet.settings.stringify_settings(options[:section], names) end when_rendering :console do |to_be_rendered| output = ''.dup if to_be_rendered.keys.length > 1 to_be_rendered.keys.sort.each do |setting| output << "#{setting} = #{to_be_rendered[setting]}\n" end else output << "#{to_be_rendered.to_a[0].last}\n" end output end end def warn_default_section(section_name) messages = [] messages << _("No section specified; defaulting to '%{section_name}'.") % { section_name: section_name } # TRANSLATORS '--section' is a command line option and should not be translated messages << _("Set the config section by using the `--section` flag.") # TRANSLATORS `puppet config --section user print foo` is a command line example and should not be translated messages << _("For example, `puppet config --section user print foo`.") messages << _("For more information, see https://puppet.com/docs/puppet/latest/configuration.html") Puppet.warning(messages.join("\n")) end def report_section_and_environment(section_name, environment_name) $stderr.puts colorize(:hyellow, _("Resolving settings from section '%{section_name}' in environment '%{environment_name}'") % { section_name: section_name, environment_name: environment_name }) end action(:set) do summary _("Set Puppet's settings.") arguments _("[setting_name] [setting_value]") description <<-'EOT' Updates values in the `puppet.conf` configuration file. EOT notes <<-'EOT' By default, this action manipulates the configuration in the 'main' section. Use the '--section' flag to manipulate other configuration domains. EOT examples <<-'EOT' Set puppet's runfile directory: $ puppet config set rundir /var/run/puppetlabs Set the vardir for only the agent: $ puppet config set vardir /opt/puppetlabs/puppet/cache --section agent EOT when_invoked do |name, value, options| @default_section = false if options[:section] == DEFAULT_SECTION_MARKER options[:section] = DEFAULT_SECTION @default_section = true end if name == 'environment' && options[:section] == 'main' Puppet.warning _(<<~EOM).chomp The environment should be set in either the `[user]`, `[agent]`, or `[server]` section. Variables set in the `[agent]` section are used when running `puppet agent`. Variables set in the `[user]` section are used when running various other puppet subcommands, like `puppet apply` and `puppet module`; these require the defined environment directory to exist locally. Set the config section by using the `--section` flag. For example, `puppet config --section user set environment foo`. For more information, see https://puppet.com/docs/puppet/latest/configuration.html#environment EOM end if Puppet::Util::Log.sendlevel?(:info) report_section_and_environment(options[:section], Puppet.settings[:environment]) end # only validate settings we recognize setting = Puppet.settings.setting(name.to_sym) if setting # set the value, which will call `on_*_and_write` hooks, if any Puppet.settings[setting.name] = value # read the value to trigger interpolation and munge validation logic Puppet.settings[setting.name] end path = Puppet::FileSystem.pathname(Puppet.settings.which_configuration_file) Puppet::FileSystem.touch(path) Puppet::FileSystem.open(path, nil, 'r+:UTF-8') do |file| Puppet::Settings::IniFile.update(file) do |config| if options[:section] == "master" # delete requested master section if it exists, # as server section should be used setting_string = config.delete("master", name) if setting_string if Puppet::Util::Log.sendlevel?(:info) report_section_and_environment(options[:section], Puppet.settings[:environment]) end puts(_("Deleted setting from '%{section_name}': '%{setting_string}', and adding it to 'server' section") % { section_name: options[:section], name: name, setting_string: setting_string.strip }) end # add the setting to the to server section instead of master section config.set("server", name, value) else config.set(options[:section], name, value) end end end nil end end action(:delete) do summary _("Delete a Puppet setting.") arguments _("<setting>") # TRANSLATORS 'main' is a specific section name and should not be translated description "Deletes a setting from the specified section. (The default is the section 'main')." notes <<-'EOT' By default, this action deletes the configuration setting from the 'main' configuration domain. Use the '--section' flags to delete settings from other configuration domains. EOT examples <<-'EOT' Delete the setting 'setting_name' from the 'main' configuration domain: $ puppet config delete setting_name Delete the setting 'setting_name' from the 'server' configuration domain: $ puppet config delete setting_name --section server EOT when_invoked do |name, options| @default_section = false if options[:section] == DEFAULT_SECTION_MARKER options[:section] = DEFAULT_SECTION @default_section = true end path = Puppet::FileSystem.pathname(Puppet.settings.which_configuration_file) if Puppet::FileSystem.exist?(path) Puppet::FileSystem.open(path, nil, 'r+:UTF-8') do |file| Puppet::Settings::IniFile.update(file) do |config| # delete from both master section and server section if options[:section] == "master" || options[:section] == "server" master_setting_string = config.delete("master", name) puts(_("Deleted setting from '%{section_name}': '%{setting_string}'") % { section_name: 'master', name: name, setting_string: master_setting_string.strip[/[^=]+/] }) if master_setting_string server_setting_string = config.delete("server", name) puts(_("Deleted setting from '%{section_name}': '%{setting_string}'") % { section_name: 'server', name: name, setting_string: server_setting_string.strip[/[^=]+/] }) if server_setting_string else setting_string = config.delete(options[:section], name) if setting_string if Puppet::Util::Log.sendlevel?(:info) report_section_and_environment(options[:section], Puppet.settings[:environment]) end puts(_("Deleted setting from '%{section_name}': '%{setting_string}'") % { section_name: options[:section], name: name, setting_string: setting_string.strip }) else Puppet.warning(_("No setting found in configuration file for section '%{section_name}' setting name '%{name}'") % { section_name: options[:section], name: name }) end end end end else # TRANSLATORS the 'puppet.conf' is a specific file and should not be translated Puppet.warning(_("The puppet.conf file does not exist %{puppet_conf}") % { puppet_conf: path }) end nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/module.rb
lib/puppet/face/module.rb
# frozen_string_literal: true require_relative '../../puppet/face' require_relative '../../puppet/module_tool' require_relative '../../puppet/util/colors' Puppet::Face.define(:module, '1.0.0') do extend Puppet::Util::Colors copyright "Puppet Inc.", 2012 license _("Apache 2 license; see COPYING") summary _("Creates, installs and searches for modules on the Puppet Forge.") description <<-EOT This subcommand can find, install, and manage modules from the Puppet Forge, a repository of user-contributed Puppet code. It can also generate empty modules, and prepare locally developed modules for release on the Forge. EOT display_global_options "environment", "modulepath" end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/catalog/select.rb
lib/puppet/face/catalog/select.rb
# frozen_string_literal: true # Select and show a list of resources of a given type. Puppet::Face.define(:catalog, '0.0.1') do action :select do summary _("Retrieve a catalog and filter it for resources of a given type.") arguments _("<host> <resource_type>") returns _(<<-'EOT') A list of resource references ("Type[title]"). When used from the API, returns an array of Puppet::Resource objects excised from a catalog. EOT description <<-'EOT' Retrieves a catalog for the specified host, then searches it for all resources of the requested type. EOT notes <<-'NOTES' By default, this action will retrieve a catalog from Puppet's compiler subsystem; you must call the action with `--terminus rest` if you wish to retrieve a catalog from the puppet master. FORMATTING ISSUES: This action cannot currently render useful yaml; instead, it returns an entire catalog. Use json instead. NOTES examples <<-'EOT' Ask the puppet master for a list of managed file resources for a node: $ puppet catalog select --terminus rest somenode.magpie.lan file EOT when_invoked do |host, type, _options| # REVISIT: Eventually, type should have a default value that triggers # the non-specific behaviour. For now, though, this will do. # --daniel 2011-05-03 catalog = Puppet::Resource::Catalog.indirection.find(host) if type == '*' catalog.resources else type = type.downcase catalog.resources.reject { |res| res.type.downcase != type } end end when_rendering :console do |value| if value.nil? then _("no matching resources found") else value.map(&:to_s).join("\n") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/node/clean.rb
lib/puppet/face/node/clean.rb
# frozen_string_literal: true Puppet::Face.define(:node, '0.0.1') do action(:clean) do summary _("Clean up signed certs, cached facts, node objects, and reports for a node stored by the puppetmaster") arguments _("<host1> [<host2> ...]") description <<-'EOT' Cleans up the following information a puppet master knows about a node: <Signed certificates> - ($vardir/ssl/ca/signed/node.domain.pem) <Cached facts> - ($vardir/yaml/facts/node.domain.yaml) <Cached node objects> - ($vardir/yaml/node/node.domain.yaml) <Reports> - ($vardir/reports/node.domain) NOTE: this action now cleans up certs via Puppet Server's CA API. A running server is required for certs to be cleaned. EOT when_invoked do |*args| nodes = args[0..-2] options = args.last raise _("At least one node should be passed") if nodes.empty? || nodes == options # This seems really bad; run_mode should be set as part of a class # definition, and should not be modifiable beyond that. This is one of # the only places left in the code that tries to manipulate it. Other # parts of code that handle certificates behave differently if the # run_mode is server. Those other behaviors are needed for cleaning the # certificates correctly. Puppet.settings.preferred_run_mode = "server" Puppet::Node::Facts.indirection.terminus_class = :yaml Puppet::Node::Facts.indirection.cache_class = :yaml Puppet::Node.indirection.terminus_class = :yaml Puppet::Node.indirection.cache_class = :yaml nodes.each { |node| cleanup(node.downcase) } end end def cleanup(node) clean_cert(node) clean_cached_facts(node) clean_cached_node(node) clean_reports(node) end class LoggerIO def debug(message) Puppet.debug(message) end def warn(message) Puppet.warning(message) unless message =~ /cadir is currently configured to be inside/ end def err(message) Puppet.err(message) unless message =~ /^\s*Error:\s*/ end def inform(message) Puppet.notice(message) end end # clean signed cert for +host+ def clean_cert(node) if Puppet.features.puppetserver_ca? Puppetserver::Ca::Action::Clean.new(LoggerIO.new).run({ 'certnames' => [node] }) else Puppet.info _("Not managing %{node} certs as this host is not a CA") % { node: node } end end # clean facts for +host+ def clean_cached_facts(node) Puppet::Node::Facts.indirection.destroy(node) Puppet.info _("%{node}'s facts removed") % { node: node } end # clean cached node +host+ def clean_cached_node(node) Puppet::Node.indirection.destroy(node) Puppet.info _("%{node}'s cached node removed") % { node: node } end # clean node reports for +host+ def clean_reports(node) Puppet::Transaction::Report.indirection.destroy(node) Puppet.info _("%{node}'s reports removed") % { node: node } end def environment @environment ||= Puppet.lookup(:current_environment) end def type_is_ensurable(resource) if (type = Puppet::Type.type(resource.restype)) && type.validattr?(:ensure) return true else type = environment.known_resource_types.find_definition(resource.restype) return true if type && type.arguments.keys.include?('ensure') end false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/module/uninstall.rb
lib/puppet/face/module/uninstall.rb
# frozen_string_literal: true Puppet::Face.define(:module, '1.0.0') do action(:uninstall) do summary _("Uninstall a puppet module.") description <<-EOT Uninstalls a puppet module from the modulepath (or a specific target directory). Note: Module uninstall uses MD5 checksums, which are prohibited on FIPS enabled systems. EOT returns _("Hash of module objects representing uninstalled modules and related errors.") examples <<-'EOT' Uninstall a module: $ puppet module uninstall puppetlabs-ssh Removed /etc/puppetlabs/code/modules/ssh (v1.0.0) Uninstall a module from a specific directory: $ puppet module uninstall puppetlabs-ssh --modulepath /opt/puppetlabs/puppet/modules Removed /opt/puppetlabs/puppet/modules/ssh (v1.0.0) Uninstall a module from a specific environment: $ puppet module uninstall puppetlabs-ssh --environment development Removed /etc/puppetlabs/code/environments/development/modules/ssh (v1.0.0) Uninstall a specific version of a module: $ puppet module uninstall puppetlabs-ssh --version 2.0.0 Removed /etc/puppetlabs/code/modules/ssh (v2.0.0) EOT arguments _("<name>") option "--force", "-f" do summary _("Force uninstall of an installed module.") description <<-EOT Force the uninstall of an installed module even if there are local changes or the possibility of causing broken dependencies. EOT end option "--ignore-changes", "-c" do summary _("Ignore any local changes made. (Implied by --force.)") description <<-EOT Uninstall an installed module even if there are local changes to it. (Implied by --force.) EOT end option "--version=" do summary _("The version of the module to uninstall") description <<-EOT The version of the module to uninstall. When using this option, a module matching the specified version must be installed or else an error is raised. EOT end when_invoked do |name, options| name = name.tr('/', '-') Puppet::ModuleTool.set_option_defaults options message = if options[:version] module_version = colorize(:cyan, options[:version].sub(/^(?=\d)/, 'v')) _("Preparing to uninstall '%{name}' (%{module_version}) ...") % { name: name, module_version: module_version } else _("Preparing to uninstall '%{name}' ...") % { name: name } end Puppet.notice message Puppet::ModuleTool::Applications::Uninstaller.run(name, options) end when_rendering :console do |return_value| if return_value[:result] == :failure Puppet.err(return_value[:error][:multiline]) exit 1 else mod = return_value[:affected_modules].first message = if mod.version module_version = colorize(:cyan, mod.version.to_s.sub(/^(?=\d)/, 'v')) _("Removed '%{name}' (%{module_version}) from %{path}") % { name: return_value[:module_name], module_version: module_version, path: mod.modulepath } else _("Removed '%{name}' from %{path}") % { name: return_value[:module_name], path: mod.modulepath } end message end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/module/changes.rb
lib/puppet/face/module/changes.rb
# frozen_string_literal: true Puppet::Face.define(:module, '1.0.0') do action(:changes) do summary _("Show modified files of an installed module.") description <<-EOT Shows any files in a module that have been modified since it was installed. This action compares the files on disk to the md5 checksums included in the module's checksums.json or, if that is missing, in metadata.json. EOT returns _("Array of strings representing paths of modified files.") examples <<-EOT Show modified files of an installed module: $ puppet module changes /etc/puppetlabs/code/modules/vcsrepo/ warning: 1 files modified lib/puppet/provider/vcsrepo.rb EOT arguments _("<path>") when_invoked do |path, options| Puppet::ModuleTool.set_option_defaults options root_path = Puppet::ModuleTool.find_module_root(path) unless root_path raise ArgumentError, _("Could not find a valid module at %{path}") % { path: path.inspect } end Puppet::ModuleTool::Applications::Checksummer.run(root_path, options) end when_rendering :console do |return_value| if return_value.empty? Puppet.notice _("No modified files") else Puppet.warning _("%{count} files modified") % { count: return_value.size } end return_value.map(&:to_s).join("\n") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/module/upgrade.rb
lib/puppet/face/module/upgrade.rb
# encoding: UTF-8 # frozen_string_literal: true Puppet::Face.define(:module, '1.0.0') do action(:upgrade) do summary _("Upgrade a puppet module.") description <<-EOT Upgrades a puppet module. Note: Module upgrade uses MD5 checksums, which are prohibited on FIPS enabled systems. EOT returns "Hash" examples <<-EOT upgrade an installed module to the latest version $ puppet module upgrade puppetlabs-apache /etc/puppetlabs/puppet/modules └── puppetlabs-apache (v1.0.0 -> v2.4.0) upgrade an installed module to a specific version $ puppet module upgrade puppetlabs-apache --version 2.1.0 /etc/puppetlabs/puppet/modules └── puppetlabs-apache (v1.0.0 -> v2.1.0) upgrade an installed module for a specific environment $ puppet module upgrade puppetlabs-apache --environment test /etc/puppetlabs/code/environments/test/modules └── puppetlabs-apache (v1.0.0 -> v2.4.0) EOT arguments _("<name>") option "--force", "-f" do summary _("Force upgrade of an installed module. (Implies --ignore-dependencies.)") description <<-EOT Force the upgrade of an installed module even if there are local changes or the possibility of causing broken dependencies. Implies --ignore-dependencies. EOT end option "--ignore-dependencies" do summary _("Do not attempt to install dependencies. (Implied by --force.)") description <<-EOT Do not attempt to install dependencies. Implied by --force. EOT end option "--ignore-changes", "-c" do summary _("Ignore and overwrite any local changes made. (Implied by --force.)") description <<-EOT Upgrade an installed module even if there are local changes to it. (Implied by --force.) EOT end option "--version=" do summary _("The version of the module to upgrade to.") description <<-EOT The version of the module to upgrade to. EOT end when_invoked do |name, options| name = name.tr('/', '-') Puppet.notice _("Preparing to upgrade '%{name}' ...") % { name: name } Puppet::ModuleTool.set_option_defaults options Puppet::ModuleTool::Applications::Upgrader.new(name, options).run end when_rendering :console do |return_value| case return_value[:result] when :noop Puppet.notice return_value[:error][:multiline] exit 0 when :failure Puppet.err(return_value[:error][:multiline]) exit 1 else tree = Puppet::ModuleTool.build_tree(return_value[:graph], return_value[:base_dir]) "#{return_value[:base_dir]}\n" + Puppet::ModuleTool.format_tree(tree) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/module/list.rb
lib/puppet/face/module/list.rb
# encoding: UTF-8 # frozen_string_literal: true Puppet::Face.define(:module, '1.0.0') do action(:list) do summary _("List installed modules") description <<-HEREDOC Lists the installed puppet modules. By default, this action scans the modulepath from puppet.conf's `[main]` block; use the --modulepath option to change which directories are scanned. The output of this action includes information from the module's metadata, including version numbers and unmet module dependencies. HEREDOC returns _("hash of paths to module objects") option "--tree" do summary _("Whether to show dependencies as a tree view") end examples <<-'EOT' List installed modules: $ puppet module list /etc/puppetlabs/code/modules ├── bodepd-create_resources (v0.0.1) ├── puppetlabs-bacula (v0.0.2) ├── puppetlabs-mysql (v0.0.1) ├── puppetlabs-sqlite (v0.0.1) └── puppetlabs-stdlib (v2.2.1) /opt/puppetlabs/puppet/modules (no modules installed) List installed modules in a tree view: $ puppet module list --tree /etc/puppetlabs/code/modules └─┬ puppetlabs-bacula (v0.0.2) ├── puppetlabs-stdlib (v2.2.1) ├─┬ puppetlabs-mysql (v0.0.1) │ └── bodepd-create_resources (v0.0.1) └── puppetlabs-sqlite (v0.0.1) /opt/puppetlabs/puppet/modules (no modules installed) List installed modules from a specified environment: $ puppet module list --environment production /etc/puppetlabs/code/modules ├── bodepd-create_resources (v0.0.1) ├── puppetlabs-bacula (v0.0.2) ├── puppetlabs-mysql (v0.0.1) ├── puppetlabs-sqlite (v0.0.1) └── puppetlabs-stdlib (v2.2.1) /opt/puppetlabs/puppet/modules (no modules installed) List installed modules from a specified modulepath: $ puppet module list --modulepath /opt/puppetlabs/puppet/modules /opt/puppetlabs/puppet/modules (no modules installed) EOT when_invoked do |options| Puppet::ModuleTool.set_option_defaults(options) environment = options[:environment_instance] modules_by_path = environment.modules_by_path { :environment => environment, :modules_by_path => modules_by_path, :unmet_dependencies => unmet_dependencies(environment), } end when_rendering :console do |result, options| environment = result[:environment] modules_by_path = result[:modules_by_path] output = ''.dup warn_unmet_dependencies(environment) environment.modulepath.each do |path| modules = modules_by_path[path] no_mods = modules.empty? ? _(' (no modules installed)') : '' output << "#{path}#{no_mods}\n" if options[:tree] # The modules with fewest things depending on them will be the # parent of the tree. Can't assume to start with 0 dependencies # since dependencies may be cyclical. modules_by_num_requires = modules.sort_by { |m| m.required_by.size } @seen = {} tree = list_build_tree(modules_by_num_requires, [], nil, :label_unmet => true, :path => path, :label_invalid => false) else tree = [] modules.sort_by { |mod| mod.forge_name or mod.name }.each do |mod| tree << list_build_node(mod, path, :label_unmet => false, :path => path, :label_invalid => true) end end output << Puppet::ModuleTool.format_tree(tree) end output end end def unmet_dependencies(environment) error_types = [:non_semantic_version, :version_mismatch, :missing] unmet_deps = {} error_types.each do |type| unmet_deps[type] = Hash.new do |hash, key| hash[key] = { :errors => [], :parent => nil } end end # Prepare the unmet dependencies for display on the console. environment.modules.sort_by(&:name).each do |mod| unmet_grouped = Hash.new { |h, k| h[k] = [] } unmet_grouped = mod.unmet_dependencies.each_with_object(unmet_grouped) do |dep, acc| acc[dep[:reason]] << dep end unmet_grouped.each do |type, deps| next if deps.empty? unmet_grouped[type].sort_by { |dep| dep[:name] }.each do |dep| dep_name = dep[:name].tr('/', '-') installed_version = dep[:mod_details][:installed_version] version_constraint = dep[:version_constraint] parent_name = dep[:parent][:name].tr('/', '-') parent_version = dep[:parent][:version] msg = _("'%{parent_name}' (%{parent_version}) requires '%{dependency_name}' (%{dependency_version})") % { parent_name: parent_name, parent_version: parent_version, dependency_name: dep_name, dependency_version: version_constraint } unmet_deps[type][dep[:name]][:errors] << msg unmet_deps[type][dep[:name]][:parent] = { :name => dep[:parent][:name], :version => parent_version } unmet_deps[type][dep[:name]][:version] = installed_version end end end unmet_deps end def warn_unmet_dependencies(environment) @unmet_deps = unmet_dependencies(environment) # Display unmet dependencies by category. error_display_order = [:non_semantic_version, :version_mismatch, :missing] error_display_order.each do |type| next if @unmet_deps[type].empty? @unmet_deps[type].keys.sort.each do |dep| name = dep.tr('/', '-') errors = @unmet_deps[type][dep][:errors] version = @unmet_deps[type][dep][:version] msg = case type when :version_mismatch _("Module '%{name}' (v%{version}) fails to meet some dependencies:\n") % { name: name, version: version } when :non_semantic_version _("Non semantic version dependency %{name} (v%{version}):\n") % { name: name, version: version } else _("Missing dependency '%{name}':\n") % { name: name } end errors.each { |error_string| msg << " #{error_string}\n" } Puppet.warning msg.chomp end end end # Prepare a list of module objects and their dependencies for print in a # tree view. # # Returns an Array of Hashes # # Example: # # [ # { # :text => "puppetlabs-bacula (v0.0.2)", # :dependencies=> [ # { :text => "puppetlabs-stdlib (v2.2.1)", :dependencies => [] }, # { # :text => "puppetlabs-mysql (v1.0.0)" # :dependencies => [ # { # :text => "bodepd-create_resources (v0.0.1)", # :dependencies => [] # } # ] # }, # { :text => "puppetlabs-sqlite (v0.0.1)", :dependencies => [] }, # ] # } # ] # # When the above data structure is passed to Puppet::ModuleTool.build_tree # you end up with something like this: # # /etc/puppetlabs/code/modules # └─┬ puppetlabs-bacula (v0.0.2) # ├── puppetlabs-stdlib (v2.2.1) # ├─┬ puppetlabs-mysql (v1.0.0) # │ └── bodepd-create_resources (v0.0.1) # └── puppetlabs-sqlite (v0.0.1) # def list_build_tree(list, ancestors = [], parent = nil, params = {}) list.filter_map do |mod| next if @seen[(mod.forge_name or mod.name)] node = list_build_node(mod, parent, params) @seen[(mod.forge_name or mod.name)] = true unless ancestors.include?(mod) node[:dependencies] ||= [] missing_deps = mod.unmet_dependencies.select do |dep| dep[:reason] == :missing end missing_deps.map do |mis_mod| str = "#{colorize(:bg_red, _('UNMET DEPENDENCY'))} #{mis_mod[:name].tr('/', '-')} " str << "(#{colorize(:cyan, mis_mod[:version_constraint])})" node[:dependencies] << { :text => str } end node[:dependencies] += list_build_tree(mod.dependencies_as_modules, ancestors + [mod], mod, params) end node end end # Prepare a module object for print in a tree view. Each node in the tree # must be a Hash in the following format: # # { :text => "puppetlabs-mysql (v1.0.0)" } # # The value of a module's :text is affected by three (3) factors: the format # of the tree, its dependency status, and the location in the modulepath # relative to its parent. # # Returns a Hash # def list_build_node(mod, parent, params) str = ''.dup str << (mod.forge_name ? mod.forge_name.tr('/', '-') : mod.name) str << ' (' + colorize(:cyan, mod.version ? "v#{mod.version}" : '???') + ')' unless File.dirname(mod.path) == params[:path] str << " [#{File.dirname(mod.path)}]" end if @unmet_deps[:version_mismatch].include?(mod.forge_name) if params[:label_invalid] str << ' ' + colorize(:red, _('invalid')) elsif parent.respond_to?(:forge_name) unmet_parent = @unmet_deps[:version_mismatch][mod.forge_name][:parent] if unmet_parent[:name] == parent.forge_name && unmet_parent[:version] == "v#{parent.version}" str << ' ' + colorize(:red, _('invalid')) end end end { :text => str } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/module/install.rb
lib/puppet/face/module/install.rb
# encoding: UTF-8 # frozen_string_literal: true require_relative '../../../puppet/forge' require_relative '../../../puppet/module_tool/install_directory' require 'pathname' Puppet::Face.define(:module, '1.0.0') do action(:install) do summary _("Install a module from the Puppet Forge or a release archive.") description <<-EOT Installs a module from the Puppet Forge or from a release archive file. Note: Module install uses MD5 checksums, which are prohibited on FIPS enabled systems. The specified module will be installed into the directory specified with the `--target-dir` option, which defaults to the first directory in the modulepath. EOT returns _("Pathname object representing the path to the installed module.") examples <<-'EOT' Install a module: $ puppet module install puppetlabs-vcsrepo Preparing to install into /etc/puppetlabs/code/modules ... Downloading from https://forgeapi.puppet.com ... Installing -- do not interrupt ... /etc/puppetlabs/code/modules └── puppetlabs-vcsrepo (v0.0.4) Install a module to a specific environment: $ puppet module install puppetlabs-vcsrepo --environment development Preparing to install into /etc/puppetlabs/code/environments/development/modules ... Downloading from https://forgeapi.puppet.com ... Installing -- do not interrupt ... /etc/puppetlabs/code/environments/development/modules └── puppetlabs-vcsrepo (v0.0.4) Install a specific module version: $ puppet module install puppetlabs-vcsrepo -v 0.0.4 Preparing to install into /etc/puppetlabs/modules ... Downloading from https://forgeapi.puppet.com ... Installing -- do not interrupt ... /etc/puppetlabs/code/modules └── puppetlabs-vcsrepo (v0.0.4) Install a module into a specific directory: $ puppet module install puppetlabs-vcsrepo --target-dir=/opt/puppetlabs/puppet/modules Preparing to install into /opt/puppetlabs/puppet/modules ... Downloading from https://forgeapi.puppet.com ... Installing -- do not interrupt ... /opt/puppetlabs/puppet/modules └── puppetlabs-vcsrepo (v0.0.4) Install a module into a specific directory and check for dependencies in other directories: $ puppet module install puppetlabs-vcsrepo --target-dir=/opt/puppetlabs/puppet/modules --modulepath /etc/puppetlabs/code/modules Preparing to install into /opt/puppetlabs/puppet/modules ... Downloading from https://forgeapi.puppet.com ... Installing -- do not interrupt ... /opt/puppetlabs/puppet/modules └── puppetlabs-vcsrepo (v0.0.4) Install a module from a release archive: $ puppet module install puppetlabs-vcsrepo-0.0.4.tar.gz Preparing to install into /etc/puppetlabs/code/modules ... Downloading from https://forgeapi.puppet.com ... Installing -- do not interrupt ... /etc/puppetlabs/code/modules └── puppetlabs-vcsrepo (v0.0.4) Install a module from a release archive and ignore dependencies: $ puppet module install puppetlabs-vcsrepo-0.0.4.tar.gz --ignore-dependencies Preparing to install into /etc/puppetlabs/code/modules ... Installing -- do not interrupt ... /etc/puppetlabs/code/modules └── puppetlabs-vcsrepo (v0.0.4) EOT arguments _("<name>") option "--force", "-f" do summary _("Force overwrite of existing module, if any. (Implies --ignore-dependencies.)") description <<-EOT Force overwrite of existing module, if any. Implies --ignore-dependencies. EOT end option "--target-dir DIR", "-i DIR" do summary _("The directory into which modules are installed.") description <<-EOT The directory into which modules are installed; defaults to the first directory in the modulepath. Specifying this option will change the installation directory, and will use the existing modulepath when checking for dependencies. If you wish to check a different set of directories for dependencies, you must also use the `--environment` or `--modulepath` options. EOT end option "--ignore-dependencies" do summary _("Do not attempt to install dependencies. (Implied by --force.)") description <<-EOT Do not attempt to install dependencies. Implied by --force. EOT end option "--version VER", "-v VER" do summary _("Module version to install.") description <<-EOT Module version to install; can be an exact version or a requirement string, eg '>= 1.0.3'. Defaults to latest version. EOT end when_invoked do |name, options| Puppet::ModuleTool.set_option_defaults options Puppet.notice _("Preparing to install into %{dir} ...") % { dir: options[:target_dir] } install_dir = Puppet::ModuleTool::InstallDirectory.new(Pathname.new(options[:target_dir])) Puppet::ModuleTool::Applications::Installer.run(name, install_dir, options) end when_rendering :console do |return_value, name, _options| case return_value[:result] when :noop Puppet.notice _("Module %{name} %{version} is already installed.") % { name: name, version: return_value[:version] } exit 0 when :failure Puppet.err(return_value[:error][:multiline]) exit 1 else tree = Puppet::ModuleTool.build_tree(return_value[:graph], return_value[:install_dir]) "#{return_value[:install_dir]}\n" + Puppet::ModuleTool.format_tree(tree) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/any.rb
lib/puppet/confine/any.rb
# frozen_string_literal: true class Puppet::Confine::Any < Puppet::Confine def self.summarize(confines) confines.inject(0) { |count, confine| count + confine.summary } end def pass?(value) !!value end def message(value) "0 confines (of #{value.length}) were true" end def summary result.find_all { |v| v == true }.length end def valid? if @values.any? { |value| pass?(value) } true else Puppet.debug { "#{label}: #{message(@values)}" } false end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/boolean.rb
lib/puppet/confine/boolean.rb
# frozen_string_literal: true require_relative '../../puppet/confine' # Common module for the Boolean confines. It currently # contains just enough code to implement PUP-9336. class Puppet::Confine module Boolean # Returns the passing value for the Boolean confine. def passing_value raise NotImplementedError, "The Boolean confine %{confine} must provide the passing value." % { confine: self.class.name } end # The Boolean confines 'true' and 'false' let the user specify # two types of values: # * A lambda for lazy evaluation. This would be something like # confine :true => lambda { true } # # * A single Boolean value, or an array of Boolean values. This would # be something like # confine :true => true OR confine :true => [true, false, false, true] # # This override distinguishes between the two cases. def values # Note that Puppet::Confine's constructor ensures that @values # will always be an array, even if a lambda's passed in. This is # why we have the length == 1 check. unless @values.length == 1 && @values.first.respond_to?(:call) return @values end # We have a lambda. Here, we want to enforce "cache positive" # behavior, which is to cache the result _if_ it evaluates to # the passing value (i.e. the class name). return @cached_value unless @cached_value.nil? # Double negate to coerce the value into a Boolean calculated_value = !!@values.first.call if calculated_value == passing_value @cached_value = [calculated_value] end [calculated_value] end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/feature.rb
lib/puppet/confine/feature.rb
# frozen_string_literal: true require_relative '../../puppet/confine' class Puppet::Confine::Feature < Puppet::Confine def self.summarize(confines) confines.collect(&:values).flatten.uniq.find_all { |value| !confines[0].pass?(value) } end # Is the named feature available? def pass?(value) Puppet.features.send(value.to_s + "?") end def message(value) "feature #{value} is missing" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/false.rb
lib/puppet/confine/false.rb
# frozen_string_literal: true require_relative '../../puppet/confine/boolean' class Puppet::Confine::False < Puppet::Confine include Puppet::Confine::Boolean def passing_value false end def self.summarize(confines) confines.inject(0) { |count, confine| count + confine.summary } end def pass?(value) !value end def message(value) "true value when expecting false" end def summary result.find_all { |v| v == false }.length end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/variable.rb
lib/puppet/confine/variable.rb
# frozen_string_literal: true require_relative '../../puppet/confine' # Require a specific value for a variable, either a Puppet setting # or a Facter value. This class is a bit weird because the name # is set explicitly by the ConfineCollection class -- from this class, # it's not obvious how the name would ever get set. class Puppet::Confine::Variable < Puppet::Confine # Provide a hash summary of failing confines -- the key of the hash # is the name of the confine, and the value is the missing yet required values. # Only returns failed values, not all required values. def self.summarize(confines) result = Hash.new { |hash, key| hash[key] = [] } confines.each_with_object(result) { |confine, total| total[confine.name] += confine.values unless confine.valid?; } end # This is set by ConfineCollection. attr_accessor :name # Retrieve the value from facter def facter_value @facter_value ||= Puppet.runtime[:facter].value(name).to_s.downcase end def initialize(values) super @values = @values.collect { |v| v.to_s.downcase } end def message(value) "facter value '#{test_value}' for '#{name}' not in required list '#{values.join(',')}'" end # Compare the passed-in value to the retrieved value. def pass?(value) test_value.downcase.to_s == value.to_s.downcase end def reset # Reset the cache. We want to cache it during a given # run, but not across runs. @facter_value = nil end def valid? @values.include?(test_value.to_s.downcase) ensure reset end private def setting? Puppet.settings.valid?(name) end def test_value setting? ? Puppet.settings[name] : facter_value end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/true.rb
lib/puppet/confine/true.rb
# frozen_string_literal: true require_relative '../../puppet/confine/boolean' class Puppet::Confine::True < Puppet::Confine include Puppet::Confine::Boolean def passing_value true end def self.summarize(confines) confines.inject(0) { |count, confine| count + confine.summary } end def pass?(value) # Double negate, so we only get true or false. !!value end def message(value) "false value when expecting true" end def summary result.find_all { |v| v == true }.length end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine/exists.rb
lib/puppet/confine/exists.rb
# frozen_string_literal: true require_relative '../../puppet/confine' class Puppet::Confine::Exists < Puppet::Confine def self.summarize(confines) confines.inject([]) { |total, confine| total + confine.summary } end def pass?(value) value && (for_binary? ? which(value) : Puppet::FileSystem.exist?(value)) end def message(value) "file #{value} does not exist" end def summary result.zip(values).each_with_object([]) { |args, array| val, f = args; array << f unless val; } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/resource.rb
lib/puppet/parser/resource.rb
# frozen_string_literal: true require_relative '../../puppet/resource' # The primary difference between this class and its # parent is that this class has rules on who can set # parameters class Puppet::Parser::Resource < Puppet::Resource require_relative 'resource/param' require_relative '../../puppet/util/tagging' include Puppet::Util include Puppet::Util::Errors include Puppet::Util::Logging attr_accessor :source, :scope, :collector_id attr_accessor :virtual, :override, :translated, :catalog, :evaluated attr_accessor :file, :line, :kind attr_reader :exported, :parameters # Determine whether the provided parameter name is a relationship parameter. def self.relationship_parameter?(name) @relationship_names ||= Puppet::Type.relationship_params.collect(&:name) @relationship_names.include?(name) end # Set up some boolean test methods def translated?; !!@translated; end def override?; !!@override; end def evaluated?; !!@evaluated; end def [](param) param = param.intern if param == :title return title end if @parameters.has_key?(param) @parameters[param].value else nil end end def eachparam @parameters.each do |_name, param| yield param end end def environment scope.environment end # Process the stage metaparameter for a class. A containment edge # is drawn from the class to the stage. The stage for containment # defaults to main, if none is specified. def add_edge_to_stage return unless class? stage = catalog.resource(:stage, self[:stage] || (scope && scope.resource && scope.resource[:stage]) || :main) unless stage raise ArgumentError, _("Could not find stage %{stage} specified by %{resource}") % { stage: self[:stage] || :main, resource: self } end self[:stage] ||= stage.title unless stage.title == :main catalog.add_edge(stage, self) end # Retrieve the associated definition and evaluate it. def evaluate return if evaluated? Puppet::Util::Profiler.profile(_("Evaluated resource %{res}") % { res: self }, [:compiler, :evaluate_resource, self]) do @evaluated = true if builtin_type? devfail "Cannot evaluate a builtin type (#{type})" elsif resource_type.nil? self.fail "Cannot find definition #{type}" else finish_evaluation() # do not finish completely (as that destroys Sensitive data) resource_type.evaluate_code(self) end end end # Mark this resource as both exported and virtual, # or remove the exported mark. def exported=(value) if value @virtual = true else end @exported = value end # Finish the evaluation by assigning defaults and scope tags # @api private # def finish_evaluation return if @evaluation_finished add_scope_tags @evaluation_finished = true end # Do any finishing work on this object, called before # storage/translation. The method does nothing the second time # it is called on the same resource. # # @param do_validate [Boolean] true if validation should be performed # # @api private def finish(do_validate = true) return if finished? @finished = true finish_evaluation replace_sensitive_data validate if do_validate end # Has this resource already been finished? def finished? @finished end def initialize(type, title, attributes, with_defaults = true) raise ArgumentError, _('Resources require a hash as last argument') unless attributes.is_a? Hash raise ArgumentError, _('Resources require a scope') unless attributes[:scope] super(type, title, attributes) @source ||= scope.source if with_defaults scope.lookupdefaults(self.type).each_pair do |name, param| next if @parameters.include?(name) debug "Adding default for #{name}" param = param.dup @parameters[name] = param tag(*param.value) if param.name == :tag end end end # Is this resource modeling an isomorphic resource type? def isomorphic? if builtin_type? resource_type.isomorphic? else true end end # Merge an override resource in. This will throw exceptions if # any overrides aren't allowed. def merge(resource) # Test the resource scope, to make sure the resource is even allowed # to override. unless source.equal?(resource.source) || resource.source.child_of?(source) raise Puppet::ParseError.new(_("Only subclasses can override parameters"), resource.file, resource.line) end if evaluated? error_location_str = Puppet::Util::Errors.error_location(file, line) msg = if error_location_str.empty? _('Attempt to override an already evaluated resource with new values') else _('Attempt to override an already evaluated resource, defined at %{error_location}, with new values') % { error_location: error_location_str } end strict = Puppet[:strict] unless strict == :off if strict == :error raise Puppet::ParseError.new(msg, resource.file, resource.line) else msg += Puppet::Util::Errors.error_location_with_space(resource.file, resource.line) Puppet.warning(msg) end end end # Some of these might fail, but they'll fail in the way we want. resource.parameters.each do |_name, param| override_parameter(param) end end def name self[:name] || title end # A temporary occasion, until I get paths in the scopes figured out. alias path to_s # Define a parameter in our resource. # if we ever receive a parameter named 'tag', set # the resource tags with its value. def set_parameter(param, value = nil) unless param.is_a?(Puppet::Parser::Resource::Param) param = param.name if param.is_a?(Puppet::Pops::Resource::Param) param = Puppet::Parser::Resource::Param.new( :name => param, :value => value, :source => source ) end tag(*param.value) if param.name == :tag # And store it in our parameter hash. @parameters[param.name] = param end alias []= set_parameter def to_hash parse_title.merge(@parameters.each_with_object({}) do |(_, param), result| value = param.value value = (:undef == value) ? nil : value next if value.nil? case param.name when :before, :subscribe, :notify, :require if value.is_a?(Array) value = value.flatten.reject { |v| v.nil? || :undef == v } end else end result[param.name] = value end) end # Convert this resource to a RAL resource. def to_ral copy_as_resource.to_ral end # Answers if this resource is tagged with at least one of the tags given in downcased string form. # # The method is a faster variant of the tagged? method that does no conversion of its # arguments. # # The match takes into account the tags that a resource will inherit from its container # but have not been set yet. # It does *not* take tags set via resource defaults as these will *never* be set on # the resource itself since all resources always have tags that are automatically # assigned. # # @param tag_array [Array[String]] list tags to look for # @return [Boolean] true if this instance is tagged with at least one of the provided tags # def raw_tagged?(tag_array) super || ((scope_resource = scope.resource) && !scope_resource.equal?(self) && scope_resource.raw_tagged?(tag_array)) end def offset nil end def pos nil end private def add_scope_tags scope_resource = scope.resource unless scope_resource.nil? || scope_resource.equal?(self) merge_tags_from(scope_resource) end end def replace_sensitive_data parameters.keys.each do |name| param = parameters[name] if param.value.is_a?(Puppet::Pops::Types::PSensitiveType::Sensitive) @sensitive_parameters << name parameters[name] = Puppet::Parser::Resource::Param.from_param(param, param.value.unwrap) end end end # Accept a parameter from an override. def override_parameter(param) # This can happen if the override is defining a new parameter, rather # than replacing an existing one. current = @parameters[param.name] (set_parameter(param) and return) unless current # Parameter is already set - if overriding with a default - simply ignore the setting of the default value return if scope.is_default?(type, param.name, param.value) # The parameter is already set. Fail if they're not allowed to override it. unless param.source.child_of?(current.source) || param.source.equal?(current.source) && scope.is_default?(type, param.name, current.value) error_location_str = Puppet::Util::Errors.error_location(current.file, current.line) msg = if current.source.to_s == '' if error_location_str.empty? _("Parameter '%{name}' is already set on %{resource}; cannot redefine") % { name: param.name, resource: ref } else _("Parameter '%{name}' is already set on %{resource} at %{error_location}; cannot redefine") % { name: param.name, resource: ref, error_location: error_location_str } end elsif error_location_str.empty? _("Parameter '%{name}' is already set on %{resource} by %{source}; cannot redefine") % { name: param.name, resource: ref, source: current.source.to_s } else _("Parameter '%{name}' is already set on %{resource} by %{source} at %{error_location}; cannot redefine") % { name: param.name, resource: ref, source: current.source.to_s, error_location: error_location_str } end raise Puppet::ParseError.new(msg, param.file, param.line) end # If we've gotten this far, we're allowed to override. # Merge with previous value, if the parameter was generated with the +> # syntax. It's important that we use a copy of the new param instance # here, not the old one, and not the original new one, so that the source # is registered correctly for later overrides but the values aren't # implicitly shared when multiple resources are overridden at once (see # ticket #3556). if param.add param = param.dup param.value = [current.value, param.value].flatten end set_parameter(param) end # Make sure the resource's parameters are all valid for the type. def validate if builtin_type? begin @parameters.each { |name, _value| validate_parameter(name) } rescue => detail self.fail Puppet::ParseError, detail.to_s + " on #{self}", detail end else resource_type.validate_resource(self) end end def extract_parameters(params) params.each do |param| # Don't set the same parameter twice self.fail Puppet::ParseError, _("Duplicate parameter '%{param}' for on %{resource}") % { param: param.name, resource: self } if @parameters[param.name] set_parameter(param) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/templatewrapper.rb
lib/puppet/parser/templatewrapper.rb
# frozen_string_literal: true require_relative '../../puppet/parser/files' require 'erb' require_relative '../../puppet/file_system' # A simple wrapper for templates, so they don't have full access to # the scope objects. # # @api private class Puppet::Parser::TemplateWrapper include Puppet::Util Puppet::Util.logmethods(self) def initialize(scope) @__scope__ = scope end # @return [String] The full path name of the template that is being executed # @api public def file @__file__ end # @return [Puppet::Parser::Scope] The scope in which the template is evaluated # @api public def scope @__scope__ end # Find which line in the template (if any) we were called from. # @return [String] the line number # @api private def script_line identifier = Regexp.escape(@__file__ || "(erb)") (caller.find { |l| l =~ /#{identifier}:/ } || "")[/:(\d+):/, 1] end private :script_line # Should return true if a variable is defined, false if it is not # @api public def has_variable?(name) scope.include?(name.to_s) end # @return [Array<String>] The list of defined classes # @api public def classes scope.catalog.classes end # @return [Array<String>] The tags defined in the current scope # @api public def tags raise NotImplementedError, "Call 'all_tags' instead." end # @return [Array<String>] All the defined tags # @api public def all_tags scope.catalog.tags end # @api private def file=(filename) @__file__ = Puppet::Parser::Files.find_template(filename, scope.compiler.environment) unless @__file__ raise Puppet::ParseError, _("Could not find template '%{filename}'") % { filename: filename } end end # @api private def result(string = nil) if string template_source = "inline template" else string = Puppet::FileSystem.read_preserve_line_endings(@__file__) template_source = @__file__ end # Expose all the variables in our scope as instance variables of the # current object, making it possible to access them without conflict # to the regular methods. escaped_template_source = template_source.gsub(/%/, '%%') benchmark(:debug, _("Bound template variables for %{template_source} in %%{seconds} seconds") % { template_source: escaped_template_source }) do scope.to_hash.each do |name, value| realname = name.gsub(/[^\w]/, "_") instance_variable_set("@#{realname}", value) end end result = nil benchmark(:debug, _("Interpolated template %{template_source} in %%{seconds} seconds") % { template_source: escaped_template_source }) do template = Puppet::Util.create_erb(string) template.filename = @__file__ result = template.result(binding) end result end def to_s "template[#{@__file__ || 'inline'}]" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/files.rb
lib/puppet/parser/files.rb
# frozen_string_literal: true module Puppet::Parser::Files module_function # Return a list of manifests as absolute filenames matching the given # pattern. # # @param pattern [String] A reference for a file in a module. It is the # format "<modulename>/<file glob>" # @param environment [Puppet::Node::Environment] the environment of modules # # @return [Array(String, Array<String>)] the module name and the list of files found # @api private def find_manifests_in_modules(pattern, environment) module_name, file_pattern = split_file_path(pattern) mod = environment.module(module_name) if mod [mod.name, mod.match_manifests(file_pattern)] else [nil, []] end end # Find the path to the given file selector. Files can be selected in # one of two ways: # * absolute path: the path is simply returned # * modulename/filename selector: a file is found in the file directory # of the named module. # # The check for file existence is performed on the node compiling the # manifest. A node running "puppet apply" compiles its own manifest, but # a node running "puppet agent" depends on the configured puppetserver # for compiling. In either case, a nil is returned if no file is found. # # @param template [String] the file selector # @param environment [Puppet::Node::Environment] the environment in which to search # @return [String, nil] the absolute path to the file or nil if there is no file found # # @api private def find_file(file, environment) find_in_module(file, environment) do |mod, module_file| mod.file(module_file) end end # Find the path to the given template selector. Templates can be selected in # a couple of ways: # * absolute path: the path is simply returned # * modulename/filename selector: a file is found in the template directory # of the named module. # # In the last two cases a nil is returned if there isn't a file found. In the # first case (absolute path), there is no existence check done and so the # path will be returned even if there isn't a file available. # # @param template [String] the template selector # @param environment [Puppet::Node::Environment] the environment in which to search # @return [String, nil] the absolute path to the template file or nil if there is no file found # # @api private def find_template(template, environment) find_in_module(template, environment) do |mod, template_file| mod.template(template_file) end end # @api private def find_in_module(reference, environment) if Puppet::Util.absolute_path?(reference) reference else path, file = split_file_path(reference) mod = environment.module(path) if file && mod yield(mod, file) else nil end end end # Split the path into the module and the rest of the path, or return # nil if the path is empty or absolute (starts with a /). # @api private def split_file_path(path) if path == "" || Puppet::Util.absolute_path?(path) nil else path.split(File::SEPARATOR, 2) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/compiler.rb
lib/puppet/parser/compiler.rb
# frozen_string_literal: true require 'forwardable' require_relative '../../puppet/node' require_relative '../../puppet/resource/catalog' require_relative '../../puppet/util/errors' require_relative '../../puppet/loaders' require_relative '../../puppet/pops' # Maintain a graph of scopes, along with a bunch of data # about the individual catalog we're compiling. class Puppet::Parser::Compiler include Puppet::Parser::AbstractCompiler extend Forwardable include Puppet::Util include Puppet::Util::Errors include Puppet::Pops::Evaluator::Runtime3Support def self.compile(node, code_id = nil) node.environment.check_for_reparse errors = node.environment.validation_errors unless errors.empty? errors.each { |e| Puppet.err(e) } if errors.size > 1 errmsg = [ _("Compilation has been halted because: %{error}") % { error: errors.first }, _("For more information, see https://puppet.com/docs/puppet/latest/environments_about.html") ] raise(Puppet::Error, errmsg.join(' ')) end new(node, :code_id => code_id).compile(&:to_resource) rescue Puppet::ParseErrorWithIssue => detail detail.node = node.name Puppet.log_exception(detail) raise rescue => detail message = _("%{message} on node %{node}") % { message: detail, node: node.name } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end attr_reader :node, :facts, :collections, :catalog, :resources, :relationships, :topscope attr_reader :qualified_variables # Access to the configured loaders for 4x # @return [Puppet::Pops::Loader::Loaders] the configured loaders # @api private attr_reader :loaders # The id of code input to the compiler. # @api private attr_accessor :code_id # Add a collection to the global list. def_delegator :@collections, :<<, :add_collection def_delegator :@relationships, :<<, :add_relationship # Store a resource override. def add_override(override) # If possible, merge the override in immediately. resource = @catalog.resource(override.ref) if resource resource.merge(override) else # Otherwise, store the override for later; these # get evaluated in Resource#finish. @resource_overrides[override.ref] << override end end def add_resource(scope, resource) @resources << resource # Note that this will fail if the resource is not unique. @catalog.add_resource(resource) if !resource.class? and resource[:stage] # TRANSLATORS "stage" is a keyword in Puppet and should not be translated raise ArgumentError, _("Only classes can set 'stage'; normal resources like %{resource} cannot change run stage") % { resource: resource } end # Stages should not be inside of classes. They are always a # top-level container, regardless of where they appear in the # manifest. return if resource.stage? # This adds a resource to the class it lexically appears in in the # manifest. unless resource.class? @catalog.add_edge(scope.resource, resource) end end # Store the fact that we've evaluated a class def add_class(name) @catalog.add_class(name) unless name == "" end # Add a catalog validator that will run at some stage to this compiler # @param catalog_validators [Class<CatalogValidator>] The catalog validator class to add def add_catalog_validator(catalog_validators) @catalog_validators << catalog_validators nil end def add_catalog_validators add_catalog_validator(CatalogValidator::RelationshipValidator) end # Return a list of all of the defined classes. def_delegator :@catalog, :classes, :classlist def with_context_overrides(description = '', &block) Puppet.override(@context_overrides, description, &block) end # Compiler our catalog. This mostly revolves around finding and evaluating classes. # This is the main entry into our catalog. def compile Puppet.override(@context_overrides, _("For compiling %{node}") % { node: node.name }) do @catalog.environment_instance = environment # Set the client's parameters into the top scope. Puppet::Util::Profiler.profile(_("Compile: Set node parameters"), [:compiler, :set_node_params]) { set_node_parameters } Puppet::Util::Profiler.profile(_("Compile: Created settings scope"), [:compiler, :create_settings_scope]) { create_settings_scope } # TRANSLATORS "main" is a function name and should not be translated Puppet::Util::Profiler.profile(_("Compile: Evaluated main"), [:compiler, :evaluate_main]) { evaluate_main } Puppet::Util::Profiler.profile(_("Compile: Evaluated AST node"), [:compiler, :evaluate_ast_node]) { evaluate_ast_node } Puppet::Util::Profiler.profile(_("Compile: Evaluated node classes"), [:compiler, :evaluate_node_classes]) { evaluate_node_classes } Puppet::Util::Profiler.profile(_("Compile: Evaluated generators"), [:compiler, :evaluate_generators]) { evaluate_generators } Puppet::Util::Profiler.profile(_("Compile: Validate Catalog pre-finish"), [:compiler, :validate_pre_finish]) do validate_catalog(CatalogValidator::PRE_FINISH) end Puppet::Util::Profiler.profile(_("Compile: Finished catalog"), [:compiler, :finish_catalog]) { finish } fail_on_unevaluated Puppet::Util::Profiler.profile(_("Compile: Validate Catalog final"), [:compiler, :validate_final]) do validate_catalog(CatalogValidator::FINAL) end if block_given? yield @catalog else @catalog end end end def validate_catalog(validation_stage) @catalog_validators.select { |vclass| vclass.validation_stage?(validation_stage) }.each { |vclass| vclass.new(@catalog).validate } end # Constructs the overrides for the context def context_overrides { :current_environment => environment, :global_scope => @topscope, # 4x placeholder for new global scope :loaders => @loaders, # 4x loaders } end def_delegator :@collections, :delete, :delete_collection # Return the node's environment. def environment node.environment end # Evaluate all of the classes specified by the node. # Classes with parameters are evaluated as if they were declared. # Classes without parameters or with an empty set of parameters are evaluated # as if they were included. This means classes with an empty set of # parameters won't conflict even if the class has already been included. def evaluate_node_classes if @node.classes.is_a? Hash classes_with_params, classes_without_params = @node.classes.partition { |_name, params| params and !params.empty? } # The results from Hash#partition are arrays of pairs rather than hashes, # so we have to convert to the forms evaluate_classes expects (Hash, and # Array of class names) classes_with_params = classes_with_params.to_h classes_without_params.map!(&:first) else classes_with_params = {} classes_without_params = @node.classes end evaluate_classes(classes_with_params, @node_scope || topscope) evaluate_classes(classes_without_params, @node_scope || topscope) end # If ast nodes are enabled, then see if we can find and evaluate one. # # @api private def evaluate_ast_node krt = environment.known_resource_types return unless krt.nodes? # ast_nodes? # Now see if we can find the node. astnode = nil @node.names.each do |name| astnode = krt.node(name.to_s.downcase) break if astnode end unless astnode ||= krt.node("default") raise Puppet::ParseError, _("Could not find node statement with name 'default' or '%{names}'") % { names: node.names.join(", ") } end # Create a resource to model this node, and then add it to the list # of resources. resource = astnode.ensure_in_catalog(topscope) resource.evaluate @node_scope = topscope.class_scope(astnode) end # Evaluates each specified class in turn. If there are any classes that # can't be found, an error is raised. This method really just creates resource objects # that point back to the classes, and then the resources are themselves # evaluated later in the process. # def evaluate_classes(classes, scope, lazy_evaluate = true) raise Puppet::DevError, _("No source for scope passed to evaluate_classes") unless scope.source class_parameters = nil # if we are a param class, save the classes hash # and transform classes to be the keys if classes.instance_of?(Hash) class_parameters = classes classes = classes.keys end hostclasses = classes.collect do |name| environment.known_resource_types.find_hostclass(name) or raise Puppet::Error, _("Could not find class %{name} for %{node}") % { name: name, node: node.name } end if class_parameters resources = ensure_classes_with_parameters(scope, hostclasses, class_parameters) unless lazy_evaluate resources.each(&:evaluate) end resources else already_included, newly_included = ensure_classes_without_parameters(scope, hostclasses) unless lazy_evaluate newly_included.each(&:evaluate) end already_included + newly_included end end def evaluate_relationships @relationships.each { |rel| rel.evaluate(catalog) } end # Return a resource by either its ref or its type and title. def_delegator :@catalog, :resource, :findresource def initialize(node, code_id: nil) @node = sanitize_node(node) @code_id = code_id initvars add_catalog_validators # Resolutions of fully qualified variable names @qualified_variables = {} end # Create a new scope, with either a specified parent scope or # using the top scope. def newscope(parent, options = {}) parent ||= topscope scope = Puppet::Parser::Scope.new(self, **options) scope.parent = parent scope end # Return any overrides for the given resource. def resource_overrides(resource) @resource_overrides[resource.ref] end private def ensure_classes_with_parameters(scope, hostclasses, parameters) hostclasses.collect do |klass| klass.ensure_in_catalog(scope, parameters[klass.name] || {}) end end def ensure_classes_without_parameters(scope, hostclasses) already_included = [] newly_included = [] hostclasses.each do |klass| class_scope = scope.class_scope(klass) if class_scope already_included << class_scope.resource else newly_included << klass.ensure_in_catalog(scope) end end [already_included, newly_included] end # Evaluate our collections and return true if anything returned an object. # The 'true' is used to continue a loop, so it's important. def evaluate_collections return false if @collections.empty? exceptwrap do # We have to iterate over a dup of the array because # collections can delete themselves from the list, which # changes its length and causes some collections to get missed. Puppet::Util::Profiler.profile(_("Evaluated collections"), [:compiler, :evaluate_collections]) do found_something = false @collections.dup.each do |collection| found_something = true if collection.evaluate end found_something end end end # Make sure all of our resources have been evaluated into native resources. # We return true if any resources have, so that we know to continue the # evaluate_generators loop. def evaluate_definitions exceptwrap do Puppet::Util::Profiler.profile(_("Evaluated definitions"), [:compiler, :evaluate_definitions]) do urs = unevaluated_resources.each do |resource| resource.evaluate rescue Puppet::Pops::Evaluator::PuppetStopIteration => detail # needs to be handled specifically as the error has the file/line/position where this # occurred rather than the resource fail(Puppet::Pops::Issues::RUNTIME_ERROR, detail, { :detail => detail.message }, detail) rescue Puppet::Error => e # PuppetError has the ability to wrap an exception, if so, use the wrapped exception's # call stack instead fail(Puppet::Pops::Issues::RUNTIME_ERROR, resource, { :detail => e.message }, e.original || e) end !urs.empty? end end end # Iterate over collections and resources until we're sure that the whole # compile is evaluated. This is necessary because both collections # and defined resources can generate new resources, which themselves could # be defined resources. def evaluate_generators count = 0 loop do done = true Puppet::Util::Profiler.profile(_("Iterated (%{count}) on generators") % { count: count + 1 }, [:compiler, :iterate_on_generators]) do # Call collections first, then definitions. done = false if evaluate_collections done = false if evaluate_definitions end break if done count += 1 if count > 1000 raise Puppet::ParseError, _("Somehow looped more than 1000 times while evaluating host catalog") end end end protected :evaluate_generators # Find and evaluate our main object, if possible. def evaluate_main krt = environment.known_resource_types @main = krt.find_hostclass('') || krt.add(Puppet::Resource::Type.new(:hostclass, '')) @topscope.source = @main @main_resource = Puppet::Parser::Resource.new('class', :main, :scope => @topscope, :source => @main) @topscope.resource = @main_resource add_resource(@topscope, @main_resource) @main_resource.evaluate end # Make sure the entire catalog is evaluated. def fail_on_unevaluated fail_on_unevaluated_overrides fail_on_unevaluated_resource_collections end # If there are any resource overrides remaining, then we could # not find the resource they were supposed to override, so we # want to throw an exception. def fail_on_unevaluated_overrides remaining = @resource_overrides.values.flatten.collect(&:ref) unless remaining.empty? raise Puppet::ParseError, _("Could not find resource(s) %{resources} for overriding") % { resources: remaining.join(', ') } end end # Make sure there are no remaining collections that are waiting for # resources that have not yet been instantiated. If this occurs it # is an error (missing resource - it could not be realized). # def fail_on_unevaluated_resource_collections remaining = @collections.collect(&:unresolved_resources).flatten.compact unless remaining.empty? raise Puppet::ParseError, _("Failed to realize virtual resources %{resources}") % { resources: remaining.join(', ') } end end # Make sure all of our resources and such have done any last work # necessary. def finish evaluate_relationships resources.each do |resource| # Add in any resource overrides. overrides = resource_overrides(resource) if overrides overrides.each do |over| resource.merge(over) end # Remove the overrides, so that the configuration knows there # are none left. overrides.clear end resource.finish if resource.respond_to?(:finish) end add_resource_metaparams end protected :finish def add_resource_metaparams main = catalog.resource(:class, :main) unless main # TRANSLATORS "main" is a function name and should not be translated raise _("Couldn't find main") end names = Puppet::Type.metaparams.select do |name| !Puppet::Parser::Resource.relationship_parameter?(name) end data = {} catalog.walk(main, :out) do |source, target| source_data = data[source] || metaparams_as_data(source, names) if source_data # only store anything in the data hash if we've actually got # data data[source] ||= source_data source_data.each do |param, value| target[param] = value if target[param].nil? end data[target] = source_data.merge(metaparams_as_data(target, names)) end target.merge_tags_from(source) end end def metaparams_as_data(resource, params) data = nil params.each do |param| next if resource[param].nil? # Because we could be creating a hash for every resource, # and we actually probably don't often have any data here at all, # we're optimizing a bit by only creating a hash if there's # any data to put in it. data ||= {} data[param] = resource[param] end data end # Set up all of our internal variables. def initvars # The list of overrides. This is used to cache overrides on objects # that don't exist yet. We store an array of each override. @resource_overrides = Hash.new do |overs, ref| overs[ref] = [] end # The list of collections that have been created. This is a global list, # but they each refer back to the scope that created them. @collections = [] # The list of relationships to evaluate. @relationships = [] # For maintaining the relationship between scopes and their resources. @catalog = Puppet::Resource::Catalog.new(@node.name, @node.environment, @code_id) # MOVED HERE - SCOPE IS NEEDED (MOVE-SCOPE) # Create the initial scope, it is needed early @topscope = Puppet::Parser::Scope.new(self) # Initialize loaders and Pcore @loaders = Puppet::Pops::Loaders.new(environment) # Need to compute overrides here, and remember them, because we are about to # enter the magic zone of known_resource_types and initial import. # Expensive entries in the context are bound lazily. @context_overrides = context_overrides() # This construct ensures that initial import (triggered by instantiating # the structure 'known_resource_types') has a configured context # It cannot survive the initvars method, and is later reinstated # as part of compiling... # Puppet.override(@context_overrides, _("For initializing compiler")) do # THE MAGIC STARTS HERE ! This triggers parsing, loading etc. @catalog.version = environment.known_resource_types.version @loaders.pre_load end @catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => @topscope)) # local resource array to maintain resource ordering @resources = [] # Make sure any external node classes are in our class list if @node.classes.instance_of?(Hash) @catalog.add_class(*@node.classes.keys) else @catalog.add_class(*@node.classes) end @catalog_validators = [] end def sanitize_node(node) node.sanitize node end # Set the node's parameters into the top-scope as variables. def set_node_parameters node.parameters.each do |param, value| # We don't want to set @topscope['environment'] from the parameters, # instead we want to get that from the node's environment itself in # case a custom node terminus has done any mucking about with # node.parameters. next if param.to_s == 'environment' # Ensure node does not leak Symbol instances in general @topscope[param.to_s] = value.is_a?(Symbol) ? value.to_s : value end @topscope['environment'] = node.environment.name.to_s # These might be nil. catalog.client_version = node.parameters["clientversion"] catalog.server_version = node.parameters["serverversion"] @topscope.set_trusted(node.trusted_data) @topscope.set_server_facts(node.server_facts) facts_hash = node.facts.nil? ? {} : node.facts.values @topscope.set_facts(facts_hash) end SETTINGS = 'settings' def create_settings_scope settings_type = create_settings_type settings_resource = Puppet::Parser::Resource.new('class', SETTINGS, :scope => @topscope) @catalog.add_resource(settings_resource) settings_type.evaluate_code(settings_resource) settings_resource.instance_variable_set(:@evaluated, true) # Prevents settings from being reevaluated scope = @topscope.class_scope(settings_type) scope.merge_settings(environment.name) end def create_settings_type environment.lock.synchronize do resource_types = environment.known_resource_types settings_type = resource_types.hostclass(SETTINGS) if settings_type.nil? settings_type = Puppet::Resource::Type.new(:hostclass, SETTINGS) resource_types.add(settings_type) end settings_type end end # Return an array of all of the unevaluated resources. These will be definitions, # which need to get evaluated into native resources. def unevaluated_resources # The order of these is significant for speed due to short-circuiting resources.reject { |resource| resource.evaluated? or resource.virtual? or resource.builtin_type? } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/e4_parser_adapter.rb
lib/puppet/parser/e4_parser_adapter.rb
# frozen_string_literal: true require_relative '../../puppet/pops' module Puppet module Parser # Adapts an egrammar/eparser to respond to the public API of the classic parser # and makes use of the new evaluator. # class E4ParserAdapter def initialize @file = '' @string = '' @use = :unspecified end def file=(file) @file = file @use = :file end def parse(string = nil) self.string = string if string parser = Pops::Parser::EvaluatingParser.singleton model = if @use == :string # Parse with a source_file to set in created AST objects (it was either given, or it may be unknown # if caller did not set a file and the present a string. # parser.parse_string(@string, @file || "unknown-source-location") else parser.parse_file(@file) end # the parse_result may be # * empty / nil (no input) # * a Model::Program # * a Model::Expression # args = {} Pops::Model::AstTransformer.new(@file).merge_location(args, model) ast_code = if model.is_a? Pops::Model::Program AST::PopsBridge::Program.new(model, args) else args[:value] = model AST::PopsBridge::Expression.new(args) end # Create the "main" class for the content - this content will get merged with all other "main" content AST::Hostclass.new('', :code => ast_code) end def string=(string) @string = string @use = :string end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/relationship.rb
lib/puppet/parser/relationship.rb
# frozen_string_literal: true class Puppet::Parser::Relationship attr_accessor :source, :target, :type PARAM_MAP = { :relationship => :before, :subscription => :notify } def arrayify(resources, left) case resources when Puppet::Pops::Evaluator::Collectors::AbstractCollector # on the LHS, go as far left as possible, else whatever the collected result is left ? leftmost_alternative(resources) : resources.collected.values when Array resources else [resources] end end def evaluate(catalog) arrayify(source, true).each do |s| arrayify(target, false).each do |t| mk_relationship(s, t, catalog) end end end def initialize(source, target, type) @source = source @target = target @type = type end def param_name PARAM_MAP[type] || raise(ArgumentError, _("Invalid relationship type %{relationship_type}") % { relationship_type: type }) end def mk_relationship(source, target, catalog) source_ref = canonical_ref(source) target_ref = canonical_ref(target) rel_param = param_name source_resource = catalog.resource(*source_ref) unless source_resource raise ArgumentError, _("Could not find resource '%{source}' for relationship on '%{target}'") % { source: source.to_s, target: target.to_s } end unless catalog.resource(*target_ref) raise ArgumentError, _("Could not find resource '%{target}' for relationship from '%{source}'") % { target: target.to_s, source: source.to_s } end Puppet.debug { "Adding relationship from #{source} to #{target} with '#{param_name}'" } if source_resource[rel_param].class != Array source_resource[rel_param] = [source_resource[rel_param]].compact end source_resource[rel_param] << (target_ref[1].nil? ? target_ref[0] : "#{target_ref[0]}[#{target_ref[1]}]") end private # Finds the leftmost alternative for a collector (if it is empty, try its empty alternative recursively until there is # either nothing left, or a non empty set is found. # def leftmost_alternative(x) if x.is_a?(Puppet::Pops::Evaluator::Collectors::AbstractCollector) collected = x.collected return collected.values unless collected.empty? adapter = Puppet::Pops::Adapters::EmptyAlternativeAdapter.get(x) adapter.nil? ? [] : leftmost_alternative(adapter.empty_alternative) elsif x.is_a?(Array) && x.size == 1 && x[0].is_a?(Puppet::Pops::Evaluator::Collectors::AbstractCollector) leftmost_alternative(x[0]) else x end end # Turns a PResourceType or PClassType into an array [type, title] and all other references to [ref, nil] # This is needed since it is not possible to find resources in the catalog based on the type system types :-( # (note, the catalog is also used on the agent side) def canonical_ref(ref) case ref when Puppet::Pops::Types::PResourceType [ref.type_name, ref.title] when Puppet::Pops::Types::PClassType ['class', ref.class_name] else [ref.to_s, nil] end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/script_compiler.rb
lib/puppet/parser/script_compiler.rb
# frozen_string_literal: true require_relative '../../puppet/loaders' require_relative '../../puppet/pops' # A Script "compiler" that does not support catalog operations # # The Script compiler is "one shot" - it does not support rechecking if underlying source has changed or # deal with possible errors in a cached environment. # class Puppet::Parser::ScriptCompiler # Allows the ScriptCompiler to use the 3.x Scope class without being an actual "Compiler" # include Puppet::Parser::AbstractCompiler # @api private attr_reader :topscope # @api private attr_reader :qualified_variables # Access to the configured loaders for 4x # @return [Puppet::Pops::Loader::Loaders] the configured loaders # @api private attr_reader :loaders # @api private attr_reader :environment # @api private attr_reader :node_name def with_context_overrides(description = '', &block) Puppet.override(@context_overrides, description, &block) end # Evaluates the configured setup for a script + code in an environment with modules # def compile Puppet[:strict_variables] = true Puppet[:strict] = :error # TRANSLATORS, "For running script" is not user facing Puppet.override(@context_overrides, "For running script") do # TRANSLATORS "main" is a function name and should not be translated result = Puppet::Util::Profiler.profile(_("Script: Evaluated main"), [:script, :evaluate_main]) { evaluate_main } if block_given? yield self else result end end rescue Puppet::ParseErrorWithIssue => detail detail.node = node_name Puppet.log_exception(detail) raise rescue => detail message = "#{detail} on node #{node_name}" Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end # Constructs the overrides for the context def context_overrides { :current_environment => environment, :global_scope => @topscope, # 4x placeholder for new global scope :loaders => @loaders, # 4x loaders :rich_data => true, } end # Create a script compiler for the given environment where errors are logged as coming # from the given node_name # def initialize(environment, node_name, for_agent = false) @environment = environment @node_name = node_name # Create the initial scope, it is needed early @topscope = Puppet::Parser::Scope.new(self) # Initialize loaders and Pcore if for_agent @loaders = Puppet::Pops::Loaders.new(environment, true) else @loaders = Puppet::Pops::Loaders.new(environment) end # Need to compute overrides here, and remember them, because we are about to # Expensive entries in the context are bound lazily. @context_overrides = context_overrides() # Resolutions of fully qualified variable names @qualified_variables = {} end # Having multiple named scopes hanging from top scope is not supported when scripting # in the regular compiler this is used to create one named scope per class. # When scripting, the "main class" is just a container of the top level code to evaluate # and it is not evaluated as a class added to a catalog. Since classes are not supported # there is no need to support the concept of "named scopes" as all variables are local # or in the top scope itself (notably, the $settings:: namespace is initialized # as just a set of variables in that namespace - there is no named scope for 'settings' # when scripting. # # Keeping this method here to get specific error as being unsure if there are functions/logic # that will call this. The AbstractCompiler defines this method, but maybe it does not # have to (TODO). # def newscope(parent, options = {}) raise _('having multiple named scopes is not supported when scripting') end private # Find and evaluate the top level code. def evaluate_main @loaders.pre_load program = @loaders.load_main_manifest program.nil? ? nil : Puppet::Pops::Parser::EvaluatingParser.singleton.evaluator.evaluate(program, @topscope) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/catalog_compiler.rb
lib/puppet/parser/catalog_compiler.rb
# frozen_string_literal: true require_relative '../../puppet/loaders' require_relative '../../puppet/pops' # A Catalog "compiler" that is like the regular compiler but with an API # that is harmonized with the ScriptCompiler # # The Script compiler is "one shot" - it does not support rechecking if underlying source has changed or # deal with possible errors in a cached environment. # class Puppet::Parser::CatalogCompiler < Puppet::Parser::Compiler # Evaluates the configured setup for a script + code in an environment with modules # def compile Puppet[:strict_variables] = true Puppet[:strict] = :error Puppet.override(rich_data: true) do super end rescue Puppet::ParseErrorWithIssue => detail detail.node = node.name Puppet.log_exception(detail) raise rescue => detail message = "#{detail} on node #{node.name}" Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end # Evaluates all added constructs, and validates the resulting catalog. # This can be called whenever a series of evaluation of puppet code strings # have reached a stable state (essentially that there are no relationships to # non-existing resources). # # Raises an error if validation fails. # def compile_additions evaluate_additions validate end # Evaluates added constructs that are lazily evaluated until all of them have been evaluated. # def evaluate_additions evaluate_generators finish end # Validates the current state of the catalog. # Does not cause evaluation of lazy constructs. def validate validate_catalog(CatalogValidator::FINAL) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/scope.rb
lib/puppet/parser/scope.rb
# frozen_string_literal: true # The scope class, which handles storing and retrieving variables and types and # such. require 'forwardable' require_relative '../../puppet/parser' require_relative '../../puppet/parser/templatewrapper' require_relative '../../puppet/parser/resource' # This class is part of the internal parser/evaluator/compiler functionality of Puppet. # It is passed between the various classes that participate in evaluation. # None of its methods are API except those that are clearly marked as such. # # @api public class Puppet::Parser::Scope extend Forwardable # Variables that always exist with nil value even if not set BUILT_IN_VARS = %w[module_name caller_module_name].freeze EMPTY_HASH = {}.freeze Puppet::Util.logmethods(self) include Puppet::Util::Errors attr_accessor :source, :resource attr_reader :compiler attr_accessor :parent # Hash of hashes of default values per type name attr_reader :defaults # Alias for `compiler.environment` def environment @compiler.environment end # Alias for `compiler.catalog` def catalog @compiler.catalog end # Abstract base class for LocalScope and MatchScope # class Ephemeral attr_reader :parent def initialize(parent = nil) @parent = parent end def is_local_scope? false end def [](name) if @parent @parent[name] end end def include?(name) (@parent and @parent.include?(name)) end def bound?(name) false end def add_entries_to(target = {}, include_undef = false) @parent.add_entries_to(target, include_undef) unless @parent.nil? # do not include match data ($0-$n) target end end class LocalScope < Ephemeral def initialize(parent = nil) super parent @symbols = {} end def [](name) val = @symbols[name] val.nil? && !@symbols.include?(name) ? super : val end def is_local_scope? true end def []=(name, value) @symbols[name] = value end def include?(name) bound?(name) || super end def delete(name) @symbols.delete(name) end def bound?(name) @symbols.include?(name) end def add_entries_to(target = {}, include_undef = false) super @symbols.each do |k, v| if (v == :undef || v.nil?) && !include_undef target.delete(k) else target[k] = v end end target end end class MatchScope < Ephemeral attr_accessor :match_data def initialize(parent = nil, match_data = nil) super parent @match_data = match_data end def is_local_scope? false end def [](name) if bound?(name) @match_data[name.to_i] else super end end def include?(name) bound?(name) or super end def bound?(name) # A "match variables" scope reports all numeric variables to be bound if the scope has # match_data. Without match data the scope is transparent. # @match_data && name =~ /^\d+$/ end def []=(name, value) # TODO: Bad choice of exception raise Puppet::ParseError, _("Numerical variables cannot be changed. Attempt to set $%{name}") % { name: name } end def delete(name) # TODO: Bad choice of exception raise Puppet::ParseError, _("Numerical variables cannot be deleted: Attempt to delete: $%{name}") % { name: name } end def add_entries_to(target = {}, include_undef = false) # do not include match data ($0-$n) super end end # @api private class ParameterScope < Ephemeral class Access attr_accessor :value def assigned? instance_variable_defined?(:@value) end end # A parameter default must be evaluated using a special scope. The scope that is given to this method must # have a `ParameterScope` as its last ephemeral scope. This method will then push a `MatchScope` while the # given `expression` is evaluated. The method will catch any throw of `:unevaluated_parameter` and produce # an error saying that the evaluated parameter X tries to access the unevaluated parameter Y. # # @param name [String] the name of the currently evaluated parameter # @param expression [Puppet::Parser::AST] the expression to evaluate # @param scope [Puppet::Parser::Scope] a scope where a `ParameterScope` has been pushed # @return [Object] the result of the evaluation # # @api private def evaluate3x(name, expression, scope) scope.with_guarded_scope do bad = catch(:unevaluated_parameter) do scope.new_match_scope(nil) return as_read_only { expression.safeevaluate(scope) } end parameter_reference_failure(name, bad) end end def evaluate(name, expression, scope, evaluator) scope.with_guarded_scope do bad = catch(:unevaluated_parameter) do scope.new_match_scope(nil) return as_read_only { evaluator.evaluate(expression, scope) } end parameter_reference_failure(name, bad) end end def parameter_reference_failure(from, to) # Parameters are evaluated in the order they have in the @params hash. keys = @params.keys raise Puppet::Error, _("%{callee}: expects a value for parameter $%{to}") % { callee: @callee_name, to: to } if keys.index(to) < keys.index(from) raise Puppet::Error, _("%{callee}: default expression for $%{from} tries to illegally access not yet evaluated $%{to}") % { callee: @callee_name, from: from, to: to } end private :parameter_reference_failure def initialize(parent, callee_name, param_names) super(parent) @callee_name = callee_name @params = {} param_names.each { |name| @params[name] = Access.new } end def [](name) access = @params[name] return super if access.nil? throw(:unevaluated_parameter, name) unless access.assigned? access.value end def []=(name, value) raise Puppet::Error, _("Attempt to assign variable %{name} when evaluating parameters") % { name: name } if @read_only @params[name] ||= Access.new @params[name].value = value end def bound?(name) @params.include?(name) end def include?(name) @params.include?(name) || super end def is_local_scope? true end def as_read_only read_only = @read_only @read_only = true begin yield ensure @read_only = read_only end end def to_hash @params.select { |_, access| access.assigned? }.transform_values(&:value) end end # Returns true if the variable of the given name has a non nil value. # TODO: This has vague semantics - does the variable exist or not? # use ['name'] to get nil or value, and if nil check with exist?('name') # this include? is only useful because of checking against the boolean value false. # def include?(name) catch(:undefined_variable) { return !self[name].nil? } false end # Returns true if the variable of the given name is set to any value (including nil) # # @return [Boolean] if variable exists or not # def exist?(name) # Note !! ensure the answer is boolean !!if name =~ /^(.*)::(.+)$/ class_name = ::Regexp.last_match(1) variable_name = ::Regexp.last_match(2) return true if class_name == '' && BUILT_IN_VARS.include?(variable_name) # lookup class, but do not care if it is not evaluated since that will result # in it not existing anyway. (Tests may run with just scopes and no evaluated classes which # will result in class_scope for "" not returning topscope). klass = find_hostclass(class_name) other_scope = klass.nil? ? nil : class_scope(klass) if other_scope.nil? class_name == '' ? compiler.topscope.exist?(variable_name) : false else other_scope.exist?(variable_name) end else # rubocop:disable Layout/ElseAlignment next_scope = inherited_scope || enclosing_scope effective_symtable(true).include?(name) || next_scope && next_scope.exist?(name) || BUILT_IN_VARS.include?(name) end # rubocop:disable Layout/EndAlignment end # Returns true if the given name is bound in the current (most nested) scope for assignments. # def bound?(name) # Do not look in ephemeral (match scope), the semantics is to answer if an assignable variable is bound effective_symtable(false).bound?(name) end # Is the value true? This allows us to control the definition of truth # in one place. def self.true?(value) case value when '' false when :undef false else !!value end end # Coerce value to a number, or return `nil` if it isn't one. def self.number?(value) case value when Numeric value when /^-?\d+(:?\.\d+|(:?\.\d+)?e\d+)$/ value.to_f when /^0x[0-9a-f]+$/i value.to_i(16) when /^0[0-7]+$/ value.to_i(8) when /^-?\d+$/ value.to_i else nil end end def find_hostclass(name) environment.known_resource_types.find_hostclass(name) end def find_definition(name) environment.known_resource_types.find_definition(name) end def find_global_scope # walk upwards until first found node_scope or top_scope if is_nodescope? || is_topscope? self else next_scope = inherited_scope || enclosing_scope if next_scope.nil? # this happens when testing, and there is only a single test scope and no link to any # other scopes self else next_scope.find_global_scope() end end end def findresource(type, title = nil) @compiler.catalog.resource(type, title) end # Initialize our new scope. Defaults to having no parent. def initialize(compiler, source: nil, resource: nil) if compiler.is_a? Puppet::Parser::AbstractCompiler @compiler = compiler else raise Puppet::DevError, _("you must pass a compiler instance to a new scope object") end @source = source @resource = resource extend_with_functions_module # The symbol table for this scope. This is where we store variables. # @symtable = Ephemeral.new(nil, true) @symtable = LocalScope.new(nil) @ephemeral = [MatchScope.new(@symtable, nil)] # All of the defaults set for types. It's a hash of hashes, # with the first key being the type, then the second key being # the parameter. @defaults = Hash.new { |dhash, type| dhash[type] = {} } # The table for storing class singletons. This will only actually # be used by top scopes and node scopes. @class_scopes = {} end # Store the fact that we've evaluated a class, and store a reference to # the scope in which it was evaluated, so that we can look it up later. def class_set(name, scope) if parent parent.class_set(name, scope) else @class_scopes[name] = scope end end # Return the scope associated with a class. This is just here so # that subclasses can set their parent scopes to be the scope of # their parent class, and it's also used when looking up qualified # variables. def class_scope(klass) # They might pass in either the class or class name k = klass.respond_to?(:name) ? klass.name : klass @class_scopes[k] || (parent && parent.class_scope(k)) end # Collect all of the defaults set at any higher scopes. # This is a different type of lookup because it's # additive -- it collects all of the defaults, with defaults # in closer scopes overriding those in later scopes. # # The lookupdefaults searches in the order: # # * inherited # * contained (recursive) # * self # def lookupdefaults(type) values = {} # first collect the values from the parents if parent parent.lookupdefaults(type).each { |var, value| values[var] = value } end # then override them with any current values # this should probably be done differently if @defaults.include?(type) @defaults[type].each { |var, value| values[var] = value } end values end # Check if the given value is a known default for the given type # def is_default?(type, key, value) defaults_for_type = @defaults[type] unless defaults_for_type.nil? default_param = defaults_for_type[key] return true if !default_param.nil? && value == default_param.value end !parent.nil? && parent.is_default?(type, key, value) end # Look up a defined type. def lookuptype(name) # This happens a lot, avoid making a call to make a call krt = environment.known_resource_types krt.find_definition(name) || krt.find_hostclass(name) end def undef_as(x, v) if v.nil? or v == :undef x else v end end # Lookup a variable within this scope using the Puppet language's # scoping rules. Variables can be qualified using just as in a # manifest. # # @param [String] name the variable name to lookup # @param [Hash] hash of options, only internal code should give this # @param [Boolean] if resolution is of the leaf of a qualified name - only internal code should give this # @return Object the value of the variable, or if not found; nil if `strict_variables` is false, and thrown :undefined_variable otherwise # # @api public def lookupvar(name, options = EMPTY_HASH) unless name.is_a? String raise Puppet::ParseError, _("Scope variable name %{name} is a %{klass}, not a string") % { name: name.inspect, klass: name.class } end # If name has '::' in it, it is resolved as a qualified variable unless (idx = name.index('::')).nil? # Always drop leading '::' if present as that is how the values are keyed. return lookup_qualified_variable(idx == 0 ? name[2..] : name, options) end # At this point, search is for a non qualified (simple) name table = @ephemeral.last val = table[name] return val unless val.nil? && !table.include?(name) next_scope = inherited_scope || enclosing_scope if next_scope next_scope.lookupvar(name, options) else variable_not_found(name) end end UNDEFINED_VARIABLES_KIND = 'undefined_variables' # The exception raised when a throw is uncaught is different in different versions # of ruby. In >=2.2.0 it is UncaughtThrowError (which did not exist prior to this) # UNCAUGHT_THROW_EXCEPTION = defined?(UncaughtThrowError) ? UncaughtThrowError : ArgumentError def variable_not_found(name, reason = nil) # Built in variables and numeric variables always exist if BUILT_IN_VARS.include?(name) || name =~ Puppet::Pops::Patterns::NUMERIC_VAR_NAME return nil end begin throw(:undefined_variable, reason) rescue UNCAUGHT_THROW_EXCEPTION case Puppet[:strict] when :off # do nothing when :warning Puppet.warn_once(UNDEFINED_VARIABLES_KIND, _("Variable: %{name}") % { name: name }, _("Undefined variable '%{name}'; %{reason}") % { name: name, reason: reason }) when :error if Puppet.lookup(:avoid_hiera_interpolation_errors) { false } Puppet.warn_once(UNDEFINED_VARIABLES_KIND, _("Variable: %{name}") % { name: name }, _("Interpolation failed with '%{name}', but compilation continuing; %{reason}") % { name: name, reason: reason }) else raise ArgumentError, _("Undefined variable '%{name}'; %{reason}") % { name: name, reason: reason } end end end nil end # Retrieves the variable value assigned to the name given as an argument. The name must be a String, # and namespace can be qualified with '::'. The value is looked up in this scope, its parent scopes, # or in a specific visible named scope. # # @param varname [String] the name of the variable (may be a qualified name using `(ns'::')*varname` # @param options [Hash] Additional options, not part of api. # @return [Object] the value assigned to the given varname # @see #[]= # @api public # def [](varname, options = EMPTY_HASH) lookupvar(varname, options) end # The class scope of the inherited thing of this scope's resource. # # @return [Puppet::Parser::Scope] The scope or nil if there is not an inherited scope def inherited_scope if resource && resource.type == TYPENAME_CLASS && !resource.resource_type.parent.nil? qualified_scope(resource.resource_type.parent) else nil end end # The enclosing scope (topscope or nodescope) of this scope. # The enclosing scopes are produced when a class or define is included at # some point. The parent scope of the included class or define becomes the # scope in which it was included. The chain of parent scopes is followed # until a node scope or the topscope is found # # @return [Puppet::Parser::Scope] The scope or nil if there is no enclosing scope def enclosing_scope if has_enclosing_scope? if parent.is_topscope? || parent.is_nodescope? parent else parent.enclosing_scope end end end def is_classscope? resource && resource.type == TYPENAME_CLASS end def is_nodescope? resource && resource.type == TYPENAME_NODE end def is_topscope? equal?(@compiler.topscope) end # @api private def lookup_qualified_variable(fqn, options) table = @compiler.qualified_variables val = table[fqn] return val if !val.nil? || table.include?(fqn) # not found - search inherited scope for class leaf_index = fqn.rindex('::') unless leaf_index.nil? leaf_name = fqn[(leaf_index + 2)..] class_name = fqn[0, leaf_index] begin qs = qualified_scope(class_name) unless qs.nil? return qs.get_local_variable(leaf_name) if qs.has_local_variable?(leaf_name) iscope = qs.inherited_scope return lookup_qualified_variable("#{iscope.source.name}::#{leaf_name}", options) unless iscope.nil? end rescue RuntimeError => e # because a failure to find the class, or inherited should be reported against given name return handle_not_found(class_name, leaf_name, options, e.message) end end # report with leading '::' by using empty class_name handle_not_found('', fqn, options) end # @api private def has_local_variable?(name) @ephemeral.last.include?(name) end # @api private def get_local_variable(name) @ephemeral.last[name] end def handle_not_found(class_name, variable_name, position, reason = nil) unless Puppet[:strict_variables] # Do not issue warning if strict variables are on, as an error will be raised by variable_not_found location = if position[:lineproc] Puppet::Util::Errors.error_location_with_space(nil, position[:lineproc].call) else Puppet::Util::Errors.error_location_with_space(position[:file], position[:line]) end variable_not_found("#{class_name}::#{variable_name}", "#{reason}#{location}") return nil end variable_not_found("#{class_name}::#{variable_name}", reason) end def has_enclosing_scope? !parent.nil? end private :has_enclosing_scope? def qualified_scope(classname) klass = find_hostclass(classname) raise _("class %{classname} could not be found") % { classname: classname } unless klass kscope = class_scope(klass) raise _("class %{classname} has not been evaluated") % { classname: classname } unless kscope kscope end private :qualified_scope # Returns a Hash containing all variables and their values, optionally (and # by default) including the values defined in parent. Local values # shadow parent values. Ephemeral scopes for match results ($0 - $n) are not included. # Optionally include the variables that are explicitly set to `undef`. # def to_hash(recursive = true, include_undef = false) if recursive and has_enclosing_scope? target = enclosing_scope.to_hash(recursive) unless (inherited = inherited_scope).nil? target.merge!(inherited.to_hash(recursive)) end else target = Hash.new end # add all local scopes @ephemeral.last.add_entries_to(target, include_undef) target end # Create a new scope and set these options. def newscope(options = {}) compiler.newscope(self, options) end def parent_module_name return nil unless @parent && @parent.source @parent.source.module_name end # Set defaults for a type. The typename should already be downcased, # so that the syntax is isolated. We don't do any kind of type-checking # here; instead we let the resource do it when the defaults are used. def define_settings(type, params) table = @defaults[type] # if we got a single param, it'll be in its own array params = [params] unless params.is_a?(Array) params.each { |param| if table.include?(param.name) raise Puppet::ParseError.new(_("Default already defined for %{type} { %{param} }; cannot redefine") % { type: type, param: param.name }, param.file, param.line) end table[param.name] = param } end # Merge all settings for the given _env_name_ into this scope # @param env_name [Symbol] the name of the environment # @param set_in_this_scope [Boolean] if the settings variables should also be set in this instance of scope def merge_settings(env_name, set_in_this_scope = true) settings = Puppet.settings table = effective_symtable(false) global_table = compiler.qualified_variables all_local = {} settings.each_key do |name| next if :name == name key = name.to_s value = transform_setting(settings.value_sym(name, env_name)) if set_in_this_scope table[key] = value end all_local[key] = value # also write the fqn into global table for direct lookup global_table["settings::#{key}"] = value end # set the 'all_local' - a hash of all settings global_table["settings::all_local"] = all_local nil end def transform_setting(val) case val when String, Numeric, true, false, nil val when Array val.map { |entry| transform_setting(entry) } when Hash result = {} val.each { |k, v| result[transform_setting(k)] = transform_setting(v) } result else # not ideal, but required as there are settings values that are special :undef == val ? nil : val.to_s end end private :transform_setting VARNAME_TRUSTED = 'trusted' VARNAME_FACTS = 'facts' VARNAME_SERVER_FACTS = 'server_facts' RESERVED_VARIABLE_NAMES = [VARNAME_TRUSTED, VARNAME_FACTS].freeze TYPENAME_CLASS = 'Class' TYPENAME_NODE = 'Node' # Set a variable in the current scope. This will override settings # in scopes above, but will not allow variables in the current scope # to be reassigned. # It's preferred that you use self[]= instead of this; only use this # when you need to set options. def setvar(name, value, options = EMPTY_HASH) if name =~ /^[0-9]+$/ raise Puppet::ParseError, _("Cannot assign to a numeric match result variable '$%{name}'") % { name: name } # unless options[:ephemeral] end unless name.is_a? String raise Puppet::ParseError, _("Scope variable name %{name} is a %{class_type}, not a string") % { name: name.inspect, class_type: name.class } end # Check for reserved variable names if (name == VARNAME_TRUSTED || name == VARNAME_FACTS) && !options[:privileged] raise Puppet::ParseError, _("Attempt to assign to a reserved variable name: '%{name}'") % { name: name } end # Check for server_facts reserved variable name if name == VARNAME_SERVER_FACTS && !options[:privileged] raise Puppet::ParseError, _("Attempt to assign to a reserved variable name: '%{name}'") % { name: name } end table = effective_symtable(options[:ephemeral]) if table.bound?(name) error = Puppet::ParseError.new(_("Cannot reassign variable '$%{name}'") % { name: name }) error.file = options[:file] if options[:file] error.line = options[:line] if options[:line] raise error end table[name] = value # Assign the qualified name in the environment # Note that Settings scope has a source set to Boolean true. # # Only meaningful to set a fqn globally if table to assign to is the top of the scope's ephemeral stack if @symtable.equal?(table) if is_topscope? # the scope name is '::' compiler.qualified_variables[name] = value elsif source.is_a?(Puppet::Resource::Type) && source.type == :hostclass # the name is the name of the class sourcename = source.name compiler.qualified_variables["#{sourcename}::#{name}"] = value end end value end def set_trusted(hash) setvar('trusted', deep_freeze(hash), :privileged => true) end def set_facts(hash) setvar('facts', deep_freeze(hash), :privileged => true) end def set_server_facts(hash) setvar('server_facts', deep_freeze(hash), :privileged => true) end # Deeply freezes the given object. The object and its content must be of the types: # Array, Hash, Numeric, Boolean, Regexp, NilClass, or String. All other types raises an Error. # (i.e. if they are assignable to Puppet::Pops::Types::Data type). # def deep_freeze(object) case object when Array object.each { |v| deep_freeze(v) } object.freeze when Hash object.each { |k, v| deep_freeze(k); deep_freeze(v) } object.freeze when NilClass, Numeric, TrueClass, FalseClass # do nothing when String object.freeze else raise Puppet::Error, _("Unsupported data type: '%{klass}'") % { klass: object.class } end object end private :deep_freeze # Return the effective "table" for setting variables. # This method returns the first ephemeral "table" that acts as a local scope, or this # scope's symtable. If the parameter `use_ephemeral` is true, the "top most" ephemeral "table" # will be returned (irrespective of it being a match scope or a local scope). # # @param use_ephemeral [Boolean] whether the top most ephemeral (of any kind) should be used or not def effective_symtable(use_ephemeral) s = @ephemeral[-1] return s || @symtable if use_ephemeral while s && !s.is_local_scope?() s = s.parent end s || @symtable end # Sets the variable value of the name given as an argument to the given value. The value is # set in the current scope and may shadow a variable with the same name in a visible outer scope. # It is illegal to re-assign a variable in the same scope. It is illegal to set a variable in some other # scope/namespace than the scope passed to a method. # # @param varname [String] The variable name to which the value is assigned. Must not contain `::` # @param value [String] The value to assign to the given variable name. # @param options [Hash] Additional options, not part of api and no longer used. # # @api public # def []=(varname, value, _ = nil) setvar(varname, value) end # Used mainly for logging def to_s # As this is used for logging, this should really not be done in this class at all... return "Scope(#{@resource})" unless @resource.nil? # For logging of function-scope - it is now showing the file and line. detail = Puppet::Pops::PuppetStack.top_of_stack return "Scope()" if detail.empty? # shorten the path if possible path = detail[0] env_path = nil env_path = environment.configuration.path_to_env unless environment.nil? || environment.configuration.nil? # check module paths first since they may be in the environment (i.e. they are longer) module_path = environment.full_modulepath.detect { |m_path| path.start_with?(m_path) } if module_path path = "<module>" + path[module_path.length..] elsif env_path && path && path.start_with?(env_path) path = "<env>" + path[env_path.length..] end # Make the output appear as "Scope(path, line)" "Scope(#{[path, detail[1]].join(', ')})" end alias_method :inspect, :to_s # Pop ephemeral scopes up to level and return them # # @param level [Integer] a positive integer # @return [Array] the removed ephemeral scopes # @api private def pop_ephemerals(level) @ephemeral.pop(@ephemeral.size - level) end # Push ephemeral scopes onto the ephemeral scope stack # @param ephemeral_scopes [Array] # @api private def push_ephemerals(ephemeral_scopes) ephemeral_scopes.each { |ephemeral_scope| @ephemeral.push(ephemeral_scope) } unless ephemeral_scopes.nil? end def ephemeral_level @ephemeral.size end # TODO: Who calls this? def new_ephemeral(local_scope = false) if local_scope @ephemeral.push(LocalScope.new(@ephemeral.last)) else @ephemeral.push(MatchScope.new(@ephemeral.last, nil)) end end # Execute given block in global scope with no ephemerals present # # @yieldparam [Scope] global_scope the global and ephemeral less scope # @return [Object] the return of the block # # @api private def with_global_scope(&block) find_global_scope.without_ephemeral_scopes(&block) end # Execute given block with a ephemeral scope containing the given variables # @api private def with_local_scope(scope_variables) local = LocalScope.new(@ephemeral.last) scope_variables.each_pair { |k, v| local[k] = v } @ephemeral.push(local) begin yield(self) ensure @ephemeral.pop end end # Execute given block with all ephemeral popped from the ephemeral stack # # @api private def without_ephemeral_scopes save_ephemeral = @ephemeral begin @ephemeral = [@symtable] yield(self) ensure @ephemeral = save_ephemeral end end # Nests a parameter scope # @param [String] callee_name the name of the function, template, or resource that defines the parameters # @param [Array<String>] param_names list of parameter names # @yieldparam [ParameterScope] param_scope the nested scope # @api private def with_parameter_scope(callee_name, param_names) param_scope = ParameterScope.new(@ephemeral.last, callee_name, param_names) with_guarded_scope do @ephemeral.push(param_scope) yield(param_scope) end end # Execute given block and ensure that ephemeral level is restored # # @return [Object] the return of the block # # @api private def with_guarded_scope elevel = ephemeral_level begin yield ensure pop_ephemerals(elevel) end end # Sets match data in the most nested scope (which always is a MatchScope), it clobbers match data already set there # def set_match_data(match_data) @ephemeral.last.match_data = match_data end # Nests a match data scope def new_match_scope(match_data) @ephemeral.push(MatchScope.new(@ephemeral.last, match_data)) end def ephemeral_from(match, file = nil, line = nil) case match when Hash # Create local scope ephemeral and set all values from hash new_ephemeral(true) match.each { |k, v| setvar(k, v, :file => file, :line => line, :ephemeral => true) } # Must always have an inner match data scope (that starts out as transparent) # In 3x slightly wasteful, since a new nested scope is created for a match # (TODO: Fix that problem) new_ephemeral(false) else raise(ArgumentError, _("Invalid regex match data. Got a %{klass}") % { klass: match.class }) unless match.is_a?(MatchData) # Create a match ephemeral and set values from match data new_match_scope(match) end end # @api private def find_resource_type(type) raise Puppet::DevError, _("Scope#find_resource_type() is no longer supported, use Puppet::Pops::Evaluator::Runtime3ResourceSupport instead") end # @api private def find_builtin_resource_type(type) raise Puppet::DevError, _("Scope#find_builtin_resource_type() is no longer supported, use Puppet::Pops::Evaluator::Runtime3ResourceSupport instead") end # @api private def find_defined_resource_type(type)
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/parser_factory.rb
lib/puppet/parser/parser_factory.rb
# frozen_string_literal: true module Puppet; end module Puppet::Parser # The ParserFactory makes selection of parser possible. # Currently, it is possible to switch between two different parsers: # * classic_parser, the parser in 3.1 # * eparser, the Expression Based Parser # class ParserFactory # Produces a parser instance for the given environment def self.parser evaluating_parser end # Creates an instance of an E4ParserAdapter that adapts an # EvaluatingParser to the 3x way of parsing. # def self.evaluating_parser unless defined?(Puppet::Parser::E4ParserAdapter) require_relative '../../puppet/parser/e4_parser_adapter' require_relative '../../puppet/pops/parser/code_merger' end E4ParserAdapter.new end def self.code_merger Puppet::Pops::Parser::CodeMerger.new end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/type_loader.rb
lib/puppet/parser/type_loader.rb
# frozen_string_literal: true require 'find' require 'forwardable' require_relative '../../puppet/parser/parser_factory' class Puppet::Parser::TypeLoader extend Forwardable class TypeLoaderError < StandardError; end # Import manifest files that match a given file glob pattern. # # @param pattern [String] the file glob to apply when determining which files # to load # @param dir [String] base directory to use when the file is not # found in a module # @api private def import(pattern, dir) modname, files = Puppet::Parser::Files.find_manifests_in_modules(pattern, environment) if files.empty? abspat = File.expand_path(pattern, dir) file_pattern = abspat + (File.extname(abspat).empty? ? '.pp' : '') files = Dir.glob(file_pattern).uniq.reject { |f| FileTest.directory?(f) } modname = nil if files.empty? raise_no_files_found(pattern) end end load_files(modname, files) end # Load all of the manifest files in all known modules. # @api private def import_all # And then load all files from each module, but (relying on system # behavior) only load files from the first module of a given name. E.g., # given first/foo and second/foo, only files from first/foo will be loaded. environment.modules.each do |mod| load_files(mod.name, mod.all_manifests) end end def_delegator :environment, :known_resource_types def initialize(env) self.environment = env end def environment @environment end def environment=(env) if env.is_a?(String) or env.is_a?(Symbol) @environment = Puppet.lookup(:environments).get!(env) else @environment = env end end # Try to load the object with the given fully qualified name. def try_load_fqname(type, fqname) return nil if fqname == "" # special-case main. files_to_try_for(fqname).each do |filename| imported_types = import_from_modules(filename) result = imported_types.find { |t| t.type == type and t.name == fqname } if result Puppet.debug { "Automatically imported #{fqname} from #{filename} into #{environment}" } return result end rescue TypeLoaderError # I'm not convinced we should just drop these errors, but this # preserves existing behaviours. end # Nothing found. nil end def parse_file(file) Puppet.debug { "importing '#{file}' in environment #{environment}" } parser = Puppet::Parser::ParserFactory.parser parser.file = file parser.parse end private def import_from_modules(pattern) modname, files = Puppet::Parser::Files.find_manifests_in_modules(pattern, environment) if files.empty? raise_no_files_found(pattern) end load_files(modname, files) end def raise_no_files_found(pattern) raise TypeLoaderError, _("No file(s) found for import of '%{pattern}'") % { pattern: pattern } end def load_files(modname, files) @loaded ||= {} loaded_asts = [] files.reject { |file| @loaded[file] }.each do |file| # The squelch_parse_errors use case is for parsing for the purpose of searching # for information and it should not abort. # There is currently one user in indirector/resourcetype/parser # if Puppet.lookup(:squelch_parse_errors) { false } begin loaded_asts << parse_file(file) rescue => e # Resume from errors so that all parseable files may # still be parsed. Mark this file as loaded so that # it would not be parsed next time (handle it as if # it was successfully parsed). Puppet.debug { "Unable to parse '#{file}': #{e.message}" } end else loaded_asts << parse_file(file) end @loaded[file] = true end loaded_asts.collect do |ast| known_resource_types.import_ast(ast, modname) end.flatten end # Return a list of all file basenames that should be tried in order # to load the object with the given fully qualified name. def files_to_try_for(qualified_name) qualified_name.split('::').inject([]) do |paths, name| add_path_for_name(paths, name) end end def add_path_for_name(paths, name) if paths.empty? [name] else paths.unshift(File.join(paths.first, name)) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions.rb
lib/puppet/parser/functions.rb
# frozen_string_literal: true require_relative '../../puppet/util/autoload' require_relative '../../puppet/parser/scope' require_relative '../../puppet/pops/adaptable' require_relative '../../puppet/concurrent/lock' # A module for managing parser functions. Each specified function # is added to a central module that then gets included into the Scope # class. # # @api public module Puppet::Parser::Functions Environment = Puppet::Node::Environment class << self include Puppet::Util end # Reset the list of loaded functions. # # @api private def self.reset # Runs a newfunction to create a function for each of the log levels root_env = Puppet.lookup(:root_environment) AnonymousModuleAdapter.clear(root_env) Puppet::Util::Log.levels.each do |level| newfunction(level, :environment => root_env, :doc => "Log a message on the server at level #{level}.") do |vals| send(level, vals.join(" ")) end end end class AutoloaderDelegate attr_reader :delegatee def initialize @delegatee = Puppet::Util::Autoload.new(self, "puppet/parser/functions") end def loadall(env = Puppet.lookup(:current_environment)) if Puppet[:strict] != :off Puppet.warn_once('deprecations', 'Puppet::Parser::Functions#loadall', _("The method 'Puppet::Parser::Functions.autoloader#loadall' is deprecated in favor of using 'Scope#call_function'.")) end @delegatee.loadall(env) end def load(name, env = Puppet.lookup(:current_environment)) if Puppet[:strict] != :off Puppet.warn_once('deprecations', "Puppet::Parser::Functions#load('#{name}')", _("The method 'Puppet::Parser::Functions.autoloader#load(\"%{name}\")' is deprecated in favor of using 'Scope#call_function'.") % { name: name }) end @delegatee.load(name, env) end def loaded?(name) if Puppet[:strict] != :off Puppet.warn_once('deprecations', "Puppet::Parser::Functions.loaded?('#{name}')", _("The method 'Puppet::Parser::Functions.autoloader#loaded?(\"%{name}\")' is deprecated in favor of using 'Scope#call_function'.") % { name: name }) end @delegatee.loaded?(name) end end # Accessor for singleton autoloader # # @api private def self.autoloader @autoloader ||= AutoloaderDelegate.new end # An adapter that ties the anonymous module that acts as the container for all 3x functions to the environment # where the functions are created. This adapter ensures that the life-cycle of those functions doesn't exceed # the life-cycle of the environment. # # @api private class AnonymousModuleAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :module def self.create_adapter(env) adapter = super(env) adapter.module = Module.new do @metadata = {} def self.all_function_info @metadata end def self.get_function_info(name) @metadata[name] end def self.add_function_info(name, info) @metadata[name] = info end end adapter end end @environment_module_lock = Puppet::Concurrent::Lock.new # Get the module that functions are mixed into corresponding to an # environment # # @api private def self.environment_module(env) @environment_module_lock.synchronize do AnonymousModuleAdapter.adapt(env).module end end # Create a new Puppet DSL function. # # **The {newfunction} method provides a public API.** # # This method is used both internally inside of Puppet to define parser # functions. For example, template() is defined in # {file:lib/puppet/parser/functions/template.rb template.rb} using the # {newfunction} method. Third party Puppet modules such as # [stdlib](https://forge.puppetlabs.com/puppetlabs/stdlib) use this method to # extend the behavior and functionality of Puppet. # # See also [Docs: Custom # Functions](https://puppet.com/docs/puppet/5.5/lang_write_functions_in_puppet.html) # # @example Define a new Puppet DSL Function # >> Puppet::Parser::Functions.newfunction(:double, :arity => 1, # :doc => "Doubles an object, typically a number or string.", # :type => :rvalue) {|i| i[0]*2 } # => {:arity=>1, :type=>:rvalue, # :name=>"function_double", # :doc=>"Doubles an object, typically a number or string."} # # @example Invoke the double function from irb as is done in RSpec examples: # >> require 'puppet_spec/scope' # >> scope = PuppetSpec::Scope.create_test_scope_for_node('example') # => Scope() # >> scope.function_double([2]) # => 4 # >> scope.function_double([4]) # => 8 # >> scope.function_double([]) # ArgumentError: double(): Wrong number of arguments given (0 for 1) # >> scope.function_double([4,8]) # ArgumentError: double(): Wrong number of arguments given (2 for 1) # >> scope.function_double(["hello"]) # => "hellohello" # # @param [Symbol] name the name of the function represented as a ruby Symbol. # The {newfunction} method will define a Ruby method based on this name on # the parser scope instance. # # @param [Proc] block the block provided to the {newfunction} method will be # executed when the Puppet DSL function is evaluated during catalog # compilation. The arguments to the function will be passed as an array to # the first argument of the block. The return value of the block will be # the return value of the Puppet DSL function for `:rvalue` functions. # # @option options [:rvalue, :statement] :type (:statement) the type of function. # Either `:rvalue` for functions that return a value, or `:statement` for # functions that do not return a value. # # @option options [String] :doc ('') the documentation for the function. # This string will be extracted by documentation generation tools. # # @option options [Integer] :arity (-1) the # [arity](https://en.wikipedia.org/wiki/Arity) of the function. When # specified as a positive integer the function is expected to receive # _exactly_ the specified number of arguments. When specified as a # negative number, the function is expected to receive _at least_ the # absolute value of the specified number of arguments incremented by one. # For example, a function with an arity of `-4` is expected to receive at # minimum 3 arguments. A function with the default arity of `-1` accepts # zero or more arguments. A function with an arity of 2 must be provided # with exactly two arguments, no more and no less. Added in Puppet 3.1.0. # # @option options [Puppet::Node::Environment] :environment (nil) can # explicitly pass the environment we wanted the function added to. Only used # to set logging functions in root environment # # @return [Hash] describing the function. # # @api public def self.newfunction(name, options = {}, &block) name = name.intern environment = options[:environment] || Puppet.lookup(:current_environment) Puppet.warning _("Overwriting previous definition for function %{name}") % { name: name } if get_function(name, environment) arity = options[:arity] || -1 ftype = options[:type] || :statement unless ftype == :statement or ftype == :rvalue raise Puppet::DevError, _("Invalid statement type %{type}") % { type: ftype.inspect } end # the block must be installed as a method because it may use "return", # which is not allowed from procs. real_fname = "real_function_#{name}" environment_module(environment).send(:define_method, real_fname, &block) fname = "function_#{name}" env_module = environment_module(environment) env_module.send(:define_method, fname) do |*args| Puppet::Util::Profiler.profile(_("Called %{name}") % { name: name }, [:functions, name]) do if args[0].is_a? Array if arity >= 0 and args[0].size != arity raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for %{arity})") % { name: name, arg_count: args[0].size, arity: arity } elsif arity < 0 and args[0].size < (arity + 1).abs raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for minimum %{min_arg_count})") % { name: name, arg_count: args[0].size, min_arg_count: (arity + 1).abs } end r = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.convert_return(send(real_fname, args[0])) # avoid leaking aribtrary value if not being an rvalue function options[:type] == :rvalue ? r : nil else raise ArgumentError, _("custom functions must be called with a single array that contains the arguments. For example, function_example([1]) instead of function_example(1)") end end end func = { :arity => arity, :type => ftype, :name => fname } func[:doc] = options[:doc] if options[:doc] env_module.add_function_info(name, func) func end # Determine if a function is defined # # @param [Symbol] name the function # @param [Puppet::Node::Environment] environment the environment to find the function in # # @return [Symbol, false] The name of the function if it's defined, # otherwise false. # # @api public def self.function(name, environment = Puppet.lookup(:current_environment)) name = name.intern func = get_function(name, environment) unless func autoloader.delegatee.load(name, environment) func = get_function(name, environment) end if func func[:name] else false end end def self.functiondocs(environment = Puppet.lookup(:current_environment)) autoloader.delegatee.loadall(environment) ret = ''.dup merged_functions(environment).sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, hash| ret << "#{name}\n#{'-' * name.to_s.length}\n" if hash[:doc] ret << Puppet::Util::Docs.scrub(hash[:doc]) else ret << "Undocumented.\n" end ret << "\n\n- *Type*: #{hash[:type]}\n\n" end ret end # Determine whether a given function returns a value. # # @param [Symbol] name the function # @param [Puppet::Node::Environment] environment The environment to find the function in # @return [Boolean] whether it is an rvalue function # # @api public def self.rvalue?(name, environment = Puppet.lookup(:current_environment)) func = get_function(name, environment) func ? func[:type] == :rvalue : false end # Return the number of arguments a function expects. # # @param [Symbol] name the function # @param [Puppet::Node::Environment] environment The environment to find the function in # @return [Integer] The arity of the function. See {newfunction} for # the meaning of negative values. # # @api public def self.arity(name, environment = Puppet.lookup(:current_environment)) func = get_function(name, environment) func ? func[:arity] : -1 end class << self private def merged_functions(environment) root = environment_module(Puppet.lookup(:root_environment)) env = environment_module(environment) root.all_function_info.merge(env.all_function_info) end def get_function(name, environment) environment_module(environment).get_function_info(name.intern) || environment_module(Puppet.lookup(:root_environment)).get_function_info(name.intern) end end class Error def self.is4x(name) raise Puppet::ParseError, _("%{name}() can only be called using the 4.x function API. See Scope#call_function") % { name: name } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/abstract_compiler.rb
lib/puppet/parser/abstract_compiler.rb
# frozen_string_literal: true module Puppet::Parser::AbstractCompiler # Returns the catalog for a compilation. Must return a Puppet::Resource::Catalog or fail with an # error if the specific compiler does not support catalog operations. # def catalog raise Puppet::DevError("Class '#{self.class}' should have implemented 'catalog'") end # Returns the environment for the compilation # def environment raise Puppet::DevError("Class '#{self.class}' should have implemented 'environment'") end # Produces a new scope # This method is here if there are functions/logic that will call this for some other purpose than to create # a named scope for a class. It may not have to be here. (TODO) # def newscope(scope, options) raise Puppet::DevError("Class '#{self.class}' should have implemented 'newscope'") end # Returns a hash of all externally referenceable qualified variables # def qualified_variables raise Puppet::DevError("Class '#{self.class}' should have implemented 'qualified_variables'") end # Returns the top scope instance def topscope raise Puppet::DevError("Class '#{self.class}' should have implemented 'topscope'") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast.rb
lib/puppet/parser/ast.rb
# frozen_string_literal: true # The base class for the 3x "parse tree", now only used by the top level # constructs and the compiler. # Handles things like file name, line #, and also does the initialization # for all of the parameters of all of the child objects. # class Puppet::Parser::AST AST = Puppet::Parser::AST include Puppet::Util::Errors attr_accessor :parent, :scope, :file, :line, :pos def inspect "( #{self.class} #{self} #{@children.inspect} )" end # Evaluate the current object. Just a stub method, since the subclass # should override this method. def evaluate(scope) end # The version of the evaluate method that should be called, because it # correctly handles errors. It is critical to use this method because # it can enable you to catch the error where it happens, rather than # much higher up the stack. def safeevaluate(scope) # We duplicate code here, rather than using exceptwrap, because this # is called so many times during parsing. evaluate(scope) rescue Puppet::Pops::Evaluator::PuppetStopIteration => detail raise detail # # Only deals with StopIteration from the break() function as a general # # StopIteration is a general runtime problem # raise Puppet::ParseError.new(detail.message, detail.file, detail.line, detail) rescue Puppet::Error => detail raise adderrorcontext(detail) rescue => detail error = Puppet::ParseError.new(detail.to_s, nil, nil, detail) # We can't use self.fail here because it always expects strings, # not exceptions. raise adderrorcontext(error, detail) end def initialize(file: nil, line: nil, pos: nil) @file = file @line = line @pos = pos end end # And include all of the AST subclasses. require_relative 'ast/branch' require_relative 'ast/leaf' require_relative 'ast/block_expression' require_relative 'ast/hostclass' require_relative 'ast/node' require_relative 'ast/resource' require_relative 'ast/resource_instance' require_relative 'ast/resourceparam'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/resource/param.rb
lib/puppet/parser/resource/param.rb
# frozen_string_literal: true # The parameters we stick in Resources. class Puppet::Parser::Resource::Param include Puppet::Util include Puppet::Util::Errors attr_accessor :name, :value, :source, :add, :file, :line def initialize(name: nil, value: nil, source: nil, line: nil, file: nil, add: nil) @value = value @source = source @line = line @file = file @add = add unless name # This must happen after file and line are set to have them reported in the error self.fail(Puppet::ResourceError, "'name' is a required option for #{self.class}") end @name = name.intern end def line_to_i line ? Integer(line) : nil end def to_s "#{name} => #{value}" end def self.from_param(param, value) new_param = param.dup new_param.value = value new_param end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/shellquote.rb
lib/puppet/parser/functions/shellquote.rb
# frozen_string_literal: true # Copyright (C) 2009 Thomas Bellman # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of Thomas Bellman shall # not be used in advertising or otherwise to promote the sale, use or # other dealings in this Software without prior written authorization # from Thomas Bellman. Puppet::Parser::Functions.newfunction(:shellquote, :type => :rvalue, :arity => -1, :doc => "\ Quote and concatenate arguments for use in Bourne shell. Each argument is quoted separately, and then all are concatenated with spaces. If an argument is an array, the elements of that array is interpolated within the rest of the arguments; this makes it possible to have an array of arguments and pass that array to shellquote instead of having to specify each argument individually in the call. ") \ do |args| safe = 'a-zA-Z0-9@%_+=:,./-' # Safe unquoted dangerous = '!"`$\\' # Unsafe inside double quotes result = [] args.flatten.each do |word| if word.length != 0 and word.count(safe) == word.length result << word elsif word.count(dangerous) == 0 result << ('"' + word + '"') elsif word.count("'") == 0 result << ("'" + word + "'") else r = '"' word.each_byte do |c| r += "\\" if dangerous.include?(c.chr) r += c.chr end r += '"' result << r end end return result.join(" ") end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/tag.rb
lib/puppet/parser/functions/tag.rb
# frozen_string_literal: true # Tag the current scope with each passed name Puppet::Parser::Functions.newfunction(:tag, :arity => -2, :doc => "Add the specified tags to the containing class or definition. All contained objects will then acquire that tag, also. ") do |vals| if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'tag' } ) end resource.tag(*vals) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/find_file.rb
lib/puppet/parser/functions/find_file.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :find_file, :type => :rvalue, :arity => -2, :doc => <<~DOC Finds an existing file from a module and returns its path. The argument to this function should be a String as a `<MODULE NAME>/<FILE>` reference, which will search for `<FILE>` relative to a module's `files` directory. (For example, the reference `mysql/mysqltuner.pl` will search for the file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.) This function can also accept: * An absolute String path, which will check for the existence of a file from anywhere on disk. * Multiple String arguments, which will return the path of the **first** file found, skipping non existing files. * An array of string paths, which will return the path of the **first** file found from the given paths in the array, skipping non existing files. The function returns `undef` if none of the given paths were found - since 4.8.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('find_file') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/hiera_array.rb
lib/puppet/parser/functions/hiera_array.rb
# frozen_string_literal: true require 'hiera_puppet' module Puppet::Parser::Functions newfunction( :hiera_array, :type => :rvalue, :arity => -2, :doc => <<~DOC Finds all matches of a key throughout the hierarchy and returns them as a single flattened array of unique values. If any of the matched values are arrays, they're flattened and included in the results. This is called an [array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge). The `hiera_array` function takes up to three arguments, in this order: 1. A string key that Hiera searches for in the hierarchy. **Required**. 2. An optional default value to return if Hiera doesn't find anything matching the key. * If this argument isn't provided and this function results in a lookup failure, Puppet fails with a compilation error. 3. The optional name of an arbitrary [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup. * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy. **Example**: Using `hiera_array` ~~~ yaml # Assuming hiera.yaml # :hierarchy: # - web01.example.com # - common # Assuming common.yaml: # users: # - 'cdouglas = regular' # - 'efranklin = regular' # Assuming web01.example.com.yaml: # users: 'abarry = admin' ~~~ ~~~ puppet $allusers = hiera_array('users', undef) # $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"]. ~~~ You can optionally generate the default value with a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that takes one parameter. **Example**: Using `hiera_array` with a lambda ~~~ puppet # Assuming the same Hiera data as the previous example: $allusers = hiera_array('users') | $key | { "Key \'${key}\' not found" } # $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"]. # If hiera_array couldn't match its key, it would return the lambda result, # "Key 'users' not found". ~~~ `hiera_array` expects that all values returned will be strings or arrays. If any matched value is a hash, Puppet raises a type mismatch error. `hiera_array` is deprecated in favor of using `lookup` and will be removed in 6.0.0. See https://puppet.com/docs/puppet/#{Puppet.minor_version}/deprecated_language.html. Replace the calls as follows: | from | to | | ---- | ---| | hiera_array($key) | lookup($key, { 'merge' => 'unique' }) | | hiera_array($key, $default) | lookup($key, { 'default_value' => $default, 'merge' => 'unique' }) | | hiera_array($key, $default, $level) | override level not supported | Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced result must be post processed to get exactly the same result, for example using simple hash/array `+` or with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml. See [the documentation](https://puppet.com/docs/hiera/latest/puppet.html#hiera-lookup-functions) for more information about Hiera lookup functions. - Since 4.0.0 DOC ) do |*_args| Error.is4x('hiera_array') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/binary_file.rb
lib/puppet/parser/functions/binary_file.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :binary_file, :type => :rvalue, :arity => 1, :doc => <<~DOC Loads a binary file from a module or file system and returns its contents as a Binary. The argument to this function should be a `<MODULE NAME>/<FILE>` reference, which will load `<FILE>` from a module's `files` directory. (For example, the reference `mysql/mysqltuner.pl` will load the file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.) This function also accepts an absolute file path that allows reading binary file content from anywhere on disk. An error is raised if the given file does not exists. To search for the existence of files, use the `find_file()` function. - since 4.8.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('binary_file') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/reduce.rb
lib/puppet/parser/functions/reduce.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :reduce, :type => :rvalue, :arity => -3, :doc => <<~DOC Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) to every value in a data structure from the first argument, carrying over the returned value of each iteration, and returns the result of the lambda's final iteration. This lets you create a new value or data structure by combining values from the first argument's data structure. This function takes two mandatory arguments, in this order: 1. An array or hash the function will iterate over. 2. A lambda, which the function calls for each element in the first argument. It takes two mandatory parameters: 1. A memo value that is overwritten after each iteration with the iteration's result. 2. A second value that is overwritten after each iteration with the next value in the function's first argument. **Example**: Using the `reduce` function `$data.reduce |$memo, $value| { ... }` or `reduce($data) |$memo, $value| { ... }` You can also pass an optional "start memo" value as an argument, such as `start` below: `$data.reduce(start) |$memo, $value| { ... }` or `reduce($data, start) |$memo, $value| { ... }` When the first argument (`$data` in the above example) is an array, Puppet passes each of the data structure's values in turn to the lambda's parameters. When the first argument is a hash, Puppet converts each of the hash's values to an array in the form `[key, value]`. If you pass a start memo value, Puppet executes the lambda with the provided memo value and the data structure's first value. Otherwise, Puppet passes the structure's first two values to the lambda. Puppet calls the lambda for each of the data structure's remaining values. For each call, it passes the result of the previous call as the first parameter ($memo in the above examples) and the next value from the data structure as the second parameter ($value). If the structure has one value, Puppet returns the value and does not call the lambda. **Example**: Using the `reduce` function ~~~ puppet # Reduce the array $data, returning the sum of all values in the array. $data = [1, 2, 3] $sum = $data.reduce |$memo, $value| { $memo + $value } # $sum contains 6 # Reduce the array $data, returning the sum of a start memo value and all values in the # array. $data = [1, 2, 3] $sum = $data.reduce(4) |$memo, $value| { $memo + $value } # $sum contains 10 # Reduce the hash $data, returning the sum of all values and concatenated string of all # keys. $data = {a => 1, b => 2, c => 3} $combine = $data.reduce |$memo, $value| { $string = "${memo[0]}${value[0]}" $number = $memo[1] + $value[1] [$string, $number] } # $combine contains [abc, 6] ~~~ **Example**: Using the `reduce` function with a start memo and two-parameter lambda ~~~ puppet # Reduce the array $data, returning the sum of all values in the array and starting # with $memo set to an arbitrary value instead of $data's first value. $data = [1, 2, 3] $sum = $data.reduce(4) |$memo, $value| { $memo + $value } # At the start of the lambda's first iteration, $memo contains 4 and $value contains 1. # After all iterations, $sum contains 10. # Reduce the hash $data, returning the sum of all values and concatenated string of # all keys, and starting with $memo set to an arbitrary array instead of $data's first # key-value pair. $data = {a => 1, b => 2, c => 3} $combine = $data.reduce( [d, 4] ) |$memo, $value| { $string = "${memo[0]}${value[0]}" $number = $memo[1] + $value[1] [$string, $number] } # At the start of the lambda's first iteration, $memo contains [d, 4] and $value # contains [a, 1]. # $combine contains [dabc, 10] ~~~ **Example**: Using the `reduce` function to reduce a hash of hashes ~~~ puppet # Reduce a hash of hashes $data, merging defaults into the inner hashes. $data = { 'connection1' => { 'username' => 'user1', 'password' => 'pass1', }, 'connection_name2' => { 'username' => 'user2', 'password' => 'pass2', }, } $defaults = { 'maxActive' => '20', 'maxWait' => '10000', 'username' => 'defaultuser', 'password' => 'defaultpass', } $merged = $data.reduce( {} ) |$memo, $x| { $memo + { $x[0] => $defaults + $data[$x[0]] } } # At the start of the lambda's first iteration, $memo is set to {}, and $x is set to # the first [key, value] tuple. The key in $data is, therefore, given by $x[0]. In # subsequent rounds, $memo retains the value returned by the expression, i.e. # $memo + { $x[0] => $defaults + $data[$x[0]] }. ~~~ - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('reduce') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/slice.rb
lib/puppet/parser/functions/slice.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :slice, :type => :rvalue, :arity => -3, :doc => <<~DOC This function takes two mandatory arguments: the first should be an array or hash, and the second specifies the number of elements to include in each slice. When the first argument is a hash, each key value pair is counted as one. For example, a slice size of 2 will produce an array of two arrays with key, and value. $a.slice(2) |$entry| { notice "first ${$entry[0]}, second ${$entry[1]}" } $a.slice(2) |$first, $second| { notice "first ${first}, second ${second}" } The function produces a concatenated result of the slices. slice([1,2,3,4,5,6], 2) # produces [[1,2], [3,4], [5,6]] slice(Integer[1,6], 2) # produces [[1,2], [3,4], [5,6]] slice(4,2) # produces [[0,1], [2,3]] slice('hello',2) # produces [[h, e], [l, l], [o]] You can also optionally pass a lambda to slice. $a.slice($n) |$x| { ... } slice($a) |$x| { ... } The lambda should have either one parameter (receiving an array with the slice), or the same number of parameters as specified by the slice size (each parameter receiving its part of the slice). If there are fewer remaining elements than the slice size for the last slice, it will contain the remaining elements. If the lambda has multiple parameters, excess parameters are set to undef for an array, or to empty arrays for a hash. $a.slice(2) |$first, $second| { ... } - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('slice') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/include.rb
lib/puppet/parser/functions/include.rb
# frozen_string_literal: true # Include the specified classes Puppet::Parser::Functions.newfunction(:include, :arity => -2, :doc => "Declares one or more classes, causing the resources in them to be evaluated and added to the catalog. Accepts a class name, an array of class names, or a comma-separated list of class names. The `include` function can be used multiple times on the same class and will only declare a given class once. If a class declared with `include` has any parameters, Puppet will automatically look up values for them in Hiera, using `<class name>::<parameter name>` as the lookup key. Contrast this behavior with resource-like class declarations (`class {'name': parameter => 'value',}`), which must be used in only one place per class and can directly set parameters. You should avoid using both `include` and resource-like declarations with the same class. The `include` function does not cause classes to be contained in the class where they are declared. For that, see the `contain` function. It also does not create a dependency relationship between the declared class and the surrounding class; for that, see the `require` function. You must use the class's full name; relative names are not allowed. In addition to names in string form, you may also directly use Class and Resource Type values that are produced by the future parser's resource and relationship expressions. - Since < 3.0.0 - Since 4.0.0 support for class and resource type values, absolute names - Since 4.7.0 returns an Array[Type[Class]] of all included classes ") do |classes| call_function('include', classes) # TRANSLATORS "function_include", "Scope", and "Scope#call_function" refer to Puppet internals and should not be translated Puppet.warn_once('deprecations', '3xfunction#include', _("Calling function_include via the Scope class is deprecated. Use Scope#call_function instead")) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/generate.rb
lib/puppet/parser/functions/generate.rb
# frozen_string_literal: true # Runs an external command and returns the results Puppet::Parser::Functions.newfunction(:generate, :arity => -2, :type => :rvalue, :doc => "Calls an external command on the Puppet master and returns the results of the command. Any arguments are passed to the external command as arguments. If the generator does not exit with return code of 0, the generator is considered to have failed and a parse error is thrown. Generators can only have file separators, alphanumerics, dashes, and periods in them. This function will attempt to protect you from malicious generator calls (e.g., those with '..' in them), but it can never be entirely safe. No subshell is used to execute generators, so all shell metacharacters are passed directly to the generator, and all metacharacters are returned by the function. Consider cleaning white space from any string generated.") do |args| # TRANSLATORS "fully qualified" refers to a fully qualified file system path raise Puppet::ParseError, _("Generators must be fully qualified") unless Puppet::Util.absolute_path?(args[0]) if Puppet::Util::Platform.windows? valid = args[0] =~ %r{^[a-z]:(?:[/\\][-.~\w]+)+$}i else valid = args[0] =~ %r{^[-/\w.+]+$} end unless valid raise Puppet::ParseError, _("Generators can only contain alphanumerics, file separators, and dashes") end if args[0] =~ /\.\./ raise Puppet::ParseError, _("Can not use generators with '..' in them.") end begin dir = File.dirname(args[0]) Puppet::Util::Execution.execute(args, failonfail: true, combine: true, cwd: dir).to_str rescue Puppet::ExecutionFailure => detail raise Puppet::ParseError, _("Failed to execute generator %{generator}: %{detail}") % { generator: args[0], detail: detail }, detail.backtrace end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/fqdn_rand.rb
lib/puppet/parser/functions/fqdn_rand.rb
# frozen_string_literal: true require 'digest/md5' require 'digest/sha2' Puppet::Parser::Functions.newfunction(:fqdn_rand, :arity => -2, :type => :rvalue, :doc => "Usage: `fqdn_rand(MAX, [SEED], [DOWNCASE])`. MAX is required and must be a positive integer; SEED is optional and may be any number or string; DOWNCASE is optional and should be a boolean true or false. Generates a random Integer number greater than or equal to 0 and less than MAX, combining the `$fqdn` fact and the value of SEED for repeatable randomness. (That is, each node will get a different random number from this function, but a given node's result will be the same every time unless its hostname changes.) If DOWNCASE is true, then the `fqdn` fact will be downcased when computing the value so that the result is not sensitive to the case of the `fqdn` fact. This function is usually used for spacing out runs of resource-intensive cron tasks that run on many nodes, which could cause a thundering herd or degrade other services if they all fire at once. Adding a SEED can be useful when you have more than one such task and need several unrelated random numbers per node. (For example, `fqdn_rand(30)`, `fqdn_rand(30, 'expensive job 1')`, and `fqdn_rand(30, 'expensive job 2')` will produce totally different numbers.)") do |args| max = args.shift.to_i initial_seed = args.shift downcase = !!args.shift fqdn = self['facts'].dig('networking', 'fqdn') fqdn = fqdn.downcase if downcase # Puppet 5.4's fqdn_rand function produces a different value than earlier versions # for the same set of inputs. # This causes problems because the values are often written into service configuration files. # When they change, services get notified and restart. # Restoring previous fqdn_rand behavior of calculating its seed value using MD5 # when running on a non-FIPS enabled platform and only using SHA256 on FIPS enabled # platforms. if Puppet::Util::Platform.fips_enabled? seed = Digest::SHA256.hexdigest([fqdn, max, initial_seed].join(':')).hex else seed = Digest::MD5.hexdigest([fqdn, max, initial_seed].join(':')).hex end Puppet::Util.deterministic_rand_int(seed, max) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/type.rb
lib/puppet/parser/functions/type.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :type, :type => :rvalue, :arity => -1, :doc => <<~DOC Returns the data type of a given value with a given degree of generality. ```puppet type InferenceFidelity = Enum[generalized, reduced, detailed] function type(Any $value, InferenceFidelity $fidelity = 'detailed') # returns Type ``` **Example:** Using `type` ``` puppet notice type(42) =~ Type[Integer] ``` Would notice `true`. By default, the best possible inference is made where all details are retained. This is good when the type is used for further type calculations but is overwhelmingly rich in information if it is used in a error message. The optional argument `$fidelity` may be given as (from lowest to highest fidelity): * `generalized` - reduces to common type and drops size constraints * `reduced` - reduces to common type in collections * `detailed` - (default) all details about inferred types is retained **Example:** Using `type()` with different inference fidelity: ``` puppet notice type([3.14, 42], 'generalized') notice type([3.14, 42], 'reduced'') notice type([3.14, 42], 'detailed') notice type([3.14, 42]) ``` Would notice the four values: 1. 'Array[Numeric]' 2. 'Array[Numeric, 2, 2]' 3. 'Tuple[Float[3.14], Integer[42,42]]]' 4. 'Tuple[Float[3.14], Integer[42,42]]]' * Since 4.4.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('type') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/hiera_hash.rb
lib/puppet/parser/functions/hiera_hash.rb
# frozen_string_literal: true require 'hiera_puppet' module Puppet::Parser::Functions newfunction( :hiera_hash, :type => :rvalue, :arity => -2, :doc => <<~DOC Finds all matches of a key throughout the hierarchy and returns them in a merged hash. If any of the matched hashes share keys, the final hash uses the value from the highest priority match. This is called a [hash merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#hash-merge). The merge strategy is determined by Hiera's [`:merge_behavior`](https://puppet.com/docs/hiera/latest/configuring.html#mergebehavior) setting. The `hiera_hash` function takes up to three arguments, in this order: 1. A string key that Hiera searches for in the hierarchy. **Required**. 2. An optional default value to return if Hiera doesn't find anything matching the key. * If this argument isn't provided and this function results in a lookup failure, Puppet fails with a compilation error. 3. The optional name of an arbitrary [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup. * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy. **Example**: Using `hiera_hash` ~~~ yaml # Assuming hiera.yaml # :hierarchy: # - web01.example.com # - common # Assuming common.yaml: # users: # regular: # 'cdouglas': 'Carrie Douglas' # Assuming web01.example.com.yaml: # users: # administrators: # 'aberry': 'Amy Berry' ~~~ ~~~ puppet # Assuming we are not web01.example.com: $allusers = hiera_hash('users', undef) # $allusers contains {regular => {"cdouglas" => "Carrie Douglas"}, # administrators => {"aberry" => "Amy Berry"}} ~~~ You can optionally generate the default value with a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that takes one parameter. **Example**: Using `hiera_hash` with a lambda ~~~ puppet # Assuming the same Hiera data as the previous example: $allusers = hiera_hash('users') | $key | { "Key \'${key}\' not found" } # $allusers contains {regular => {"cdouglas" => "Carrie Douglas"}, # administrators => {"aberry" => "Amy Berry"}} # If hiera_hash couldn't match its key, it would return the lambda result, # "Key 'users' not found". ~~~ `hiera_hash` expects that all values returned will be hashes. If any of the values found in the data sources are strings or arrays, Puppet raises a type mismatch error. `hiera_hash` is deprecated in favor of using `lookup` and will be removed in 6.0.0. See https://puppet.com/docs/puppet/#{Puppet.minor_version}/deprecated_language.html. Replace the calls as follows: | from | to | | ---- | ---| | hiera_hash($key) | lookup($key, { 'merge' => 'hash' }) | | hiera_hash($key, $default) | lookup($key, { 'default_value' => $default, 'merge' => 'hash' }) | | hiera_hash($key, $default, $level) | override level not supported | Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced result must be post processed to get exactly the same result, for example using simple hash/array `+` or with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml. See [the documentation](https://puppet.com/docs/hiera/latest/puppet.html#hiera-lookup-functions) for more information about Hiera lookup functions. - Since 4.0.0 DOC ) do |*_args| Error.is4x('hiera_hash') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/new.rb
lib/puppet/parser/functions/new.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :new, :type => :rvalue, :arity => -1, :doc => <<~DOC Creates a new instance/object of a given data type. This function makes it possible to create new instances of concrete data types. If a block is given it is called with the just created instance as an argument. Calling this function is equivalent to directly calling the data type: **Example:** `new` and calling type directly are equivalent ```puppet $a = Integer.new("42") $b = Integer("42") ``` These would both convert the string `"42"` to the decimal value `42`. **Example:** arguments by position or by name ```puppet $a = Integer.new("42", 8) $b = Integer({from => "42", radix => 8}) ``` This would convert the octal (radix 8) number `"42"` in string form to the decimal value `34`. The new function supports two ways of giving the arguments: * by name (using a hash with property to value mapping) * by position (as regular arguments) Note that it is not possible to create new instances of some abstract data types (for example `Variant`). The data type `Optional[T]` is an exception as it will create an instance of `T` or `undef` if the value to convert is `undef`. The arguments that can be given is determined by the data type. > An assertion is always made that the produced value complies with the given type constraints. **Example:** data type constraints are checked ```puppet Integer[0].new("-100") ``` Would fail with an assertion error (since value is less than 0). The following sections show the arguments and conversion rules per data type built into the Puppet Type System. ### Conversion to Optional[T] and NotUndef[T] Conversion to these data types is the same as a conversion to the type argument `T`. In the case of `Optional[T]` it is accepted that the argument to convert may be `undef`. It is however not acceptable to give other arguments (than `undef`) that cannot be converted to `T`. ### Conversion to Integer A new `Integer` can be created from `Integer`, `Float`, `Boolean`, and `String` values. For conversion from `String` it is possible to specify the radix (base). ```puppet type Radix = Variant[Default, Integer[2,2], Integer[8,8], Integer[10,10], Integer[16,16]] function Integer.new( String $value, Radix $radix = 10, Boolean $abs = false ) function Integer.new( Variant[Numeric, Boolean] $value, Boolean $abs = false ) ``` * When converting from `String` the default radix is 10. * If radix is not specified an attempt is made to detect the radix from the start of the string: * `0b` or `0B` is taken as radix 2. * `0x` or `0X` is taken as radix 16. * `0` as radix 8. * All others are decimal. * Conversion from `String` accepts an optional sign in the string. * For hexadecimal (radix 16) conversion an optional leading "0x", or "0X" is accepted. * For octal (radix 8) an optional leading "0" is accepted. * For binary (radix 2) an optional leading "0b" or "0B" is accepted. * When `radix` is set to `default`, the conversion is based on the leading. characters in the string. A leading "0" for radix 8, a leading "0x", or "0X" for radix 16, and leading "0b" or "0B" for binary. * Conversion from `Boolean` results in 0 for `false` and 1 for `true`. * Conversion from `Integer`, `Float`, and `Boolean` ignores the radix. * `Float` value fractions are truncated (no rounding). * When `abs` is set to `true`, the result will be an absolute integer. Examples - Converting to Integer: ```puppet $a_number = Integer("0xFF", 16) # results in 255 $a_number = Integer("010") # results in 8 $a_number = Integer("010", 10) # results in 10 $a_number = Integer(true) # results in 1 $a_number = Integer(-38, 10, true) # results in 38 ``` ### Conversion to Float A new `Float` can be created from `Integer`, `Float`, `Boolean`, and `String` values. For conversion from `String` both float and integer formats are supported. ```puppet function Float.new( Variant[Numeric, Boolean, String] $value, Boolean $abs = true ) ``` * For an integer, the floating point fraction of `.0` is added to the value. * A `Boolean` `true` is converted to 1.0, and a `false` to 0.0 * In `String` format, integer prefixes for hex and binary are understood (but not octal since floating point in string format may start with a '0'). * When `abs` is set to `true`, the result will be an absolute floating point value. ### Conversion to Numeric A new `Integer` or `Float` can be created from `Integer`, `Float`, `Boolean` and `String` values. ```puppet function Numeric.new( Variant[Numeric, Boolean, String] $value, Boolean $abs = true ) ``` * If the value has a decimal period, or if given in scientific notation (e/E), the result is a `Float`, otherwise the value is an `Integer`. The conversion from `String` always uses a radix based on the prefix of the string. * Conversion from `Boolean` results in 0 for `false` and 1 for `true`. * When `abs` is set to `true`, the result will be an absolute `Float`or `Integer` value. Examples - Converting to Numeric ```puppet $a_number = Numeric(true) # results in 1 $a_number = Numeric("0xFF") # results in 255 $a_number = Numeric("010") # results in 8 $a_number = Numeric("3.14") # results in 3.14 (a float) $a_number = Numeric(-42.3, true) # results in 42.3 $a_number = Numeric(-42, true) # results in 42 ``` ### Conversion to Timespan A new `Timespan` can be created from `Integer`, `Float`, `String`, and `Hash` values. Several variants of the constructor are provided. #### Timespan from seconds When a Float is used, the decimal part represents fractions of a second. ```puppet function Timespan.new( Variant[Float, Integer] $value ) ``` #### Timespan from days, hours, minutes, seconds, and fractions of a second The arguments can be passed separately in which case the first four, days, hours, minutes, and seconds are mandatory and the rest are optional. All values may overflow and/or be negative. The internal 128-bit nano-second integer is calculated as: ``` (((((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000 + milliseconds) * 1000 + microseconds) * 1000 + nanoseconds ``` ```puppet function Timespan.new( Integer $days, Integer $hours, Integer $minutes, Integer $seconds, Integer $milliseconds = 0, Integer $microseconds = 0, Integer $nanoseconds = 0 ) ``` or, all arguments can be passed as a `Hash`, in which case all entries are optional: ```puppet function Timespan.new( Struct[{ Optional[negative] => Boolean, Optional[days] => Integer, Optional[hours] => Integer, Optional[minutes] => Integer, Optional[seconds] => Integer, Optional[milliseconds] => Integer, Optional[microseconds] => Integer, Optional[nanoseconds] => Integer }] $hash ) ``` #### Timespan from String and format directive patterns The first argument is parsed using the format optionally passed as a string or array of strings. When an array is used, an attempt will be made to parse the string using the first entry and then with each entry in succession until parsing succeeds. If the second argument is omitted, an array of default formats will be used. An exception is raised when no format was able to parse the given string. ```puppet function Timespan.new( String $string, Variant[String[2],Array[String[2], 1]] $format = <default format>) ) ``` the arguments may also be passed as a `Hash`: ```puppet function Timespan.new( Struct[{ string => String[1], Optional[format] => Variant[String[2],Array[String[2], 1]] }] $hash ) ``` The directive consists of a percent (%) character, zero or more flags, optional minimum field width and a conversion specifier as follows: ``` %[Flags][Width]Conversion ``` ##### Flags: | Flag | Meaning | ---- | --------------- | - | Don't pad numerical output | _ | Use spaces for padding | 0 | Use zeros for padding ##### Format directives: | Format | Meaning | | ------ | ------- | | D | Number of Days | | H | Hour of the day, 24-hour clock | | M | Minute of the hour (00..59) | | S | Second of the minute (00..59) | | L | Millisecond of the second (000..999) | | N | Fractional seconds digits | The format directive that represents the highest magnitude in the format will be allowed to overflow. I.e. if no "%D" is used but a "%H" is present, then the hours may be more than 23. The default array contains the following patterns: ``` ['%D-%H:%M:%S', '%D-%H:%M', '%H:%M:%S', '%H:%M'] ``` Examples - Converting to Timespan ```puppet $duration = Timespan(13.5) # 13 seconds and 500 milliseconds $duration = Timespan({days=>4}) # 4 days $duration = Timespan(4, 0, 0, 2) # 4 days and 2 seconds $duration = Timespan('13:20') # 13 hours and 20 minutes (using default pattern) $duration = Timespan('10:03.5', '%M:%S.%L') # 10 minutes, 3 seconds, and 5 milli-seconds $duration = Timespan('10:03.5', '%M:%S.%N') # 10 minutes, 3 seconds, and 5 nano-seconds ``` ### Conversion to Timestamp A new `Timestamp` can be created from `Integer`, `Float`, `String`, and `Hash` values. Several variants of the constructor are provided. #### Timestamp from seconds since epoch (1970-01-01 00:00:00 UTC) When a Float is used, the decimal part represents fractions of a second. ```puppet function Timestamp.new( Variant[Float, Integer] $value ) ``` #### Timestamp from String and patterns consisting of format directives The first argument is parsed using the format optionally passed as a string or array of strings. When an array is used, an attempt will be made to parse the string using the first entry and then with each entry in succession until parsing succeeds. If the second argument is omitted, an array of default formats will be used. A third optional timezone argument can be provided. The first argument will then be parsed as if it represents a local time in that timezone. The timezone can be any timezone that is recognized when using the '%z' or '%Z' formats, or the word 'current', in which case the current timezone of the evaluating process will be used. The timezone argument is case insensitive. The default timezone, when no argument is provided, or when using the keyword `default`, is 'UTC'. It is illegal to provide a timezone argument other than `default` in combination with a format that contains '%z' or '%Z' since that would introduce an ambiguity as to which timezone to use. The one extracted from the string, or the one provided as an argument. An exception is raised when no format was able to parse the given string. ```puppet function Timestamp.new( String $string, Variant[String[2],Array[String[2], 1]] $format = <default format>, String $timezone = default) ) ``` the arguments may also be passed as a `Hash`: ```puppet function Timestamp.new( Struct[{ string => String[1], Optional[format] => Variant[String[2],Array[String[2], 1]], Optional[timezone] => String[1] }] $hash ) ``` The directive consists of a percent (%) character, zero or more flags, optional minimum field width and a conversion specifier as follows: ``` %[Flags][Width]Conversion ``` ##### Flags: | Flag | Meaning | ---- | --------------- | - | Don't pad numerical output | _ | Use spaces for padding | 0 | Use zeros for padding | # | Change names to upper-case or change case of am/pm | ^ | Use uppercase | : | Use colons for %z ##### Format directives (names and padding can be altered using flags): **Date (Year, Month, Day):** | Format | Meaning | | ------ | ------- | | Y | Year with century, zero-padded to at least 4 digits | | C | year / 100 (rounded down such as 20 in 2009) | | y | year % 100 (00..99) | | m | Month of the year, zero-padded (01..12) | | B | The full month name ("January") | | b | The abbreviated month name ("Jan") | | h | Equivalent to %b | | d | Day of the month, zero-padded (01..31) | | e | Day of the month, blank-padded ( 1..31) | | j | Day of the year (001..366) | **Time (Hour, Minute, Second, Subsecond):** | Format | Meaning | | ------ | ------- | | H | Hour of the day, 24-hour clock, zero-padded (00..23) | | k | Hour of the day, 24-hour clock, blank-padded ( 0..23) | | I | Hour of the day, 12-hour clock, zero-padded (01..12) | | l | Hour of the day, 12-hour clock, blank-padded ( 1..12) | | P | Meridian indicator, lowercase ("am" or "pm") | | p | Meridian indicator, uppercase ("AM" or "PM") | | M | Minute of the hour (00..59) | | S | Second of the minute (00..60) | | L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000 | | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified width are truncated to avoid carry up | **Time (Hour, Minute, Second, Subsecond):** | Format | Meaning | | ------ | ------- | | z | Time zone as hour and minute offset from UTC (e.g. +0900) | | :z | hour and minute offset from UTC with a colon (e.g. +09:00) | | ::z | hour, minute and second offset from UTC (e.g. +09:00:00) | | Z | Abbreviated time zone name or similar information. (OS dependent) | **Weekday:** | Format | Meaning | | ------ | ------- | | A | The full weekday name ("Sunday") | | a | The abbreviated name ("Sun") | | u | Day of the week (Monday is 1, 1..7) | | w | Day of the week (Sunday is 0, 0..6) | **ISO 8601 week-based year and week number:** The first week of YYYY starts with a Monday and includes YYYY-01-04. The days in the year before the first week are in the last week of the previous year. | Format | Meaning | | ------ | ------- | | G | The week-based year | | g | The last 2 digits of the week-based year (00..99) | | V | Week number of the week-based year (01..53) | **Week number:** The first week of YYYY that starts with a Sunday or Monday (according to %U or %W). The days in the year before the first week are in week 0. | Format | Meaning | | ------ | ------- | | U | Week number of the year. The week starts with Sunday. (00..53) | | W | Week number of the year. The week starts with Monday. (00..53) | **Seconds since the Epoch:** | Format | Meaning | | s | Number of seconds since 1970-01-01 00:00:00 UTC. | **Literal string:** | Format | Meaning | | ------ | ------- | | n | Newline character (\n) | | t | Tab character (\t) | | % | Literal "%" character | **Combination:** | Format | Meaning | | ------ | ------- | | c | date and time (%a %b %e %T %Y) | | D | Date (%m/%d/%y) | | F | The ISO 8601 date format (%Y-%m-%d) | | v | VMS date (%e-%^b-%4Y) | | x | Same as %D | | X | Same as %T | | r | 12-hour time (%I:%M:%S %p) | | R | 24-hour time (%H:%M) | | T | 24-hour time (%H:%M:%S) | The default array contains the following patterns: When a timezone argument (other than `default`) is explicitly provided: ``` ['%FT%T.L', '%FT%T', '%F'] ``` otherwise: ``` ['%FT%T.%L %Z', '%FT%T %Z', '%F %Z', '%FT%T.L', '%FT%T', '%F'] ``` Examples - Converting to Timestamp ```puppet $ts = Timestamp(1473150899) # 2016-09-06 08:34:59 UTC $ts = Timestamp({string=>'2015', format=>'%Y'}) # 2015-01-01 00:00:00.000 UTC $ts = Timestamp('Wed Aug 24 12:13:14 2016', '%c') # 2016-08-24 12:13:14 UTC $ts = Timestamp('Wed Aug 24 12:13:14 2016 PDT', '%c %Z') # 2016-08-24 19:13:14.000 UTC $ts = Timestamp('2016-08-24 12:13:14', '%F %T', 'PST') # 2016-08-24 20:13:14.000 UTC $ts = Timestamp('2016-08-24T12:13:14', default, 'PST') # 2016-08-24 20:13:14.000 UTC ``` ### Conversion to Type A new `Type` can be create from its `String` representation. **Example:** Creating a type from a string ```puppet $t = Type.new('Integer[10]') ``` ### Conversion to String Conversion to `String` is the most comprehensive conversion as there are many use cases where a string representation is wanted. The defaults for the many options have been chosen with care to be the most basic "value in textual form" representation. The more advanced forms of formatting are intended to enable writing special purposes formatting functions in the Puppet language. A new string can be created from all other data types. The process is performed in several steps - first the data type of the given value is inferred, then the resulting data type is used to find the most significant format specified for that data type. And finally, the found format is used to convert the given value. The mapping from data type to format is referred to as the *format map*. This map allows different formatting depending on type. **Example:** Positive Integers in Hexadecimal prefixed with '0x', negative in Decimal ```puppet $format_map = { Integer[default, 0] => "%d", Integer[1, default] => "%#x" } String("-1", $format_map) # produces '-1' String("10", $format_map) # produces '0xa' ``` A format is specified on the form: ``` %[Flags][Width][.Precision]Format ``` `Width` is the number of characters into which the value should be fitted. This allocated space is padded if value is shorter. By default it is space padded, and the flag `0` will cause padding with `0` for numerical formats. `Precision` is the number of fractional digits to show for floating point, and the maximum characters included in a string format. Note that all data type supports the formats `s` and `p` with the meaning "default string representation" and "default programmatic string representation" (which for example means that a String is quoted in 'p' format). #### Signatures of String conversion ```puppet type Format = Pattern[/^%([\s\+\-#0\[\{<\(\|]*)([1-9][0-9]*)?(?:\.([0-9]+))?([a-zA-Z])/] type ContainerFormat = Struct[{ format => Optional[String], separator => Optional[String], separator2 => Optional[String], string_formats => Hash[Type, Format] }] type TypeMap = Hash[Type, Variant[Format, ContainerFormat]] type Formats = Variant[Default, String[1], TypeMap] function String.new( Any $value, Formats $string_formats ) ``` Where: * `separator` is the string used to separate entries in an array, or hash (extra space should not be included at the end), defaults to `","` * `separator2` is the separator between key and value in a hash entry (space padding should be included as wanted), defaults to `" => "`. * `string_formats` is a data type to format map for values contained in arrays and hashes - defaults to `{Any => "%p"}`. Note that these nested formats are not applicable to data types that are containers; they are always formatted as per the top level format specification. **Example:** Simple Conversion to String (using defaults) ```puppet $str = String(10) # produces '10' $str = String([10]) # produces '["10"]' ``` **Example:** Simple Conversion to String specifying the format for the given value directly ```puppet $str = String(10, "%#x") # produces '0x10' $str = String([10], "%(a") # produces '("10")' ``` **Example:** Specifying type for values contained in an array ```puppet $formats = { Array => { format => '%(a', string_formats => { Integer => '%#x' } } } $str = String([1,2,3], $formats) # produces '(0x1, 0x2, 0x3)' ``` The given formats are merged with the default formats, and matching of values to convert against format is based on the specificity of the mapped type; for example, different formats can be used for short and long arrays. #### Integer to String | Format | Integer Formats | ------ | --------------- | d | Decimal, negative values produces leading '-'. | x X | Hexadecimal in lower or upper case. Uses ..f/..F for negative values unless + is also used. A `#` adds prefix 0x/0X. | o | Octal. Uses ..0 for negative values unless `+` is also used. A `#` adds prefix 0. | b B | Binary with prefix 'b' or 'B'. Uses ..1/..1 for negative values unless `+` is also used. | c | Numeric value representing a Unicode value, result is a one unicode character string, quoted if alternative flag # is used | s | Same as d, or d in quotes if alternative flag # is used. | p | Same as d. | eEfgGaA | Converts integer to float and formats using the floating point rules. Defaults to `d`. #### Float to String | Format | Float formats | ------ | ------------- | f | Floating point in non exponential notation. | e E | Exponential notation with 'e' or 'E'. | g G | Conditional exponential with 'e' or 'E' if exponent < -4 or >= the precision. | a A | Hexadecimal exponential form, using 'x'/'X' as prefix and 'p'/'P' before exponent. | s | Converted to string using format p, then applying string formatting rule, alternate form # quotes result. | p | Same as f format with minimum significant number of fractional digits, prec has no effect. | dxXobBc | Converts float to integer and formats using the integer rules. Defaults to `p`. #### String to String | Format | String | ------ | ------ | s | Unquoted string, verbatim output of control chars. | p | Programmatic representation - strings are quoted, interior quotes and control chars are escaped. | C | Each `::` name segment capitalized, quoted if alternative flag `#` is used. | c | Capitalized string, quoted if alternative flag `#` is used. | d | Downcased string, quoted if alternative flag `#` is used. | u | Upcased string, quoted if alternative flag `#` is used. | t | Trims leading and trailing whitespace from the string, quoted if alternative flag `#` is used. Defaults to `s` at top level and `p` inside array or hash. #### Boolean to String | Format | Boolean Formats | ---- | ------------------- | t T | String 'true'/'false' or 'True'/'False', first char if alternate form is used (i.e. 't'/'f' or 'T'/'F'). | y Y | String 'yes'/'no', 'Yes'/'No', 'y'/'n' or 'Y'/'N' if alternative flag `#` is used. | dxXobB | Numeric value 0/1 in accordance with the given format which must be valid integer format. | eEfgGaA | Numeric value 0.0/1.0 in accordance with the given float format and flags. | s | String 'true' / 'false'. | p | String 'true' / 'false'. #### Regexp to String | Format | Regexp Formats | ---- | -------------- | s | No delimiters, quoted if alternative flag `#` is used. | p | Delimiters `/ /`. #### Undef to String | Format | Undef formats | ------ | ------------- | s | Empty string, or quoted empty string if alternative flag `#` is used. | p | String 'undef', or quoted '"undef"' if alternative flag `#` is used. | n | String 'nil', or 'null' if alternative flag `#` is used. | dxXobB | String 'NaN'. | eEfgGaA | String 'NaN'. | v | String 'n/a'. | V | String 'N/A'. | u | String 'undef', or 'undefined' if alternative `#` flag is used. #### Default value to String | Format | Default formats | ------ | --------------- | d D | String 'default' or 'Default', alternative form `#` causes value to be quoted. | s | Same as d. | p | Same as d. #### Binary value to String | Format | Default formats | ------ | --------------- | s | binary as unquoted UTF-8 characters (errors if byte sequence is invalid UTF-8). Alternate form escapes non ascii bytes. | p | 'Binary("<base64strict>")' | b | '<base64>' - base64 string with newlines inserted | B | '<base64strict>' - base64 strict string (without newlines inserted) | u | '<base64urlsafe>' - base64 urlsafe string | t | 'Binary' - outputs the name of the type only | T | 'BINARY' - output the name of the type in all caps only * The alternate form flag `#` will quote the binary or base64 text output. * The format `%#s` allows invalid UTF-8 characters and outputs all non ascii bytes as hex escaped characters on the form `\\xHH` where `H` is a hex digit. * The width and precision values are applied to the text part only in `%p` format. #### Array & Tuple to String | Format | Array/Tuple Formats | ------ | ------------- | a | Formats with `[ ]` delimiters and `,`, alternate form `#` indents nested arrays/hashes. | s | Same as a. | p | Same as a. See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for more information about options. The alternate form flag `#` will cause indentation of nested array or hash containers. If width is also set it is taken as the maximum allowed length of a sequence of elements (not including delimiters). If this max length is exceeded, each element will be indented. #### Hash & Struct to String | Format | Hash/Struct Formats | ------ | ------------- | h | Formats with `{ }` delimiters, `,` element separator and ` => ` inner element separator unless overridden by flags. | s | Same as h. | p | Same as h. | a | Converts the hash to an array of [k,v] tuples and formats it using array rule(s). See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for more information about options. The alternate form flag `#` will format each hash key/value entry indented on a separate line. #### Type to String | Format | Array/Tuple Formats | ------ | ------------- | s | The same as `p`, quoted if alternative flag `#` is used. | p | Outputs the type in string form as specified by the Puppet Language. #### Flags | Flag | Effect | ------ | ------ | (space) | A space instead of `+` for numeric output (`-` is shown), for containers skips delimiters. | # | Alternate format; prefix 0x/0x, 0 (octal) and 0b/0B for binary, Floats force decimal '.'. For g/G keep trailing 0. | + | Show sign +/- depending on value's sign, changes x, X, o, b, B format to not use 2's complement form. | - | Left justify the value in the given width. | 0 | Pad with 0 instead of space for widths larger than value. | <[({\| | Defines an enclosing pair <> [] () {} or \| \| when used with a container type. ### Conversion to Boolean Accepts a single value as argument: * Float 0.0 is `false`, all other float values are `true` * Integer 0 is `false`, all other integer values are `true` * Strings * `true` if 'true', 'yes', 'y' (case independent compare) * `false` if 'false', 'no', 'n' (case independent compare) * Boolean is already boolean and is simply returned ### Conversion to Array and Tuple When given a single value as argument: * A non empty `Hash` is converted to an array matching `Array[Tuple[Any,Any], 1]`. * An empty `Hash` becomes an empty array. * An `Array` is simply returned. * An `Iterable[T]` is turned into an array of `T` instances. * A `Binary` is converted to an `Array[Integer[0,255]]` of byte values When given a second Boolean argument: * if `true`, a value that is not already an array is returned as a one element array. * if `false`, (the default), converts the first argument as shown above. **Example:** Ensuring value is an array ```puppet $arr = Array($value, true) ``` Conversion to a `Tuple` works exactly as conversion to an `Array`, only that the constructed array is asserted against the given tuple type. ### Conversion to Hash and Struct Accepts a single value as argument: * An empty `Array` becomes an empty `Hash` * An `Array` matching `Array[Tuple[Any,Any], 1]` is converted to a hash where each tuple describes a key/value entry * An `Array` with an even number of entries is interpreted as `[key1, val1, key2, val2, ...]` * An `Iterable` is turned into an `Array` and then converted to hash as per the array rules * A `Hash` is simply returned Alternatively, a tree can be constructed by giving two values; an array of tuples on the form `[path, value]` (where the `path` is the path from the root of a tree, and `value` the value at that position in the tree), and either the option `'tree'` (do not convert arrays to hashes except the top level), or `'hash_tree'` (convert all arrays to hashes). The tree/hash_tree forms of Hash creation are suited for transforming the result of an iteration using `tree_each` and subsequent filtering or mapping. **Example:** Mapping a hash tree Mapping an arbitrary structure in a way that keeps the structure, but where some values are replaced can be done by using the `tree_each` function, mapping, and then constructing a new Hash from the result: ```puppet # A hash tree with 'water' at different locations $h = { a => { b => { x => 'water'}}, b => { y => 'water'} } # a helper function that turns water into wine function make_wine($x) { if $x == 'water' { 'wine' } else { $x } } # create a flattened tree with water turned into wine $flat_tree = $h.tree_each.map |$entry| { [$entry[0], make_wine($entry[1])] } # create a new Hash and log it notice Hash($flat_tree, 'hash_tree') ``` Would notice the hash `{a => {b => {x => wine}}, b => {y => wine}}` Conversion to a `Struct` works exactly as conversion to a `Hash`, only that the constructed hash is asserted against the given struct type. ### Conversion to a Regexp A `String` can be converted into a `Regexp` **Example**: Converting a String into a Regexp ```puppet $s = '[a-z]+\.com' $r = Regexp($s) if('foo.com' =~ $r) { ... } ``` ### Creating a SemVer A SemVer object represents a single [Semantic Version](http://semver.org/). It can be created from a String, individual values for its parts, or a hash specifying the value per part. See the specification at [semver.org](http://semver.org/) for the meaning of the SemVer's parts. The signatures are: ```puppet type PositiveInteger = Integer[0,default] type SemVerQualifier = Pattern[/\A(?<part>[0-9A-Za-z-]+)(?:\.\g<part>)*\Z/] type SemVerString = String[1] type SemVerHash =Struct[{ major => PositiveInteger, minor => PositiveInteger, patch => PositiveInteger, Optional[prerelease] => SemVerQualifier, Optional[build] => SemVerQualifier }] function SemVer.new(SemVerString $str) function SemVer.new( PositiveInteger $major PositiveInteger $minor PositiveInteger $patch Optional[SemVerQualifier] $prerelease = undef
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/hiera_include.rb
lib/puppet/parser/functions/hiera_include.rb
# frozen_string_literal: true require 'hiera_puppet' module Puppet::Parser::Functions newfunction( :hiera_include, :arity => -2, :doc => <<~DOC Assigns classes to a node using an [array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge) that retrieves the value for a user-specified key from Hiera's data. The `hiera_include` function requires: - A string key name to use for classes. - A call to this function (i.e. `hiera_include('classes')`) in your environment's `sites.pp` manifest, outside of any node definitions and below any top-scope variables that Hiera uses in lookups. - `classes` keys in the appropriate Hiera data sources, with an array for each `classes` key and each value of the array containing the name of a class. The function takes up to three arguments, in this order: 1. A string key that Hiera searches for in the hierarchy. **Required**. 2. An optional default value to return if Hiera doesn't find anything matching the key. * If this argument isn't provided and this function results in a lookup failure, Puppet fails with a compilation error. 3. The optional name of an arbitrary [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup. * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy. The function uses an [array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge) to retrieve the `classes` array, so every node gets every class from the hierarchy. **Example**: Using `hiera_include` ~~~ yaml # Assuming hiera.yaml # :hierarchy: # - web01.example.com # - common # Assuming web01.example.com.yaml: # classes: # - apache::mod::php # Assuming common.yaml: # classes: # - apache ~~~ ~~~ puppet # In site.pp, outside of any node definitions and below any top-scope variables: hiera_include('classes', undef) # Puppet assigns the apache and apache::mod::php classes to the web01.example.com node. ~~~ You can optionally generate the default value with a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that takes one parameter. **Example**: Using `hiera_include` with a lambda ~~~ puppet # Assuming the same Hiera data as the previous example: # In site.pp, outside of any node definitions and below any top-scope variables: hiera_include('classes') | $key | {"Key \'${key}\' not found" } # Puppet assigns the apache and apache::mod::php classes to the web01.example.com node. # If hiera_include couldn't match its key, it would return the lambda result, # "Key 'classes' not found". ~~~ `hiera_include` is deprecated in favor of using a combination of `include` and `lookup` and will be removed in Puppet 6.0.0. Replace the calls as follows: | from | to | | ---- | ---| | hiera_include($key) | include(lookup($key, { 'merge' => 'unique' })) | | hiera_include($key, $default) | include(lookup($key, { 'default_value' => $default, 'merge' => 'unique' })) | | hiera_include($key, $default, $level) | override level not supported | See [the Upgrading to Hiera 5 migration guide](https://puppet.com/docs/puppet/5.5/hiera_migrate.html) for more information. Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced result must be post processed to get exactly the same result, for example using simple hash/array `+` or with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml. - Since 4.0.0 DOC ) do |*_args| Error.is4x('hiera_include') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/digest.rb
lib/puppet/parser/functions/digest.rb
# frozen_string_literal: true require_relative '../../../puppet/util/checksums' Puppet::Parser::Functions.newfunction(:digest, :type => :rvalue, :arity => 1, :doc => "Returns a hash value from a provided string using the digest_algorithm setting from the Puppet config file.") do |args| algo = Puppet[:digest_algorithm] Puppet::Util::Checksums.method(algo.intern).call args[0] end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/filter.rb
lib/puppet/parser/functions/filter.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :filter, :type => :rvalue, :arity => -3, :doc => <<~DOC Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) to every value in a data structure and returns an array or hash containing any elements for which the lambda evaluates to a truthy value (not `false` or `undef`). This function takes two mandatory arguments, in this order: 1. An array or hash the function will iterate over. 2. A lambda, which the function calls for each element in the first argument. It can request one or two parameters. **Example**: Using the `filter` function `$filtered_data = $data.filter |$parameter| { <PUPPET CODE BLOCK> }` or `$filtered_data = filter($data) |$parameter| { <PUPPET CODE BLOCK> }` When the first argument (`$data` in the above example) is an array, Puppet passes each value in turn to the lambda and returns an array containing the results. **Example**: Using the `filter` function with an array and a one-parameter lambda ~~~ puppet # For the array $data, return an array containing the values that end with "berry" $data = ["orange", "blueberry", "raspberry"] $filtered_data = $data.filter |$items| { $items =~ /berry$/ } # $filtered_data = [blueberry, raspberry] ~~~ When the first argument is a hash, Puppet passes each key and value pair to the lambda as an array in the form `[key, value]` and returns a hash containing the results. **Example**: Using the `filter` function with a hash and a one-parameter lambda ~~~ puppet # For the hash $data, return a hash containing all values of keys that end with "berry" $data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 } $filtered_data = $data.filter |$items| { $items[0] =~ /berry$/ } # $filtered_data = {blueberry => 1, raspberry => 2} ~~~ When the first argument is an array and the lambda has two parameters, Puppet passes the array's indexes (enumerated from 0) in the first parameter and its values in the second parameter. **Example**: Using the `filter` function with an array and a two-parameter lambda ~~~ puppet # For the array $data, return an array of all keys that both end with "berry" and have # an even-numbered index $data = ["orange", "blueberry", "raspberry"] $filtered_data = $data.filter |$indexes, $values| { $indexes % 2 == 0 and $values =~ /berry$/ } # $filtered_data = [raspberry] ~~~ When the first argument is a hash, Puppet passes its keys to the first parameter and its values to the second parameter. **Example**: Using the `filter` function with a hash and a two-parameter lambda ~~~ puppet # For the hash $data, return a hash of all keys that both end with "berry" and have # values less than or equal to 1 $data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 } $filtered_data = $data.filter |$keys, $values| { $keys =~ /berry$/ and $values <= 1 } # $filtered_data = {blueberry => 1} ~~~ - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('filter') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/file.rb
lib/puppet/parser/functions/file.rb
# frozen_string_literal: true require_relative '../../../puppet/file_system' Puppet::Parser::Functions.newfunction( :file, :arity => -2, :type => :rvalue, :doc => "Loads a file from a module and returns its contents as a string. The argument to this function should be a `<MODULE NAME>/<FILE>` reference, which will load `<FILE>` from a module's `files` directory. (For example, the reference `mysql/mysqltuner.pl` will load the file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.) This function can also accept: * An absolute path, which can load a file from anywhere on disk. * Multiple arguments, which will return the contents of the **first** file found, skipping any files that don't exist. " ) do |vals| path = nil vals.each do |file| found = Puppet::Parser::Files.find_file(file, compiler.environment) if found && Puppet::FileSystem.exist?(found) path = found break end end if path Puppet::FileSystem.read_preserve_line_endings(path) else raise Puppet::ParseError, _("Could not find any files from %{values}") % { values: vals.join(", ") } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/realize.rb
lib/puppet/parser/functions/realize.rb
# frozen_string_literal: true # This is just syntactic sugar for a collection, although it will generally # be a good bit faster. Puppet::Parser::Functions.newfunction(:realize, :arity => -2, :doc => "Make a virtual object real. This is useful when you want to know the name of the virtual object and don't want to bother with a full collection. It is slightly faster than a collection, and, of course, is a bit shorter. You must pass the object using a reference; e.g.: `realize User[luke]`.") do |vals| if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'realize' } ) end vals = [vals] unless vals.is_a?(Array) coll = Puppet::Pops::Evaluator::Collectors::FixedSetCollector.new(self, vals.flatten) compiler.add_collection(coll) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/tagged.rb
lib/puppet/parser/functions/tagged.rb
# frozen_string_literal: true # Test whether a given tag is set. This functions as a big OR -- if any of the specified tags are unset, we return false. Puppet::Parser::Functions.newfunction(:tagged, :type => :rvalue, :arity => -2, :doc => "A boolean function that tells you whether the current container is tagged with the specified tags. The tags are ANDed, so that all of the specified tags must be included for the function to return true.") do |vals| if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'tagged' } ) end retval = true vals.each do |val| unless compiler.catalog.tagged?(val) or resource.tagged?(val) retval = false break end end return retval end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/hiera.rb
lib/puppet/parser/functions/hiera.rb
# frozen_string_literal: true require 'hiera_puppet' module Puppet::Parser::Functions newfunction( :hiera, :type => :rvalue, :arity => -2, :doc => <<~DOC Performs a standard priority lookup of the hierarchy and returns the most specific value for a given key. The returned value can be any type of data. The function takes up to three arguments, in this order: 1. A string key that Hiera searches for in the hierarchy. **Required**. 2. An optional default value to return if Hiera doesn't find anything matching the key. * If this argument isn't provided and this function results in a lookup failure, Puppet fails with a compilation error. 3. The optional name of an arbitrary [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup. * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy. The `hiera` function does **not** find all matches throughout a hierarchy, instead returining the first specific value starting at the top of the hierarchy. To search throughout a hierarchy, use the `hiera_array` or `hiera_hash` functions. **Example**: Using `hiera` ~~~ yaml # Assuming hiera.yaml # :hierarchy: # - web01.example.com # - common # Assuming web01.example.com.yaml: # users: # - "Amy Barry" # - "Carrie Douglas" # Assuming common.yaml: users: admins: - "Edith Franklin" - "Ginny Hamilton" regular: - "Iris Jackson" - "Kelly Lambert" ~~~ ~~~ puppet # Assuming we are not web01.example.com: $users = hiera('users', undef) # $users contains {admins => ["Edith Franklin", "Ginny Hamilton"], # regular => ["Iris Jackson", "Kelly Lambert"]} ~~~ You can optionally generate the default value with a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that takes one parameter. **Example**: Using `hiera` with a lambda ~~~ puppet # Assuming the same Hiera data as the previous example: $users = hiera('users') | $key | { "Key \'${key}\' not found" } # $users contains {admins => ["Edith Franklin", "Ginny Hamilton"], # regular => ["Iris Jackson", "Kelly Lambert"]} # If hiera couldn't match its key, it would return the lambda result, # "Key 'users' not found". ~~~ The returned value's data type depends on the types of the results. In the example above, Hiera matches the 'users' key and returns it as a hash. The `hiera` function is deprecated in favor of using `lookup` and will be removed in 6.0.0. See https://puppet.com/docs/puppet/#{Puppet.minor_version}/deprecated_language.html. Replace the calls as follows: | from | to | | ---- | ---| | hiera($key) | lookup($key) | | hiera($key, $default) | lookup($key, { 'default_value' => $default }) | | hiera($key, $default, $level) | override level not supported | Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced result must be post processed to get exactly the same result, for example using simple hash/array `+` or with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml. See [the documentation](https://puppet.com/docs/hiera/latest/puppet.html#hiera-lookup-functions) for more information about Hiera lookup functions. - Since 4.0.0 DOC ) do |*_args| Error.is4x('hiera') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/step.rb
lib/puppet/parser/functions/step.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :step, :type => :rvalue, :arity => -1, :doc => <<~DOC Provides stepping with given interval over elements in an iterable and optionally runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each element. This function takes two to three arguments: 1. An 'Iterable' that the function will iterate over. 2. An `Integer` step factor. This must be a positive integer. 3. An optional lambda, which the function calls for each element in the interval. It must request one parameter. **Example:** Using the `step` function ```puppet $data.step(<n>) |$parameter| { <PUPPET CODE BLOCK> } ``` or ```puppet $stepped_data = $data.step(<n>) ``` or ```puppet step($data, <n>) |$parameter| { <PUPPET CODE BLOCK> } ``` or ```puppet $stepped_data = step($data, <n>) ``` When no block is given, Puppet returns an `Iterable` that yields the first element and every nth successor element, from its first argument. This allows functions on iterables to be chained. When a block is given, Puppet iterates and calls the block with the first element and then with every nth successor element. It then returns `undef`. **Example:** Using the `step` function with an array, a step factor, and a one-parameter block ```puppet # For the array $data, call a block with the first element and then with each 3rd successor element $data = [1,2,3,4,5,6,7,8] $data.step(3) |$item| { notice($item) } # Puppet notices the values '1', '4', '7'. ``` When no block is given, Puppet returns a new `Iterable` which allows it to be directly chained into another function that takes an `Iterable` as an argument. **Example:** Using the `step` function chained with a `map` function. ```puppet # For the array $data, return an array, set to the first element and each 5th successor element, in reverse # order multiplied by 10 $data = Integer[0,20] $transformed_data = $data.step(5).map |$item| { $item * 10 } $transformed_data contains [0,50,100,150,200] ``` **Example:** The same example using `step` function chained with a `map` in alternative syntax ```puppet # For the array $data, return an array, set to the first and each 5th # successor, in reverse order, multiplied by 10 $data = Integer[0,20] $transformed_data = map(step($data, 5)) |$item| { $item * 10 } $transformed_data contains [0,50,100,150,200] ``` * Since 4.4.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('step') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/md5.rb
lib/puppet/parser/functions/md5.rb
# frozen_string_literal: true require 'digest/md5' Puppet::Parser::Functions.newfunction(:md5, :type => :rvalue, :arity => 1, :doc => "Returns a MD5 hash value from a provided string.") do |args| Digest::MD5.hexdigest(args[0]) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/epp.rb
lib/puppet/parser/functions/epp.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction(:epp, :type => :rvalue, :arity => -2, :doc => "Evaluates an Embedded Puppet (EPP) template file and returns the rendered text result as a String. `epp('<MODULE NAME>/<TEMPLATE FILE>', <PARAMETER HASH>)` The first argument to this function should be a `<MODULE NAME>/<TEMPLATE FILE>` reference, which loads `<TEMPLATE FILE>` from `<MODULE NAME>`'s `templates` directory. In most cases, the last argument is optional; if used, it should be a [hash](https://puppet.com/docs/puppet/latest/lang_data_hash.html) that contains parameters to pass to the template. - See the [template](https://puppet.com/docs/puppet/latest/lang_template.html) documentation for general template usage information. - See the [EPP syntax](https://puppet.com/docs/puppet/latest/lang_template_epp.html) documentation for examples of EPP. For example, to call the apache module's `templates/vhost/_docroot.epp` template and pass the `docroot` and `virtual_docroot` parameters, call the `epp` function like this: `epp('apache/vhost/_docroot.epp', { 'docroot' => '/var/www/html', 'virtual_docroot' => '/var/www/example' })` This function can also accept an absolute path, which can load a template file from anywhere on disk. Puppet produces a syntax error if you pass more parameters than are declared in the template's parameter tag. When passing parameters to a template that contains a parameter tag, use the same names as the tag's declared parameters. Parameters are required only if they are declared in the called template's parameter tag without default values. Puppet produces an error if the `epp` function fails to pass any required parameter. - Since 4.0.0") do |_args| Puppet::Parser::Functions::Error.is4x('epp') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/defined.rb
lib/puppet/parser/functions/defined.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :defined, :type => :rvalue, :arity => -2, :doc => <<~DOC Determines whether a given class or resource type is defined and returns a Boolean value. You can also use `defined` to determine whether a specific resource is defined, or whether a variable has a value (including `undef`, as opposed to the variable never being declared or assigned). This function takes at least one string argument, which can be a class name, type name, resource reference, or variable reference of the form `'$name'`. The `defined` function checks both native and defined types, including types provided by modules. Types and classes are matched by their names. The function matches resource declarations by using resource references. **Examples**: Different types of `defined` function matches ~~~ puppet # Matching resource types defined("file") defined("customtype") # Matching defines and classes defined("foo") defined("foo::bar") # Matching variables defined('$name') # Matching declared resources defined(File['/tmp/file']) ~~~ Puppet depends on the configuration's evaluation order when checking whether a resource is declared. **Example**: Importance of evaluation order when using `defined` ~~~ puppet # Assign values to $is_defined_before and $is_defined_after using identical `defined` # functions. $is_defined_before = defined(File['/tmp/file']) file { "/tmp/file": ensure => present, } $is_defined_after = defined(File['/tmp/file']) # $is_defined_before returns false, but $is_defined_after returns true. ~~~ This order requirement only refers to evaluation order. The order of resources in the configuration graph (e.g. with `before` or `require`) does not affect the `defined` function's behavior. > **Warning:** Avoid relying on the result of the `defined` function in modules, as you > might not be able to guarantee the evaluation order well enough to produce consistent > results. This can cause other code that relies on the function's result to behave > inconsistently or fail. If you pass more than one argument to `defined`, the function returns `true` if _any_ of the arguments are defined. You can also match resources by type, allowing you to match conditions of different levels of specificity, such as whether a specific resource is of a specific data type. **Example**: Matching multiple resources and resources by different types with `defined` ~~~ puppet file { "/tmp/file1": ensure => file, } $tmp_file = file { "/tmp/file2": ensure => file, } # Each of these statements return `true` ... defined(File['/tmp/file1']) defined(File['/tmp/file1'],File['/tmp/file2']) defined(File['/tmp/file1'],File['/tmp/file2'],File['/tmp/file3']) # ... but this returns `false`. defined(File['/tmp/file3']) # Each of these statements returns `true` ... defined(Type[Resource['file','/tmp/file2']]) defined(Resource['file','/tmp/file2']) defined(File['/tmp/file2']) defined('$tmp_file') # ... but each of these returns `false`. defined(Type[Resource['exec','/tmp/file2']]) defined(Resource['exec','/tmp/file2']) defined(File['/tmp/file3']) defined('$tmp_file2') ~~~ - Since 2.7.0 - Since 3.6.0 variable reference and future parser types - Since 3.8.1 type specific requests with future parser - Since 4.0.0 includes all future parser features DOC ) do |_vals| Puppet::Parser::Functions::Error.is4x('defined') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/contain.rb
lib/puppet/parser/functions/contain.rb
# frozen_string_literal: true # Called within a class definition, establishes a containment # relationship with another class Puppet::Parser::Functions.newfunction( :contain, :arity => -2, :doc => "Contain one or more classes inside the current class. If any of these classes are undeclared, they will be declared as if called with the `include` function. Accepts a class name, an array of class names, or a comma-separated list of class names. A contained class will not be applied before the containing class is begun, and will be finished before the containing class is finished. You must use the class's full name; relative names are not allowed. In addition to names in string form, you may also directly use Class and Resource Type values that are produced by evaluating resource and relationship expressions. The function returns an array of references to the classes that were contained thus allowing the function call to `contain` to directly continue. - Since 4.0.0 support for Class and Resource Type values, absolute names - Since 4.7.0 an Array[Type[Class[n]]] is returned with all the contained classes " ) do |classes| # Call the 4.x version of this function in case 3.x ruby code uses this function Puppet.warn_once('deprecations', '3xfunction#contain', _("Calling function_contain via the Scope class is deprecated. Use Scope#call_function instead")) call_function('contain', classes) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/sprintf.rb
lib/puppet/parser/functions/sprintf.rb
# frozen_string_literal: true # Copyright (C) 2009 Thomas Bellman # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of Thomas Bellman shall # not be used in advertising or otherwise to promote the sale, use or # other dealings in this Software without prior written authorization # from Thomas Bellman. Puppet::Parser::Functions.newfunction( :sprintf, :type => :rvalue, :arity => -2, :doc => "Perform printf-style formatting of text. The first parameter is format string describing how the rest of the parameters should be formatted. See the documentation for the [`Kernel::sprintf` function](https://ruby-doc.org/core/Kernel.html) in Ruby for details. To use [named format](https://idiosyncratic-ruby.com/49-what-the-format.html) arguments, provide a hash containing the target string values as the argument to be formatted. For example: ```puppet notice sprintf(\"%<x>s : %<y>d\", { 'x' => 'value is', 'y' => 42 }) ``` This statement produces a notice of `value is : 42`." ) do |args| fmt = args[0] args = args[1..] begin return sprintf(fmt, *args) rescue KeyError => e if args.size == 1 && args[0].is_a?(Hash) # map the single hash argument such that all top level string keys are symbols # as that allows named arguments to be used in the format string. # result = {} args[0].each_pair { |k, v| result[k.is_a?(String) ? k.to_sym : k] = v } return sprintf(fmt, result) end raise e end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/strftime.rb
lib/puppet/parser/functions/strftime.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :strftime, :type => :rvalue, :arity => -3, :doc => <<~DOC Formats timestamp or timespan according to the directives in the given format string. The directives begins with a percent (%) character. Any text not listed as a directive will be passed through to the output string. A third optional timezone argument can be provided. The first argument will then be formatted to represent a local time in that timezone. The timezone can be any timezone that is recognized when using the '%z' or '%Z' formats, or the word 'current', in which case the current timezone of the evaluating process will be used. The timezone argument is case insensitive. The default timezone, when no argument is provided, or when using the keyword `default`, is 'UTC'. The directive consists of a percent (%) character, zero or more flags, optional minimum field width and a conversion specifier as follows: ``` %[Flags][Width]Conversion ``` ### Flags that controls padding | Flag | Meaning | ---- | --------------- | - | Don't pad numerical output | _ | Use spaces for padding | 0 | Use zeros for padding ### `Timestamp` specific flags | Flag | Meaning | ---- | --------------- | # | Change case | ^ | Use uppercase | : | Use colons for %z ### Format directives applicable to `Timestamp` (names and padding can be altered using flags): **Date (Year, Month, Day):** | Format | Meaning | | ------ | ------- | | Y | Year with century, zero-padded to at least 4 digits | | C | year / 100 (rounded down such as 20 in 2009) | | y | year % 100 (00..99) | | m | Month of the year, zero-padded (01..12) | | B | The full month name ("January") | | b | The abbreviated month name ("Jan") | | h | Equivalent to %b | | d | Day of the month, zero-padded (01..31) | | e | Day of the month, blank-padded ( 1..31) | | j | Day of the year (001..366) | **Time (Hour, Minute, Second, Subsecond):** | Format | Meaning | | ------ | ------- | | H | Hour of the day, 24-hour clock, zero-padded (00..23) | | k | Hour of the day, 24-hour clock, blank-padded ( 0..23) | | I | Hour of the day, 12-hour clock, zero-padded (01..12) | | l | Hour of the day, 12-hour clock, blank-padded ( 1..12) | | P | Meridian indicator, lowercase ("am" or "pm") | | p | Meridian indicator, uppercase ("AM" or "PM") | | M | Minute of the hour (00..59) | | S | Second of the minute (00..60) | | L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000 | | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified width are truncated to avoid carry up | **Time (Hour, Minute, Second, Subsecond):** | Format | Meaning | | ------ | ------- | | z | Time zone as hour and minute offset from UTC (e.g. +0900) | | :z | hour and minute offset from UTC with a colon (e.g. +09:00) | | ::z | hour, minute and second offset from UTC (e.g. +09:00:00) | | Z | Abbreviated time zone name or similar information. (OS dependent) | **Weekday:** | Format | Meaning | | ------ | ------- | | A | The full weekday name ("Sunday") | | a | The abbreviated name ("Sun") | | u | Day of the week (Monday is 1, 1..7) | | w | Day of the week (Sunday is 0, 0..6) | **ISO 8601 week-based year and week number:** The first week of YYYY starts with a Monday and includes YYYY-01-04. The days in the year before the first week are in the last week of the previous year. | Format | Meaning | | ------ | ------- | | G | The week-based year | | g | The last 2 digits of the week-based year (00..99) | | V | Week number of the week-based year (01..53) | **Week number:** The first week of YYYY that starts with a Sunday or Monday (according to %U or %W). The days in the year before the first week are in week 0. | Format | Meaning | | ------ | ------- | | U | Week number of the year. The week starts with Sunday. (00..53) | | W | Week number of the year. The week starts with Monday. (00..53) | **Seconds since the Epoch:** | Format | Meaning | | s | Number of seconds since 1970-01-01 00:00:00 UTC. | **Literal string:** | Format | Meaning | | ------ | ------- | | n | Newline character (\n) | | t | Tab character (\t) | | % | Literal "%" character | **Combination:** | Format | Meaning | | ------ | ------- | | c | date and time (%a %b %e %T %Y) | | D | Date (%m/%d/%y) | | F | The ISO 8601 date format (%Y-%m-%d) | | v | VMS date (%e-%^b-%4Y) | | x | Same as %D | | X | Same as %T | | r | 12-hour time (%I:%M:%S %p) | | R | 24-hour time (%H:%M) | | T | 24-hour time (%H:%M:%S) | **Example**: Using `strftime` with a `Timestamp`: ~~~ puppet $timestamp = Timestamp('2016-08-24T12:13:14') # Notice the timestamp using a format that notices the ISO 8601 date format notice($timestamp.strftime('%F')) # outputs '2016-08-24' # Notice the timestamp using a format that notices weekday, month, day, time (as UTC), and year notice($timestamp.strftime('%c')) # outputs 'Wed Aug 24 12:13:14 2016' # Notice the timestamp using a specific timezone notice($timestamp.strftime('%F %T %z', 'PST')) # outputs '2016-08-24 04:13:14 -0800' # Notice the timestamp using timezone that is current for the evaluating process notice($timestamp.strftime('%F %T', 'current')) # outputs the timestamp using the timezone for the current process ~~~ ### Format directives applicable to `Timespan`: | Format | Meaning | | ------ | ------- | | D | Number of Days | | H | Hour of the day, 24-hour clock | | M | Minute of the hour (00..59) | | S | Second of the minute (00..59) | | L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000. | | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified length are truncated to avoid carry up | The format directive that represents the highest magnitude in the format will be allowed to overflow. I.e. if no "%D" is used but a "%H" is present, then the hours will be more than 23 in case the timespan reflects more than a day. **Example**: Using `strftime` with a Timespan and a format ~~~ puppet $duration = Timespan({ hours => 3, minutes => 20, seconds => 30 }) # Notice the duration using a format that outputs <hours>:<minutes>:<seconds> notice($duration.strftime('%H:%M:%S')) # outputs '03:20:30' # Notice the duration using a format that outputs <minutes>:<seconds> notice($duration.strftime('%M:%S')) # outputs '200:30' ~~~ - Since 4.8.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('strftime') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/sha1.rb
lib/puppet/parser/functions/sha1.rb
# frozen_string_literal: true require 'digest/sha1' Puppet::Parser::Functions.newfunction(:sha1, :type => :rvalue, :arity => 1, :doc => "Returns a SHA1 hash value from a provided string.") do |args| Digest::SHA1.hexdigest(args[0]) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/match.rb
lib/puppet/parser/functions/match.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :match, :arity => 2, :doc => <<~DOC Matches a regular expression against a string and returns an array containing the match and any matched capturing groups. The first argument is a string or array of strings. The second argument is either a regular expression, regular expression represented as a string, or Regex or Pattern data type that the function matches against the first argument. The returned array contains the entire match at index 0, and each captured group at subsequent index values. If the value or expression being matched is an array, the function returns an array with mapped match results. If the function doesn't find a match, it returns 'undef'. **Example**: Matching a regular expression in a string ~~~ ruby $matches = "abc123".match(/[a-z]+[1-9]+/) # $matches contains [abc123] ~~~ **Example**: Matching a regular expressions with grouping captures in a string ~~~ ruby $matches = "abc123".match(/([a-z]+)([1-9]+)/) # $matches contains [abc123, abc, 123] ~~~ **Example**: Matching a regular expression with grouping captures in an array of strings ~~~ ruby $matches = ["abc123","def456"].match(/([a-z]+)([1-9]+)/) # $matches contains [[abc123, abc, 123], [def456, def, 456]] ~~~ - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('match') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/lest.rb
lib/puppet/parser/functions/lest.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :lest, :type => :rvalue, :arity => -2, :doc => <<~DOC Call a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) (which should accept no arguments) if the argument given to the function is `undef`. Returns the result of calling the lambda if the argument is `undef`, otherwise the given argument. The `lest` function is useful in a chain of `then` calls, or in general as a guard against `undef` values. The function can be used to call `fail`, or to return a default value. These two expressions are equivalent: ```puppet if $x == undef { do_things() } lest($x) || { do_things() } ``` **Example:** Using the `lest` function ```puppet $data = {a => [ b, c ] } notice $data.dig(a, b, c) .then |$x| { $x * 2 } .lest || { fail("no value for $data[a][b][c]" } ``` Would fail the operation because $data[a][b][c] results in `undef` (there is no `b` key in `a`). In contrast - this example: ```puppet $data = {a => { b => { c => 10 } } } notice $data.dig(a, b, c) .then |$x| { $x * 2 } .lest || { fail("no value for $data[a][b][c]" } ``` Would notice the value `20` * Since 4.5.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('lest') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/template.rb
lib/puppet/parser/functions/template.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction(:template, :type => :rvalue, :arity => -2, :doc => "Loads an ERB template from a module, evaluates it, and returns the resulting value as a string. The argument to this function should be a `<MODULE NAME>/<TEMPLATE FILE>` reference, which will load `<TEMPLATE FILE>` from a module's `templates` directory. (For example, the reference `apache/vhost.conf.erb` will load the file `<MODULES DIRECTORY>/apache/templates/vhost.conf.erb`.) This function can also accept: * An absolute path, which can load a template file from anywhere on disk. * Multiple arguments, which will evaluate all of the specified templates and return their outputs concatenated into a single string.") do |vals| if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::FEATURE_NOT_SUPPORTED_WHEN_SCRIPTING, { :feature => 'ERB template' } ) end vals.collect do |file| # Use a wrapper, so the template can't get access to the full # Scope object. debug "Retrieving template #{file}" wrapper = Puppet::Parser::TemplateWrapper.new(self) wrapper.file = file begin wrapper.result rescue => detail info = detail.backtrace.first.split(':') message = [] message << _("Failed to parse template %{file}:") % { file: file } message << _(" Filepath: %{file_path}") % { file_path: info[0] } message << _(" Line: %{line}") % { line: info[1] } message << _(" Detail: %{detail}") % { detail: detail } raise Puppet::ParseError, message.join("\n") + "\n" end end.join("") end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/require.rb
lib/puppet/parser/functions/require.rb
# frozen_string_literal: true # Requires the specified classes Puppet::Parser::Functions.newfunction( :require, :arity => -2, :doc => "Evaluate one or more classes, adding the required class as a dependency. The relationship metaparameters work well for specifying relationships between individual resources, but they can be clumsy for specifying relationships between classes. This function is a superset of the 'include' function, adding a class relationship so that the requiring class depends on the required class. Warning: using require in place of include can lead to unwanted dependency cycles. For instance the following manifest, with 'require' instead of 'include' would produce a nasty dependence cycle, because notify imposes a before between File[/foo] and Service[foo]: class myservice { service { foo: ensure => running } } class otherstuff { include myservice file { '/foo': notify => Service[foo] } } Note that this function only works with clients 0.25 and later, and it will fail if used with earlier clients. You must use the class's full name; relative names are not allowed. In addition to names in string form, you may also directly use Class and Resource Type values that are produced when evaluating resource and relationship expressions. - Since 4.0.0 Class and Resource types, absolute names - Since 4.7.0 Returns an Array[Type[Class]] with references to the required classes " ) do |classes| call_function('require', classes) Puppet.warn_once('deprecations', '3xfunction#require', _("Calling function_require via the Scope class is deprecated. Use Scope#call_function instead")) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/assert_type.rb
lib/puppet/parser/functions/assert_type.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :assert_type, :type => :rvalue, :arity => -3, :doc => <<~DOC Returns the given value if it is of the given [data type](https://puppet.com/docs/puppet/latest/lang_data.html), or otherwise either raises an error or executes an optional two-parameter [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html). The function takes two mandatory arguments, in this order: 1. The expected data type. 2. A value to compare against the expected data type. **Example**: Using `assert_type` ~~~ puppet $raw_username = 'Amy Berry' # Assert that $raw_username is a non-empty string and assign it to $valid_username. $valid_username = assert_type(String[1], $raw_username) # $valid_username contains "Amy Berry". # If $raw_username was an empty string or a different data type, the Puppet run would # fail with an "Expected type does not match actual" error. ~~~ You can use an optional lambda to provide enhanced feedback. The lambda takes two mandatory parameters, in this order: 1. The expected data type as described in the function's first argument. 2. The actual data type of the value. **Example**: Using `assert_type` with a warning and default value ~~~ puppet $raw_username = 'Amy Berry' # Assert that $raw_username is a non-empty string and assign it to $valid_username. # If it isn't, output a warning describing the problem and use a default value. $valid_username = assert_type(String[1], $raw_username) |$expected, $actual| { warning( "The username should be \'${expected}\', not \'${actual}\'. Using 'anonymous'." ) 'anonymous' } # $valid_username contains "Amy Berry". # If $raw_username was an empty string, the Puppet run would set $valid_username to # "anonymous" and output a warning: "The username should be 'String[1, default]', not # 'String[0, 0]'. Using 'anonymous'." ~~~ For more information about data types, see the [documentation](https://puppet.com/docs/puppet/latest/lang_data.html). - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('assert_type') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/next.rb
lib/puppet/parser/functions/next.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :next, :arity => -2, :doc => <<~DOC Immediately returns the given optional value from a block (lambda), function, class body or user defined type body. If a value is not given, an `undef` value is returned. This function does not return to the immediate caller. The signal produced to return a value bubbles up through the call stack until reaching a code block (lambda), function, class definition or definition of a user defined type at which point the value given to the function will be produced as the result of that body of code. An error is raised if the signal to return a value reaches the end of the call stack. **Example:** Using `next` in `each` ```puppet $data = [1,2,3] $data.each |$x| { if $x == 2 { next() } notice $x } ``` Would notice the values `1` and `3` **Example:** Using `next` to produce a value If logic consists of deeply nested conditionals it may be complicated to get out of the innermost conditional. A call to `next` can then simplify the logic. This example however, only shows the principle. ```puppet $data = [1,2,3] notice $data.map |$x| { if $x == 2 { next($x*100) }; $x*10 } ``` Would notice the value `[10, 200, 30]` * Also see functions `return` and `break` * Since 4.8.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('next') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/fail.rb
lib/puppet/parser/functions/fail.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :fail, :arity => -1, :doc => <<~DOC Fail with a parse error. Any parameters will be stringified, concatenated, and passed to the exception-handler. DOC ) do |vals| vals = vals.collect(&:to_s).join(" ") if vals.is_a? Array raise Puppet::ParseError, vals.to_s end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/create_resources.rb
lib/puppet/parser/functions/create_resources.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction(:create_resources, :arity => -3, :doc => <<-'ENDHEREDOC') do |args| Converts a hash into a set of resources and adds them to the catalog. **Note**: Use this function selectively. It's generally better to write resources in [Puppet](https://puppet.com/docs/puppet/latest/lang_resources.html), as resources created with `create_resource` are difficult to read and troubleshoot. This function takes two mandatory arguments: a resource type, and a hash describing a set of resources. The hash should be in the form `{title => {parameters} }`: # A hash of user resources: $myusers = { 'nick' => { uid => '1330', gid => allstaff, groups => ['developers', 'operations', 'release'], }, 'dan' => { uid => '1308', gid => allstaff, groups => ['developers', 'prosvc', 'release'], }, } create_resources(user, $myusers) A third, optional parameter may be given, also as a hash: $defaults = { 'ensure' => present, 'provider' => 'ldap', } create_resources(user, $myusers, $defaults) The values given on the third argument are added to the parameters of each resource present in the set given on the second argument. If a parameter is present on both the second and third arguments, the one on the second argument takes precedence. This function can be used to create defined resources and classes, as well as native resources. Virtual and Exported resources may be created by prefixing the type name with @ or @@ respectively. For example, the $myusers hash may be exported in the following manner: create_resources("@@user", $myusers) The $myusers may be declared as virtual resources using: create_resources("@user", $myusers) Note that `create_resources` filters out parameter values that are `undef` so that normal data binding and Puppet default value expressions are considered (in that order) for the final value of a parameter (just as when setting a parameter to `undef` in a Puppet language resource declaration). ENDHEREDOC if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'create_resources' } ) end raise ArgumentError, (_("create_resources(): wrong number of arguments (%{count}; must be 2 or 3)") % { count: args.length }) if args.length > 3 raise ArgumentError, _('create_resources(): second argument must be a hash') unless args[1].is_a?(Hash) if args.length == 3 raise ArgumentError, _('create_resources(): third argument, if provided, must be a hash') unless args[2].is_a?(Hash) end type, instances, defaults = args defaults ||= {} type_name = type.sub(/^@{1,2}/, '').downcase # Get file/line information from the Puppet stack (where call comes from in Puppet source) # If relayed via other Puppet functions in ruby that do not nest their calls, the source position # will be in the original Puppet source. # file, line = Puppet::Pops::PuppetStack.top_of_stack if type.start_with? '@@' exported = true virtual = true elsif type.start_with? '@' virtual = true end if type_name == 'class' && (exported || virtual) # cannot find current evaluator, so use another evaluator = Puppet::Pops::Parser::EvaluatingParser.new.evaluator # optionally fails depending on configured severity of issue evaluator.runtime_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE) end instances.map do |title, params| # Add support for iteration if title is an array resource_titles = title.is_a?(Array) ? title : [title] Puppet::Pops::Evaluator::Runtime3ResourceSupport.create_resources( file, line, self, virtual, exported, type_name, resource_titles, defaults.merge(params).filter_map do |name, value| value = nil if value == :undef Puppet::Parser::Resource::Param.new( :name => name, :value => value, # wide open to various data types, must be correct :source => source, # TODO: support :line => line, :file => file, :add => false ) end ) end.flatten.compact end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/split.rb
lib/puppet/parser/functions/split.rb
# frozen_string_literal: true module Puppet::Parser::Functions newfunction( :split, :type => :rvalue, :arity => 2, :doc => "\ Split a string variable into an array using the specified split regexp. *Example:* $string = 'v1.v2:v3.v4' $array_var1 = split($string, ':') $array_var2 = split($string, '[.]') $array_var3 = split($string, Regexp['[.:]']) `$array_var1` now holds the result `['v1.v2', 'v3.v4']`, while `$array_var2` holds `['v1', 'v2:v3', 'v4']`, and `$array_var3` holds `['v1', 'v2', 'v3', 'v4']`. Note that in the second example, we split on a literal string that contains a regexp meta-character (.), which must be escaped. A simple way to do that for a single character is to enclose it in square brackets; a backslash will also escape a single character." ) do |_args| Error.is4x('split') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/scanf.rb
lib/puppet/parser/functions/scanf.rb
# frozen_string_literal: true require 'scanf' Puppet::Parser::Functions.newfunction( :scanf, :type => :rvalue, :arity => 2, :doc => <<~DOC Scans a string and returns an array of one or more converted values based on the given format string. See the documentation of Ruby's String#scanf method for details about the supported formats (which are similar but not identical to the formats used in Puppet's `sprintf` function.) This function takes two mandatory arguments: the first is the string to convert, and the second is the format string. The result of the scan is an array, with each successfully scanned and transformed value. The scanning stops if a scan is unsuccessful, and the scanned result up to that point is returned. If there was no successful scan, the result is an empty array. ```puppet "42".scanf("%i") ``` You can also optionally pass a lambda to scanf, to do additional validation or processing. ```puppet "42".scanf("%i") |$x| { unless $x[0] =~ Integer { fail "Expected a well formed integer value, got '$x[0]'" } $x[0] } ``` - Since 4.0.0 DOC ) do |args| data = args[0] format = args[1] data.scanf(format) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/map.rb
lib/puppet/parser/functions/map.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :map, :type => :rvalue, :arity => -3, :doc => <<~DOC Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) to every value in a data structure and returns an array containing the results. This function takes two mandatory arguments, in this order: 1. An array or hash the function will iterate over. 2. A lambda, which the function calls for each element in the first argument. It can request one or two parameters. **Example**: Using the `map` function `$transformed_data = $data.map |$parameter| { <PUPPET CODE BLOCK> }` or `$transformed_data = map($data) |$parameter| { <PUPPET CODE BLOCK> }` When the first argument (`$data` in the above example) is an array, Puppet passes each value in turn to the lambda. **Example**: Using the `map` function with an array and a one-parameter lambda ~~~ puppet # For the array $data, return an array containing each value multiplied by 10 $data = [1,2,3] $transformed_data = $data.map |$items| { $items * 10 } # $transformed_data contains [10,20,30] ~~~ When the first argument is a hash, Puppet passes each key and value pair to the lambda as an array in the form `[key, value]`. **Example**: Using the `map` function with a hash and a one-parameter lambda ~~~ puppet # For the hash $data, return an array containing the keys $data = {'a'=>1,'b'=>2,'c'=>3} $transformed_data = $data.map |$items| { $items[0] } # $transformed_data contains ['a','b','c'] ~~~ When the first argument is an array and the lambda has two parameters, Puppet passes the array's indexes (enumerated from 0) in the first parameter and its values in the second parameter. **Example**: Using the `map` function with an array and a two-parameter lambda ~~~ puppet # For the array $data, return an array containing the indexes $data = [1,2,3] $transformed_data = $data.map |$index,$value| { $index } # $transformed_data contains [0,1,2] ~~~ When the first argument is a hash, Puppet passes its keys to the first parameter and its values to the second parameter. **Example**: Using the `map` function with a hash and a two-parameter lambda ~~~ puppet # For the hash $data, return an array containing each value $data = {'a'=>1,'b'=>2,'c'=>3} $transformed_data = $data.map |$key,$value| { $value } # $transformed_data contains [1,2,3] ~~~ - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('map') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/inline_template.rb
lib/puppet/parser/functions/inline_template.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction(:inline_template, :type => :rvalue, :arity => -2, :doc => "Evaluate a template string and return its value. See [the templating docs](https://puppet.com/docs/puppet/latest/lang_template.html) for more information. Note that if multiple template strings are specified, their output is all concatenated and returned as the output of the function.") do |vals| if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::FEATURE_NOT_SUPPORTED_WHEN_SCRIPTING, { :feature => 'ERB inline_template' } ) end require 'erb' vals.collect do |string| # Use a wrapper, so the template can't get access to the full # Scope object. wrapper = Puppet::Parser::TemplateWrapper.new(self) begin wrapper.result(string) rescue => detail raise Puppet::ParseError, _("Failed to parse inline template: %{detail}") % { detail: detail }, detail.backtrace end end.join("") end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/return.rb
lib/puppet/parser/functions/return.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :return, :arity => -2, :doc => <<~DOC Immediately returns the given optional value from a function, class body or user defined type body. If a value is not given, an `undef` value is returned. This function does not return to the immediate caller. If this function is called from within a lambda, the return action is from the scope of the function containing the lambda (top scope), not the function accepting the lambda (local scope). The signal produced to return a value bubbles up through the call stack until reaching a function, class definition or definition of a user defined type at which point the value given to the function will be produced as the result of that body of code. An error is raised if the signal to return a value reaches the end of the call stack. **Example:** Using `return` ```puppet function example($x) { # handle trivial cases first for better readability of # what follows if $x == undef or $x == [] or $x == '' { return false } # complex logic to determine if value is true true } notice example([]) # would notice false notice example(42) # would notice true ``` **Example:** Using `return` in a class ```puppet class example($x) { # handle trivial cases first for better readability of # what follows if $x == undef or $x == [] or $x == '' { # Do some default configuration of this class notice 'foo' return() } # complex logic configuring the class if something more interesting # was given in $x notice 'bar' } ``` When used like this: ```puppet class { example: x => [] } ``` The code would notice `'foo'`, but not `'bar'`. When used like this: ```puppet class { example: x => [some_value] } ``` The code would notice `'bar'` but not `'foo'` Note that the returned value is ignored if used in a class or user defined type. **Example:** Using `return` in a lambda ```puppet # Concatenate three strings into a single string formatted as a list. function getFruit() { with("apples", "oranges", "bananas") |$x, $y, $z| { return("${x}, ${y}, and ${z}") } notice "not reached" } $fruit = getFruit() notice $fruit # The output contains "apples, oranges, and bananas". # "not reached" is not output because the function returns its value within the # calling function's scope, which stops processing the calling function before # the `notice "not reached"` statement. # Using `return()` outside of a calling function results in an error. ``` * Also see functions `return` and `break` * Since 4.8.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('return') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/each.rb
lib/puppet/parser/functions/each.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :each, :type => :rvalue, :arity => -3, :doc => <<~DOC Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) repeatedly using each value in a data structure, then returns the values unchanged. This function takes two mandatory arguments, in this order: 1. An array or hash the function will iterate over. 2. A lambda, which the function calls for each element in the first argument. It can request one or two parameters. **Example**: Using the `each` function `$data.each |$parameter| { <PUPPET CODE BLOCK> }` or `each($data) |$parameter| { <PUPPET CODE BLOCK> }` When the first argument (`$data` in the above example) is an array, Puppet passes each value in turn to the lambda, then returns the original values. **Example**: Using the `each` function with an array and a one-parameter lambda ~~~ puppet # For the array $data, run a lambda that creates a resource for each item. $data = ["routers", "servers", "workstations"] $data.each |$item| { notify { $item: message => $item } } # Puppet creates one resource for each of the three items in $data. Each resource is # named after the item's value and uses the item's value in a parameter. ~~~ When the first argument is a hash, Puppet passes each key and value pair to the lambda as an array in the form `[key, value]` and returns the original hash. **Example**: Using the `each` function with a hash and a one-parameter lambda ~~~ puppet # For the hash $data, run a lambda using each item as a key-value array that creates a # resource for each item. $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"} $data.each |$items| { notify { $items[0]: message => $items[1] } } # Puppet creates one resource for each of the three items in $data, each named after the # item's key and containing a parameter using the item's value. ~~~ When the first argument is an array and the lambda has two parameters, Puppet passes the array's indexes (enumerated from 0) in the first parameter and its values in the second parameter. **Example**: Using the `each` function with an array and a two-parameter lambda ~~~ puppet # For the array $data, run a lambda using each item's index and value that creates a # resource for each item. $data = ["routers", "servers", "workstations"] $data.each |$index, $value| { notify { $value: message => $index } } # Puppet creates one resource for each of the three items in $data, each named after the # item's value and containing a parameter using the item's index. ~~~ When the first argument is a hash, Puppet passes its keys to the first parameter and its values to the second parameter. **Example**: Using the `each` function with a hash and a two-parameter lambda ~~~ puppet # For the hash $data, run a lambda using each item's key and value to create a resource # for each item. $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"} $data.each |$key, $value| { notify { $key: message => $value } } # Puppet creates one resource for each of the three items in $data, each named after the # item's key and containing a parameter using the item's value. ~~~ For an example that demonstrates how to create multiple `file` resources using `each`, see the Puppet [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) documentation. - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('each') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/lookup.rb
lib/puppet/parser/functions/lookup.rb
# frozen_string_literal: true module Puppet::Parser::Functions newfunction(:lookup, :type => :rvalue, :arity => -2, :doc => <<~'ENDHEREDOC') do |_args| Uses the Puppet lookup system to retrieve a value for a given key. By default, this returns the first value found (and fails compilation if no values are available), but you can configure it to merge multiple values into one, fail gracefully, and more. When looking up a key, Puppet will search up to three tiers of data, in the following order: 1. Hiera. 2. The current environment's data provider. 3. The indicated module's data provider, if the key is of the form `<MODULE NAME>::<SOMETHING>`. #### Arguments You must provide the name of a key to look up, and can optionally provide other arguments. You can combine these arguments in the following ways: * `lookup( <NAME>, [<VALUE TYPE>], [<MERGE BEHAVIOR>], [<DEFAULT VALUE>] )` * `lookup( [<NAME>], <OPTIONS HASH> )` * `lookup( as above ) |$key| { # lambda returns a default value }` Arguments in `[square brackets]` are optional. The arguments accepted by `lookup` are as follows: 1. `<NAME>` (string or array) --- The name of the key to look up. * This can also be an array of keys. If Puppet doesn't find anything for the first key, it will try again with the subsequent ones, only resorting to a default value if none of them succeed. 2. `<VALUE TYPE>` (data type) --- A [data type](https://puppet.com/docs/puppet/latest/lang_data_type.html) that must match the retrieved value; if not, the lookup (and catalog compilation) will fail. Defaults to `Data` (accepts any normal value). 3. `<MERGE BEHAVIOR>` (string or hash; see **"Merge Behaviors"** below) --- Whether (and how) to combine multiple values. If present, this overrides any merge behavior specified in the data sources. Defaults to no value; Puppet will use merge behavior from the data sources if present, and will otherwise do a first-found lookup. 4. `<DEFAULT VALUE>` (any normal value) --- If present, `lookup` returns this when it can't find a normal value. Default values are never merged with found values. Like a normal value, the default must match the value type. Defaults to no value; if Puppet can't find a normal value, the lookup (and compilation) will fail. 5. `<OPTIONS HASH>` (hash) --- Alternate way to set the arguments above, plus some less-common extra options. If you pass an options hash, you can't combine it with any regular arguments (except `<NAME>`). An options hash can have the following keys: * `'name'` --- Same as `<NAME>` (argument 1). You can pass this as an argument or in the hash, but not both. * `'value_type'` --- Same as `<VALUE TYPE>` (argument 2). * `'merge'` --- Same as `<MERGE BEHAVIOR>` (argument 3). * `'default_value'` --- Same as `<DEFAULT VALUE>` (argument 4). * `'default_values_hash'` (hash) --- A hash of lookup keys and default values. If Puppet can't find a normal value, it will check this hash for the requested key before giving up. You can combine this with `default_value` or a lambda, which will be used if the key isn't present in this hash. Defaults to an empty hash. * `'override'` (hash) --- A hash of lookup keys and override values. Puppet will check for the requested key in the overrides hash _first;_ if found, it returns that value as the _final_ value, ignoring merge behavior. Defaults to an empty hash. Finally, `lookup` can take a lambda, which must accept a single parameter. This is yet another way to set a default value for the lookup; if no results are found, Puppet will pass the requested key to the lambda and use its result as the default value. #### Merge Behaviors Puppet lookup uses a hierarchy of data sources, and a given key might have values in multiple sources. By default, Puppet returns the first value it finds, but it can also continue searching and merge all the values together. > **Note:** Data sources can use the special `lookup_options` metadata key to request a specific merge behavior for a key. The `lookup` function will use that requested behavior unless you explicitly specify one. The valid merge behaviors are: * `'first'` --- Returns the first value found, with no merging. Puppet lookup's default behavior. * `'unique'` (called "array merge" in classic Hiera) --- Combines any number of arrays and scalar values to return a merged, flattened array with all duplicate values removed. The lookup will fail if any hash values are found. * `'hash'` --- Combines the keys and values of any number of hashes to return a merged hash. If the same key exists in multiple source hashes, Puppet will use the value from the highest-priority data source; it won't recursively merge the values. * `'deep'` --- Combines the keys and values of any number of hashes to return a merged hash. If the same key exists in multiple source hashes, Puppet will recursively merge hash or array values (with duplicate values removed from arrays). For conflicting scalar values, the highest-priority value will win. * `{'strategy' => 'first|unique|hash'}` --- Same as the string versions of these merge behaviors. * `{'strategy' => 'deep', <DEEP OPTION> => <VALUE>, ...}` --- Same as `'deep'`, but can adjust the merge with additional options. The available options are: * `'knockout_prefix'` (string or undef) --- A string prefix to indicate a value should be _removed_ from the final result. Defaults to `undef`, which disables this feature. * `'sort_merged_arrays'` (boolean) --- Whether to sort all arrays that are merged together. Defaults to `false`. * `'merge_hash_arrays'` (boolean) --- Whether to merge hashes within arrays. Defaults to `false`. #### Examples Look up a key and return the first value found: lookup('ntp::service_name') Do a unique merge lookup of class names, then add all of those classes to the catalog (like `hiera_include`): lookup('classes', Array[String], 'unique').include Do a deep hash merge lookup of user data, but let higher priority sources remove values by prefixing them with `--`: lookup( { 'name' => 'users', 'merge' => { 'strategy' => 'deep', 'knockout_prefix' => '--', }, }) ENDHEREDOC Error.is4x('lookup') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/versioncmp.rb
lib/puppet/parser/functions/versioncmp.rb
# frozen_string_literal: true require_relative '../../../puppet/util/package' Puppet::Parser::Functions.newfunction(:versioncmp, :type => :rvalue, :arity => 2, :doc => "Compares two version numbers. Prototype: \$result = versioncmp(a, b) Where a and b are arbitrary version strings. This function returns: * `1` if version a is greater than version b * `0` if the versions are equal * `-1` if version a is less than version b Example: if versioncmp('2.6-1', '2.4.5') > 0 { notice('2.6-1 is > than 2.4.5') } This function uses the same version comparison algorithm used by Puppet's `package` type. ") do |args| return Puppet::Util::Package.versioncmp(args[0], args[1]) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/inline_epp.rb
lib/puppet/parser/functions/inline_epp.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction(:inline_epp, :type => :rvalue, :arity => -2, :doc => "Evaluates an Embedded Puppet (EPP) template string and returns the rendered text result as a String. `inline_epp('<EPP TEMPLATE STRING>', <PARAMETER HASH>)` The first argument to this function should be a string containing an EPP template. In most cases, the last argument is optional; if used, it should be a [hash](https://puppet.com/docs/puppet/latest/lang_data_hash.html) that contains parameters to pass to the template. - See the [template](https://puppet.com/docs/puppet/latest/lang_template.html) documentation for general template usage information. - See the [EPP syntax](https://puppet.com/docs/puppet/latest/lang_template_epp.html) documentation for examples of EPP. For example, to evaluate an inline EPP template and pass it the `docroot` and `virtual_docroot` parameters, call the `inline_epp` function like this: `inline_epp('docroot: <%= $docroot %> Virtual docroot: <%= $virtual_docroot %>', { 'docroot' => '/var/www/html', 'virtual_docroot' => '/var/www/example' })` Puppet produces a syntax error if you pass more parameters than are declared in the template's parameter tag. When passing parameters to a template that contains a parameter tag, use the same names as the tag's declared parameters. Parameters are required only if they are declared in the called template's parameter tag without default values. Puppet produces an error if the `inline_epp` function fails to pass any required parameter. An inline EPP template should be written as a single-quoted string or [heredoc](https://puppet.com/docs/puppet/latest/lang_data_string.html#heredocs). A double-quoted string is subject to expression interpolation before the string is parsed as an EPP template. For example, to evaluate an inline EPP template using a heredoc, call the `inline_epp` function like this: ~~~ puppet # Outputs 'Hello given argument planet!' inline_epp(@(END), { x => 'given argument' }) <%- | $x, $y = planet | -%> Hello <%= $x %> <%= $y %>! END ~~~ - Since 3.5 - Requires [future parser](https://puppet.com/docs/puppet/3.8/experiments_future.html) in Puppet 3.5 to 3.8") do |_arguments| Puppet::Parser::Functions::Error.is4x('inline_epp') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/regsubst.rb
lib/puppet/parser/functions/regsubst.rb
# frozen_string_literal: true # Copyright (C) 2009 Thomas Bellman # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of Thomas Bellman shall # not be used in advertising or otherwise to promote the sale, use or # other dealings in this Software without prior written authorization # from Thomas Bellman. module Puppet::Parser::Functions newfunction( :regsubst, :type => :rvalue, :arity => -4, :doc => " Perform regexp replacement on a string or array of strings. * *Parameters* (in order): * _target_ The string or array of strings to operate on. If an array, the replacement will be performed on each of the elements in the array, and the return value will be an array. * _regexp_ The regular expression matching the target string. If you want it anchored at the start and or end of the string, you must do that with ^ and $ yourself. * _replacement_ Replacement string. Can contain backreferences to what was matched using \\0 (whole match), \\1 (first set of parentheses), and so on. * _flags_ Optional. String of single letter flags for how the regexp is interpreted: - *E* Extended regexps - *I* Ignore case in regexps - *M* Multiline regexps - *G* Global replacement; all occurrences of the regexp in each target string will be replaced. Without this, only the first occurrence will be replaced. * _encoding_ Optional. How to handle multibyte characters. A single-character string with the following values: - *N* None - *E* EUC - *S* SJIS - *U* UTF-8 * *Examples* Get the third octet from the node's IP address: $i3 = regsubst($ipaddress,'^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$','\\3') Put angle brackets around each octet in the node's IP address: $x = regsubst($ipaddress, '([0-9]+)', '<\\1>', 'G') " ) do |_args| Error.is4x('regsubst') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/break.rb
lib/puppet/parser/functions/break.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :break, :arity => 0, :doc => <<~DOC Breaks the innermost iteration as if it encountered an end of input. This function does not return to the caller. The signal produced to stop the iteration bubbles up through the call stack until either terminating the innermost iteration or raising an error if the end of the call stack is reached. The break() function does not accept an argument. **Example:** Using `break` ```puppet $data = [1,2,3] notice $data.map |$x| { if $x == 3 { break() } $x*10 } ``` Would notice the value `[10, 20]` **Example:** Using a nested `break` ```puppet function break_if_even($x) { if $x % 2 == 0 { break() } } $data = [1,2,3] notice $data.map |$x| { break_if_even($x); $x*10 } ``` Would notice the value `[10]` * Also see functions `next` and `return` * Since 4.8.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('break') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/dig.rb
lib/puppet/parser/functions/dig.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :dig, :type => :rvalue, :arity => -1, :doc => <<~DOC Returns a value for a sequence of given keys/indexes into a structure, such as an array or hash. This function is used to "dig into" a complex data structure by using a sequence of keys / indexes to access a value from which the next key/index is accessed recursively. The first encountered `undef` value or key stops the "dig" and `undef` is returned. An error is raised if an attempt is made to "dig" into something other than an `undef` (which immediately returns `undef`), an `Array` or a `Hash`. **Example:** Using `dig` ```puppet $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}} notice $data.dig('a', 'b', 1, 'x') ``` Would notice the value 100. This is roughly equivalent to `$data['a']['b'][1]['x']`. However, a standard index will return an error and cause catalog compilation failure if any parent of the final key (`'x'`) is `undef`. The `dig` function will return undef, rather than failing catalog compilation. This allows you to check if data exists in a structure without mandating that it always exists. * Since 4.5.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('dig') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/then.rb
lib/puppet/parser/functions/then.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :then, :type => :rvalue, :arity => -2, :doc => <<~DOC Call a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) with the given argument unless the argument is undef. Return `undef` if argument is `undef`, and otherwise the result of giving the argument to the lambda. This is useful to process a sequence of operations where an intermediate result may be `undef` (which makes the entire sequence `undef`). The `then` function is especially useful with the function `dig` which performs in a similar way "digging out" a value in a complex structure. **Example:** Using `dig` and `then` ```puppet $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}} notice $data.dig(a, b, 1, x).then |$x| { $x * 2 } ``` Would notice the value 200 Contrast this with: ```puppet $data = {a => { b => [{x => 10, y => 20}, {ex => 100, why => 200}]}} notice $data.dig(a, b, 1, x).then |$x| { $x * 2 } ``` Which would notice `undef` since the last lookup of 'x' results in `undef` which is returned (without calling the lambda given to the `then` function). As a result there is no need for conditional logic or a temporary (non local) variable as the result is now either the wanted value (`x`) multiplied by 2 or `undef`. Calls to `then` can be chained. In the next example, a structure is using an offset based on using 1 as the index to the first element (instead of 0 which is used in the language). We are not sure if user input actually contains an index at all, or if it is outside the range of available names.args. **Example:** Chaining calls to the `then` function ```puppet # Names to choose from $names = ['Ringo', 'Paul', 'George', 'John'] # Structure where 'beatle 2' is wanted (but where the number refers # to 'Paul' because input comes from a source using 1 for the first # element). $data = ['singer', { beatle => 2 }] $picked = assert_type(String, # the data we are interested in is the second in the array, # a hash, where we want the value of the key 'beatle' $data.dig(1, 'beatle') # and we want the index in $names before the given index .then |$x| { $names[$x-1] } # so we can construct a string with that beatle's name .then |$x| { "Picked Beatle '${x}'" } ) ``` Would notice "Picked Beatle 'Paul'", and would raise an error if the result was not a String. * Since 4.5.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('then') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/reverse_each.rb
lib/puppet/parser/functions/reverse_each.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :reverse_each, :type => :rvalue, :arity => -1, :doc => <<~DOC Reverses the order of the elements of something that is iterable and optionally runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each element. This function takes one to two arguments: 1. An `Iterable` that the function will iterate over. 2. An optional lambda, which the function calls for each element in the first argument. It must request one parameter. **Example:** Using the `reverse_each` function ```puppet $data.reverse_each |$parameter| { <PUPPET CODE BLOCK> } ``` or ```puppet $reverse_data = $data.reverse_each ``` or ```puppet reverse_each($data) |$parameter| { <PUPPET CODE BLOCK> } ``` or ```puppet $reverse_data = reverse_each($data) ``` When no second argument is present, Puppet returns an `Iterable` that represents the reverse order of its first argument. This allows methods on `Iterable` to be chained. When a lambda is given as the second argument, Puppet iterates the first argument in reverse order and passes each value in turn to the lambda, then returns `undef`. **Example:** Using the `reverse_each` function with an array and a one-parameter lambda ``` puppet # Puppet will log a notice for each of the three items # in $data in reverse order. $data = [1,2,3] $data.reverse_each |$item| { notice($item) } ``` When no second argument is present, Puppet returns a new `Iterable` which allows it to be directly chained into another function that takes an `Iterable` as an argument. **Example:** Using the `reverse_each` function chained with a `map` function. ```puppet # For the array $data, return an array containing each # value multiplied by 10 in reverse order $data = [1,2,3] $transformed_data = $data.reverse_each.map |$item| { $item * 10 } # $transformed_data is set to [30,20,10] ``` **Example:** Using `reverse_each` function chained with a `map` in alternative syntax ```puppet # For the array $data, return an array containing each # value multiplied by 10 in reverse order $data = [1,2,3] $transformed_data = map(reverse_each($data)) |$item| { $item * 10 } # $transformed_data is set to [30,20,10] ``` * Since 4.4.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('reverse_each') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/with.rb
lib/puppet/parser/functions/with.rb
# frozen_string_literal: true Puppet::Parser::Functions.newfunction( :with, :type => :rvalue, :arity => -1, :doc => <<~DOC Call a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) with the given arguments and return the result. Since a lambda's scope is local to the lambda, you can use the `with` function to create private blocks of code within a class using variables whose values cannot be accessed outside of the lambda. **Example**: Using `with` ~~~ puppet # Concatenate three strings into a single string formatted as a list. $fruit = with("apples", "oranges", "bananas") |$x, $y, $z| { "${x}, ${y}, and ${z}" } $check_var = $x # $fruit contains "apples, oranges, and bananas" # $check_var is undefined, as the value of $x is local to the lambda. ~~~ - Since 4.0.0 DOC ) do |_args| Puppet::Parser::Functions::Error.is4x('with') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/functions/sha256.rb
lib/puppet/parser/functions/sha256.rb
# frozen_string_literal: true require 'digest/sha2' Puppet::Parser::Functions.newfunction(:sha256, :type => :rvalue, :arity => 1, :doc => "Returns a SHA256 hash value from a provided string.") do |args| Digest::SHA256.hexdigest(args[0]) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/resource.rb
lib/puppet/parser/ast/resource.rb
# frozen_string_literal: true # Instruction for Resource instantiation. # Instantiates resources of both native and user defined types. # class Puppet::Parser::AST::Resource < Puppet::Parser::AST::Branch attr_accessor :type, :instances, :exported, :virtual def initialize(argshash) Puppet.warn_once('deprecations', 'AST::Resource', _('Use of Puppet::Parser::AST::Resource is deprecated and not fully functional')) super(argshash) end # Evaluates resources by adding them to the compiler for lazy evaluation # and returning the produced resource references. # def evaluate(scope) # We want virtual to be true if exported is true. We can't # just set :virtual => self.virtual in the initialization, # because sometimes the :virtual attribute is set *after* # :exported, in which case it clobbers :exported if :exported # is true. Argh, this was a very tough one to track down. virt = virtual || exported # First level of implicit iteration: build a resource for each # instance. This handles things like: # file { '/foo': owner => blah; '/bar': owner => blah } @instances.map do |instance| # Evaluate all of the specified params. paramobjects = instance.parameters.map { |param| param.safeevaluate(scope) } resource_titles = instance.title.safeevaluate(scope) # it's easier to always use an array, even for only one name resource_titles = [resource_titles] unless resource_titles.is_a?(Array) fully_qualified_type, resource_titles = scope.resolve_type_and_titles(type, resource_titles) # Second level of implicit iteration; build a resource for each # title. This handles things like: # file { ['/foo', '/bar']: owner => blah } resource_titles.flatten.map do |resource_title| exceptwrap :type => Puppet::ParseError do resource = Puppet::Parser::Resource.new( fully_qualified_type, resource_title, :parameters => paramobjects, :file => file, :line => line, :exported => exported, :virtual => virt, :source => scope.source, :scope => scope, :strict => true ) if resource.resource_type.is_a? Puppet::Resource::Type resource.resource_type.instantiate_resource(scope, resource) end scope.compiler.add_resource(scope, resource) scope.compiler.evaluate_classes([resource_title], scope, false) if fully_qualified_type == 'class' resource end end end.flatten.compact end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/resourceparam.rb
lib/puppet/parser/ast/resourceparam.rb
# frozen_string_literal: true # The AST object for the parameters inside resource expressions # class Puppet::Parser::AST::ResourceParam < Puppet::Parser::AST::Branch attr_accessor :value, :param, :add def initialize(argshash) Puppet.warn_once('deprecations', 'AST::ResourceParam', _('Use of Puppet::Parser::AST::ResourceParam is deprecated and not fully functional')) super(argshash) end def each [@param, @value].each { |child| yield child } end # Return the parameter and the value. def evaluate(scope) value = @value.safeevaluate(scope) Puppet::Parser::Resource::Param.new( :name => @param, :value => value.nil? ? :undef : value, :source => scope.source, :line => line, :file => file, :add => add ) end def to_s "#{@param} => #{@value}" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/node.rb
lib/puppet/parser/ast/node.rb
# frozen_string_literal: true class Puppet::Parser::AST::Node < Puppet::Parser::AST::TopLevelConstruct attr_accessor :names, :context def initialize(names, context = {}) raise ArgumentError, _("names should be an array") unless names.is_a? Array if context[:parent] raise Puppet::DevError, _("Node inheritance is removed in Puppet 4.0.0. See http://links.puppet.com/puppet-node-inheritance-deprecation") end @names = names @context = context end def instantiate(modname) @names.map { |name| Puppet::Resource::Type.new(:node, name, @context.merge(:module_name => modname)) } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/block_expression.rb
lib/puppet/parser/ast/block_expression.rb
# frozen_string_literal: true # Evaluates contained expressions, produce result of the last # class Puppet::Parser::AST::BlockExpression < Puppet::Parser::AST::Branch def evaluate(scope) @children.reduce(nil) { |_, child| child.safeevaluate(scope) } end def sequence_with(other) Puppet::Parser::AST::BlockExpression.new(:children => children + other.children) end def to_s "[" + @children.collect(&:to_s).join(', ') + "]" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/resource_instance.rb
lib/puppet/parser/ast/resource_instance.rb
# frozen_string_literal: true # A simple container for a parameter for an object. Consists of a # title and a set of parameters. # class Puppet::Parser::AST::ResourceInstance < Puppet::Parser::AST::Branch attr_accessor :title, :parameters def initialize(argshash) Puppet.warn_once('deprecations', 'AST::ResourceInstance', _('Use of Puppet::Parser::AST::ResourceInstance is deprecated')) super(argshash) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/pops_bridge.rb
lib/puppet/parser/ast/pops_bridge.rb
# frozen_string_literal: true require_relative '../../../puppet/parser/ast/top_level_construct' require_relative '../../../puppet/pops' # The AST::Bridge contains classes that bridges between the new Pops based model # and the 3.x AST. This is required to be able to reuse the Puppet::Resource::Type which is # fundamental for the rest of the logic. # class Puppet::Parser::AST::PopsBridge # Bridges to one Pops Model Expression # The @value is the expression # This is used to represent the body of a class, definition, or node, and for each parameter's default value # expression. # class Expression < Puppet::Parser::AST::Leaf def to_s Puppet::Pops::Model::ModelTreeDumper.new.dump(@value) end def source_text source_adapter = Puppet::Pops::Utils.find_closest_positioned(@value) source_adapter ? source_adapter.extract_text() : nil end def evaluate(scope) evaluator = Puppet::Pops::Parser::EvaluatingParser.singleton object = evaluator.evaluate(scope, @value) evaluator.convert_to_3x(object, scope) end # Adapts to 3x where top level constructs needs to have each to iterate over children. Short circuit this # by yielding self. By adding this there is no need to wrap a pops expression inside an AST::BlockExpression # def each yield self end def sequence_with(other) if value.nil? # This happens when testing and not having a complete setup other else # When does this happen ? Ever ? raise "sequence_with called on Puppet::Parser::AST::PopsBridge::Expression - please report use case" # What should be done if the above happens (We don't want this to happen). # Puppet::Parser::AST::BlockExpression.new(:children => [self] + other.children) end end # The 3x requires code plugged in to an AST to have this in certain positions in the tree. The purpose # is to either print the content, or to look for things that needs to be defined. This implementation # cheats by always returning an empty array. (This allows simple files to not require a "Program" at the top. # def children [] end end class ExpressionSupportingReturn < Expression def evaluate(scope) catch(:return) do return catch(:next) do return super(scope) end end end end # Bridges the top level "Program" produced by the pops parser. # Its main purpose is to give one point where all definitions are instantiated (actually defined since the # Puppet 3x terminology is somewhat misleading - the definitions are instantiated, but instances of the created types # are not created, that happens when classes are included / required, nodes are matched and when resources are instantiated # by a resource expression (which is also used to instantiate a host class). # class Program < Puppet::Parser::AST::TopLevelConstruct attr_reader :program_model, :context def initialize(program_model, context = {}) @program_model = program_model @context = context @ast_transformer ||= Puppet::Pops::Model::AstTransformer.new(@context[:file]) end # This is the 3x API, the 3x AST searches through all code to find the instructions that can be instantiated. # This Pops-model based instantiation relies on the parser to build this list while parsing (which is more # efficient as it avoids one full scan of all logic via recursive enumeration/yield) # def instantiate(modname) @program_model.definitions.map do |d| case d when Puppet::Pops::Model::HostClassDefinition instantiate_HostClassDefinition(d, modname) when Puppet::Pops::Model::ResourceTypeDefinition instantiate_ResourceTypeDefinition(d, modname) when Puppet::Pops::Model::NodeDefinition instantiate_NodeDefinition(d, modname) else loaders = Puppet::Pops::Loaders.loaders loaders.instantiate_definition(d, loaders.find_loader(modname)) # The 3x logic calling this will not know what to do with the result, it is compacted away at the end nil end end.flatten().compact() # flatten since node definition may have returned an array # Compact since 4x definitions are not understood by compiler end def evaluate(scope) Puppet::Pops::Parser::EvaluatingParser.singleton.evaluate(scope, program_model) end # Adapts to 3x where top level constructs needs to have each to iterate over children. Short circuit this # by yielding self. This means that the HostClass container will call this bridge instance with `instantiate`. # def each yield self end # Returns true if this Program only contains definitions def is_definitions_only? is_definition?(program_model) end private def is_definition?(o) case o when Puppet::Pops::Model::Program is_definition?(o.body) when Puppet::Pops::Model::BlockExpression o.statements.all { |s| is_definition?(s) } when Puppet::Pops::Model::Definition true else false end end def instantiate_Parameter(o) # 3x needs parameters as an array of `[name]` or `[name, value_expr]` if o.value [o.name, Expression.new(:value => o.value)] else [o.name] end end def create_type_map(definition) result = {} # No need to do anything if there are no parameters return result unless definition.parameters.size > 0 # No need to do anything if there are no typed parameters typed_parameters = definition.parameters.select(&:type_expr) return result if typed_parameters.empty? # If there are typed parameters, they need to be evaluated to produce the corresponding type # instances. This evaluation requires a scope. A scope is not available when doing deserialization # (there is also no initialized evaluator). When running apply and test however, the environment is # reused and we may reenter without a scope (which is fine). A debug message is then output in case # there is the need to track down the odd corner case. See {#obtain_scope}. # scope = obtain_scope if scope evaluator = Puppet::Pops::Parser::EvaluatingParser.singleton typed_parameters.each do |p| result[p.name] = evaluator.evaluate(scope, p.type_expr) end end result end # Obtains the scope or issues a warning if :global_scope is not bound def obtain_scope Puppet.lookup(:global_scope) do # This occurs when testing and when applying a catalog (there is no scope available then), and # when running tests that run a partial setup. # This is bad if the logic is trying to compile, but a warning can not be issues since it is a normal # use case that there is no scope when requesting the type in order to just get the parameters. Puppet.debug { _("Instantiating Resource with type checked parameters - scope is missing, skipping type checking.") } nil end end # Produces a hash with data for Definition and HostClass def args_from_definition(o, modname, expr_class = Expression) args = { :arguments => o.parameters.collect { |p| instantiate_Parameter(p) }, :argument_types => create_type_map(o), :module_name => modname } unless is_nop?(o.body) args[:code] = expr_class.new(:value => o.body) end @ast_transformer.merge_location(args, o) end def instantiate_HostClassDefinition(o, modname) args = args_from_definition(o, modname, ExpressionSupportingReturn) args[:parent] = absolute_reference(o.parent_class) Puppet::Resource::Type.new(:hostclass, o.name, @context.merge(args)) end def instantiate_ResourceTypeDefinition(o, modname) instance = Puppet::Resource::Type.new(:definition, o.name, @context.merge(args_from_definition(o, modname, ExpressionSupportingReturn))) Puppet::Pops::Loaders.register_runtime3_type(instance.name, o.locator.to_uri(o)) instance end def instantiate_NodeDefinition(o, modname) args = { :module_name => modname } unless is_nop?(o.body) args[:code] = Expression.new(:value => o.body) end unless is_nop?(o.parent) args[:parent] = @ast_transformer.hostname(o.parent) end args = @ast_transformer.merge_location(args, o) host_matches = @ast_transformer.hostname(o.host_matches) host_matches.collect do |name| Puppet::Resource::Type.new(:node, name, @context.merge(args)) end end def code Expression.new(:value => @value) end def is_nop?(o) @ast_transformer.is_nop?(o) end def absolute_reference(ref) if ref.nil? || ref.empty? || ref.start_with?('::') ref else "::#{ref}" end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/leaf.rb
lib/puppet/parser/ast/leaf.rb
# frozen_string_literal: true # The base class for all of the leaves of the parse trees. These # basically just have types and values. Both of these parameters # are simple values, not AST objects. # class Puppet::Parser::AST::Leaf < Puppet::Parser::AST attr_accessor :value, :type # Return our value. def evaluate(scope) @value end def match(value) @value == value end def to_s @value.to_s unless @value.nil? end def initialize(value: nil, file: nil, line: nil, pos: nil) @value = value super(file: file, line: line, pos: pos) end end # Host names, either fully qualified or just the short name, or even a regex # class Puppet::Parser::AST::HostName < Puppet::Parser::AST::Leaf def initialize(value: nil, file: nil, line: nil, pos: nil) super(value: value, file: file, line: line, pos: pos) # Note that this is an AST::Regex, not a Regexp unless @value.is_a?(Regex) @value = @value.to_s.downcase if @value =~ /[^-\w.]/ raise Puppet::DevError, _("'%{value}' is not a valid hostname") % { value: @value } end end end # implementing eql? and hash so that when an HostName is stored # in a hash it has the same hashing properties as the underlying value def eql?(value) @value.eql?(value.is_a?(HostName) ? value.value : value) end def hash @value.hash end end class Puppet::Parser::AST::Regex < Puppet::Parser::AST::Leaf def initialize(value: nil, file: nil, line: nil, pos: nil) super(value: value, file: file, line: line, pos: pos) # transform value from hash options unless it is already a regular expression @value = Regexp.new(@value) unless @value.is_a?(Regexp) end # we're returning self here to wrap the regexp and to be used in places # where a string would have been used, without modifying any client code. # For instance, in many places we have the following code snippet: # val = @val.safeevaluate(@scope) # if val.match(otherval) # ... # end # this way, we don't have to modify this test specifically for handling # regexes. # def evaluate(scope) self end def match(value) @value.match(value) end def to_s Puppet::Pops::Types::PRegexpType.regexp_to_s_with_delimiters(@value) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/top_level_construct.rb
lib/puppet/parser/ast/top_level_construct.rb
# frozen_string_literal: true # The base class for AST nodes representing top level things: # hostclasses, definitions, and nodes. class Puppet::Parser::AST::TopLevelConstruct < Puppet::Parser::AST end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser/ast/hostclass.rb
lib/puppet/parser/ast/hostclass.rb
# frozen_string_literal: true require_relative '../../../puppet/parser/ast/top_level_construct' class Puppet::Parser::AST::Hostclass < Puppet::Parser::AST::TopLevelConstruct attr_accessor :name, :context def initialize(name, context = {}) @context = context @name = name end def instantiate(modname) new_class = Puppet::Resource::Type.new(:hostclass, @name, @context.merge(:module_name => modname)) all_types = [new_class] if code code.each do |nested_ast_node| if nested_ast_node.respond_to? :instantiate all_types += nested_ast_node.instantiate(modname) end end end all_types end def code @context[:code] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false