user53029
user53029

Reputation: 695

run puppet class only if condition is met

I've coded a puppet module that I only want to run if selinux is either enforcing or permissive. If its disabled, I want puppet to ignore the class. I'm having a difficult time though trying to find the right conditional format. Here's what I have so far:

 class some-class {

 $selinux='/usr/bin/getenforce'     

 exec { "some command":
      command => "some command",
      onlyif => [ $selinux == Enforcing, $selinux == Permissive' ],
      timeout => 30
      }
      }

This does not work on a puppet run and I get a "Could not find command '$selinux'. I've been googling all day but cant seem to find how to structure this correctly.

Upvotes: 0

Views: 2776

Answers (2)

John Bollinger
John Bollinger

Reputation: 180093

In the first place, the idiomatic way to do this would be to create a custom fact that determines nodes' SELinux enforcement status. In your Puppet manifests you would then use an ordinary Puppet conditional based on the value of that fact. For example,

if $selinux_enforcement in ['Permissive', 'Enforcing'] {
  exec { "some command":
    timeout => 30
  }
}

But if you want specifically to use the unless or onlyif property of an Exec resource to control whether to run that Exec's command, then you have to understand that those properties specify operating system commands to run to perform the evaluation. Their exit codes convey whether to proceed with running the main command. For a Linux target, using the default Exec provider, posix, you might do something like this:

exec { "some command":
  path => [ '/bin', '/usr/bin', '/sbin', '/usr/sbin' ],
  timeout => 30,
  onlyif => 'bash -c "case $(getenforce) in Enforcing|Permissive) exit 0;; *) exit 1;; esac"' ,
}

As an aside, do note that the SELinux software suite typically contains a command selinuxenabled, which addresses the question more directly than getenforce does. Aimed at use in scripts, this command conveys its result via its exit status, so it might be a better candidate for your onlyif, simplifying it to just:

  onlyif => 'selinuxenabled'

Upvotes: 1

yodog
yodog

Reputation: 6232

Are you sure getenforce is in /usr/bin/?

Try this to verify:

root@lab:~# which getenforce
/sbin/getenforce

You will also run into several other errors with your code, since you didn't quote your strings, you tried to get a boolean from a string comparison, etc.

Drop you $selinux variable and use only the code below

exec {
    "rasg":
        command => "echo rasg > /tmp/rasg.txt",
        onlyif  => "getenforce | egrep -q 'Enforcing|Permissive'",
        path    => [ "/bin", "/sbin", "/usr/bin" ],
        timeout => 30,
    ;
}

Upvotes: 1

Related Questions