edmamerto
edmamerto

Reputation: 8155

Chef understanding only_if in execute resource

I have here an execute block that looks like this

execute 'uninstall_datadog' do
  command 'sudo apt-get --purge remove datadog-agent -y'
  only_if 'command -v datadog-agent'
end

So my understanding is if exit status of only_if is not 0 then this block will not execute. Is this true?

Upvotes: 1

Views: 1148

Answers (2)

edmamerto
edmamerto

Reputation: 8155

command is a bash builtin, looks like might not be executing as bash. bash -c "command -v datadog-agent" would work, but could also use which datadog-agent instead.

Upvotes: 0

Roland
Roland

Reputation: 1426

Yes.

However I see some problems with your example:

  1. the built-in package resource is able to remove a package if it is installed.
  package 'datadog-agent' do
    action :purge
    options '--yes' # not sure about this
  end

If the package is not installed (anymore), chef will just skip it. See https://docs.chef.io/resource_package.html for more details.

  1. usually chef runs as root so the sudo command is not needed in execute commands.

  2. only_if by default runs in the environment of the chef-client/chef-solo/chef-apply process. See https://docs.chef.io/resource_common.html#arguments you'll have to adjust environment variables like PATH when impersonating as another user

Upvotes: 3

Related Questions