3

I want to check "if dir exists" condition with puppet how it done here How to do a file/dir exists conditional in Puppet? but then if i write

  exec { 'check_presence':
    command => "true",
    path    =>  ["/usr/bin","/usr/sbin", "/bin"],
    onlyif  => "test -d /test"
  }
  file { '/test/123':
    ensure  => directory,
    mode    => '0644',
    require => Exec['check_presence']
  }

from exec i get alwyas true, and puppet always try to create /test/123

Debug: Exec[check_presence](provider=posix): Executing check 'test -e /test'
Debug: Executing 'test -e /test'

Error: Cannot create /test/123; parent directory /test does not exist
Error: /Stage[main]/tst::test/File[/test]/ensure: change from absent to directory failed: Cannot create /test/123; parent directory /test does not exist

Why he do it?! And how i must check parent directory exists?!

My puppet is 3.8

UPD I don't want to create /test ! I want to create /test/123 ONLY if /test already exists!

user423253
  • 33
  • 4
  • The question you link to actually does have an answer that works - it's [the one by Mike Taylor](https://serverfault.com/a/851172/120438). – Jenny D Jul 04 '17 at 08:08
  • Possible duplicate of [How to do a file/dir exists conditional in Puppet?](https://serverfault.com/questions/516917/how-to-do-a-file-dir-exists-conditional-in-puppet) – Jenny D Jul 04 '17 at 08:08

2 Answers2

1

If you don't want to create /test itself I believe you'll have to do both things in an exec:

exec { '/usr/bin/install /test/123':
  onlyif  => "/usr/bin/test -d /test"
}

Using install rather than mkdir enables setting properties like mode in the same command.


The easiest way to create parent directories is to chain files:

file { '/test':
  ensure  => directory,
  mode    => '0644',
} ->
file { '/test/123':
  ensure  => directory,
  mode    => '0644',
}

The semantics of your code simply requires the exec to "be instantiated" (that is, run) before the child directory is created. There is no optionality implied by this - true will run if /test exists, otherwise true does not run.

l0b0
  • 1,140
  • 1
  • 8
  • 17
1

puppet doesn't have one native function for this, the only workaround:

mkdir -p your_module_path/lib/puppet/parser/functions/ now you need to create this file directory_exists.rb with this code:

require 'puppet'

module Puppet::Parser::Functions
  newfunction(:directory_exists, :type => :rvalue) do |args|
    if File.directory?(args[0])
      return true
    else
      return false
    end
  end
end

Now in your puppet code, you can use the function:

if directory_exists('/test') {
  file { '/test/123':
    ensure  => directory,
    mode    => '0644',
    owner   => 'root',
    group   => 'root',
  }
}
c4f4t0r
  • 5,301
  • 3
  • 31
  • 42