Search code examples
rubypuppeterb

puppet erb dynamic content


site.pp

class httpd_conf_files ($repos) {
    ensure_packages(['httpd'], {'ensure' => 'present'})
    $repos.each |String $repo| {
    file {"/etc/httpd/conf.d/${repo}_repo1.conf":
                                  ensure  => file,
                                  mode    => '0644',
                                      content => template('deploy/repos.erb'),
          }
      }
}

nodes.pp

node 'repo-web-c010' {
                  class { httpd_conf_files:
                           repos => ['centos','ubuntu'],
                  }
}

However, both files centos_repo1.conf and ubuntu_repo1.conf have the same content.

repos.erb

    <% @repos.each do |rep|
    if rep == "centos"
        $x      = "/opt/repos/yum/"+rep
                 $_repo  = rep
         else
                 $x      = "/opt/repos/"+rep
                 $_repo  = rep
         end

    end -%>
    Alias /<%=$_repo%> <%=$x%>
    DocumentRoot  <%=$x%>
    IndexOptions NameWidth=* +SuppressDescription
    <Directory <%=$x%>>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog logs/<%=$_repo%>_repo1_error.log
    LogLevel warn

    CustomLog logs/<%=$_repo%>_repo1_access.log combined

Can someone enlighten me what's wrong?


Solution

  • The logic in your ERB template, as hinted at in a comment, is invalid.

    Because you loop through the @repos array and set $x and $_repo on each iteration, those variables always take their values from the last iteration of that loop. This is why you always end up with the same generated content.

    The template could be changed to this:

    <% if @repo == "centos"
         x = "/opt/repos/yum/" + @repo
         _repo = @repo
       else
         x = "/opt/repos/" + @repo
         _repo = @repo
       end -%>
    Alias /<%= _repo %> <%= x %>
    DocumentRoot  <%= x %>
    IndexOptions NameWidth=* +SuppressDescription
    <Directory <%= x %>>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog logs/<%= _repo %>_repo1_error.log
    LogLevel warn
    
    CustomLog logs/<%= _repo %>_repo1_access.log combined
    

    Notice that I also changed your variables $x and $_repo because the dollar sign denotes global variables in Ruby, and global variables are probably not what you want there.

    It would be better still if you moved the conditional logic from your ERB template into your Puppet manifest.

    Finally, you really need to fix up your indentation because it is very hard to read as you have it.