14

I've been trying to figure out a way to test if a resource is already defined in another file, and if not create it? A quick example:

  if File[$local_container] {
    alert("Testing - It existed $local_container")
  } else {
    file{ "$local_container":
      ensure => directory,
    }
  }

However - File[$local_container] always seems to evaluate to true. Is there a way to do this?

4 Answers 4

10

The better way of doing this is by making use of ensure_resource function from puppetlabs stdlib

It takes a resource type, title, and a list of attributes that describe a resource as parameters.

say you have test case to only create the resource if it does not already exist-

ensure_resource('package', 'test-pkg', {'ensure' => 'present'})
1
  • This seems much cleaner, passing the checkmark this way. Thanks for the tip!
    – gnarf
    Jan 25, 2015 at 15:25
15

Do you mean "test if a resource is already defined"? If you define a resource (ie, file {}, etc) Puppet will create what you're describing if doesn't already exist (assuming you pass ensure => present, of course).

To check if a resource is already defined in the catalog or not:

mark-draytons-macbook:~ mark$ cat test.pp 
file { "/tmp/foo": ensure => present }

if defined(File["/tmp/foo"]) {
  alert("/tmp/foo is defined")
} else {
  alert("/tmp/foo is not defined")
}

if defined(File["/tmp/bar"]) {
  alert("/tmp/bar is defined")
} else {
  alert("/tmp/bar is not defined")
}

mark-draytons-macbook:~ mark$ puppet test.pp 
alert: Scope(Class[main]): /tmp/foo is defined
alert: Scope(Class[main]): /tmp/bar is not defined
notice: //File[/tmp/foo]/ensure: created

Note: defined() is dependent on parse order.

1
  • 5
    That "depends on parse order" part makes it almost useless.
    – joerx
    Apr 1, 2014 at 2:47
2

Or....

unless File["${local_container}"] {
  file{ "${local_container}":
     ensure => directory,
  }
}

And do keep an eye on those quotes and curly braces....

-3

simply,

file{ "$local_container":
  ensure => directory,
  replace => false,
}
1
  • Nope, if the "$local_container" file was already defined somewhere else (like say by something that wanted to control the permissions/owner) you can't define the same resource twice.
    – gnarf
    Jun 3, 2014 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.