From cf6cb773c327098ee850fbffb17ce3564895dfa4 Mon Sep 17 00:00:00 2001 From: Christopher Thorn Date: Thu, 14 Mar 2024 21:33:39 -0700 Subject: [PATCH] (#9292) New command line flag for puppet resource, fail See discussion in issue #9292. What this PR adds is the ability for on the command line if --fail is passed then the `puppet resource` command will exit with a non zero return code. --- lib/puppet/application/resource.rb | 11 +++++++++-- spec/unit/application/resource_spec.rb | 10 ++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/puppet/application/resource.rb b/lib/puppet/application/resource.rb index cbbe671f9e3..0c39a6c1aae 100644 --- a/lib/puppet/application/resource.rb +++ b/lib/puppet/application/resource.rb @@ -15,6 +15,7 @@ def preinit option("--verbose", "-v") option("--edit", "-e") option("--to_yaml", "-y") + option('--fail', '-f') option("--types", "-t") do |_arg| env = Puppet.lookup(:environments).get(Puppet[:environment]) || create_default_environment @@ -109,6 +110,9 @@ def help Output found resources in yaml format, suitable to use with Hiera and create_resources. + * --fail: + Fails and returns an exit code of 1 if the resource could not be modified. + EXAMPLE ------- This example uses `puppet resource` to return a Puppet configuration for @@ -236,8 +240,11 @@ def find_or_save_resources(type, name, params) resource = Puppet::Resource.new(type, name, :parameters => params) # save returns [resource that was saved, transaction log from applying the resource] - save_result = Puppet::Resource.indirection.save(resource, key) - [save_result.first] + save_result, report = Puppet::Resource.indirection.save(resource, key) + status = report.resource_statuses[resource.ref] + raise "Failed to manage resource #{resource.ref}" if status&.failed? && options[:fail] + + [save_result] end else if type == "file" diff --git a/spec/unit/application/resource_spec.rb b/spec/unit/application/resource_spec.rb index b257696eac8..901fb4a9bb0 100644 --- a/spec/unit/application/resource_spec.rb +++ b/spec/unit/application/resource_spec.rb @@ -118,12 +118,19 @@ @resource_app.main end + before :each do + allow(@res).to receive(:ref).and_return("type/name") + end + it "should add given parameters to the object" do allow(@resource_app.command_line).to receive(:args).and_return(['type','name','param=temp']) expect(Puppet::Resource.indirection).to receive(:save).with(@res, 'type/name').and_return([@res, @report]) expect(Puppet::Resource).to receive(:new).with('type', 'name', {:parameters => {'param' => 'temp'}}).and_return(@res) + resource_status = instance_double('Puppet::Resource::Status') + allow(@report).to receive(:resource_statuses).and_return({'type/name' => resource_status}) + allow(resource_status).to receive(:failed?).and_return(false) @resource_app.main end end @@ -140,6 +147,9 @@ def exists? true end + def string=(value) + end + def string Puppet::Util::Execution::ProcessOutput.new('test', 0) end