diff --git a/lib/inspec/cli.rb b/lib/inspec/cli.rb index 19f86c1bd..57071ac2f 100644 --- a/lib/inspec/cli.rb +++ b/lib/inspec/cli.rb @@ -155,6 +155,13 @@ class Inspec::InspecCLI < Inspec::BaseCLI # rubocop:disable Metrics/ClassLength configure_logger(opts) o = opts.dup + # print error if user passed --sudo but with no --target + if opts[:sudo] && opts[:target].nil? + Inspec::Log.error('--sudo is only valid when running against a remote host using --target') + Inspec::Log.error('To run InSpec locally with elevated privileges, run `sudo inspec exec ...`') + exit 1 + end + # run tests run_tests(targets, o) rescue StandardError => e diff --git a/test/functional/inspec_exec_test.rb b/test/functional/inspec_exec_test.rb index ad1e68dcb..ec77f6cb8 100644 --- a/test/functional/inspec_exec_test.rb +++ b/test/functional/inspec_exec_test.rb @@ -248,4 +248,12 @@ Test Summary: \e[38;5;41m2 successful\e[0m, \e[38;5;9m0 failures\e[0m, \e[38;5;2 out.stdout.force_encoding(Encoding::UTF_8).must_include "Summary: \e[38;5;41m0 successful\e[0m, \e[38;5;9m0 failures\e[0m, \e[38;5;247m2 skipped\e[0m\n" end end + + describe 'when trying to use --sudo with a local target' do + it 'must print an error and exit' do + out = inspec("exec #{File.join(profile_path, 'profile-support-skip')} --sudo") + out.stdout.force_encoding(Encoding::UTF_8).must_include "--sudo is only valid when running against a remote host using --target" + out.exit_status.must_equal 1 + end + end end