0

I'm pretty much a novice in speaking Ruby. I'm trying to write a template (.erb) for Puppet. My goal is to based on this variable:

$c_repo = 'repo1,repo1-condb,repo2,....'

to write a template, which in turn shall create a cron-job file like this:

43 2 * * * root /etc/zmfs/zmfs-check.sh repo1 >> /var/log/zmfs.log 2>&1
45 2 * * * root /etc/zmfs/zmfs-check.sh repo1-condb >> /var/log/zmfs.log 2>&1
....

I can create a fairly simple one with single value though:

$c_repo = 'repo1'
43 2 * * * root /etc/zmfs/zmfs-check.sh <%= c_repo %> >> /var/log/zmfs.log 2>&1

but just can't figure out how to create the loop for the list. Any help greatly appreciated. Cheers!!

MacUsers
  • 2,091
  • 3
  • 35
  • 56

1 Answers1

1

This should work:

<% c_repo.split(',').each_with_index do |repo, i| -%>
<%= (i*2)%60 %> 2 * * * root /etc/zmfs/zmfs-check.sh <%= repo %> /var/log/zmfs.log 2>&1
<% end -%>

Output:

0 2 * * * root /etc/zmfs/zmfs-check.sh repo1 /var/log/zmfs.log 2>&1
2 2 * * * root /etc/zmfs/zmfs-check.sh repo1-condb /var/log/zmfs.log 2>&1
4 2 * * * root /etc/zmfs/zmfs-check.sh repo2 /var/log/zmfs.log 2>&1
Raphael
  • 1,701
  • 15
  • 26
  • when I let Puppet to run this template, I get this error: `private method 'split' called for nil:NilClass`. Any idea what might be the problem? Thanks! – MacUsers Dec 07 '11 at 14:58
  • Sure you've read this, but just for posterity here's the Puppet template doc page: http://docs.puppetlabs.com/guides/templating.html – Raphael Dec 07 '11 at 15:42
  • Added a dash to closing tags (`-%>`) so that undesirable whitespace isn't put into your cron-job. – Raphael Dec 07 '11 at 15:45
  • Found it: it should should be `<% c_repo.split(',').each_with_index do |repo, i| -%>` i.e. without the `$` sign. But it's adding 2 whitespace at the beginning of the every line. it's taking the "indenting" literally. cheers!! – MacUsers Dec 07 '11 at 18:09
  • Cool, glad it worked for you. I updated my answer to reflect what actually worked. – Raphael Dec 07 '11 at 19:20
  • Just a quick question: How can I convert that comma separated list to a space delimited string, so that when the template file is run, I can get something like `for px in repo1 repo1-condb repo2 ...`? Cheers!! – MacUsers Dec 09 '11 at 13:46
  • 1
    See: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-split http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-join For example: s.split(',').join(' ') – Raphael Dec 09 '11 at 19:59
  • Thanks! worked just fine. I just changed the `split()` bit to be the in the safe-side: `c_repo.split(/\s*,\s*/).join(' ')`. Thanks for the links as well, really very useful for me. – MacUsers Dec 12 '11 at 10:15