Search code examples
puppet

How to get list of applied resources


I'm trying to get a list of applied resources of a specific type to use their attribute values.

I have a custom resource (define) that creates a file in a particular directory. I'm using it in entirely different places of my code. I'm trying to purge from that directory all things that haven't been defined in my puppet code. In other words, I'm trying to manage the content of that directory fully. But I can't get the list of all defined resources of this type to obtain the files I'm managing. Below is some redacted code to clarify

The custom resource

define scheduler::job (
...
) {
  $job_name = $title
  $jobs_dir = $scheduler::jobs_dir

  file { "${jobs_dir}/${job_name}.yaml":
    ensure  => file,
    mode    => '0640',
    content => template('scheduler/job.yaml.erb'),
    notify  => Exec[$scheduler::reload_exec],
  }
}

How it applies

scheduler::job { 'job-1': }
scheduler::job { 'job-2': }

What I'm trying to do

file { $scheduler::jobs_dir:
  ensure  => directory,
  group   => $group,
  mode    => '0640',
  owner   => $user,
  path    => $scheduler::jobs_dir,
  purge   => true,
  recurse => true,
  force   => true,
  ignore  => <<LIST OF CREATED FILES AKA JOB_NAME>>,
}

I've tried to use resource collectors, but as mentioned in the documentation, they can be used only for amending resource attributes or as the operand of a chaining statement.

I've also tried to use resource references, but it seems I can't get an array of all resources: I still need to provide some names.


Solution

  • It turns out you can use purge + recurse in the file resource definition to purge all non-managed by puppet files. So the solution is pretty simple:

    file { $scheduler::jobs_dir:
      ensure  => directory,
      purge   => true,
      recurse => true,
    }