基于条件的Elide Puppet参数

时间:2016-11-11 15:48:05

标签: puppet puppetlabs-apache

我在Puppet define中声明了以下资源。有些参数以auth_*开头,用于控制身份验证。我希望能够根据布尔变量的值(即$use_authentication)传递该参数块,或者不传递它们。

似乎if语句在这里不起作用,我认为“选择器”也不会这样做。 Felix Frank在非常密切相关的问题“conditional within define in puppet”中有一个非常有用的答案,但我不认为这个策略会起作用,因为需要省略的参数是嵌套两层深的。

apache::vhost { "$name-non-ssl":
    servername => $vhost_name,
    docroot => $document_root,
    port => 80,

    access_log_file => 'access.log',
    access_log_format => 'vhost_common',
    error_log_file => 'error.log',

    directories => [
         {path => $document_root,
          auth_type => 'Basic',
          auth_name => "$name",
          auth_user_file => '/somefile.pwd',
          auth_require => 'valid-user',
          rewrites => [
              {
                  comment => "rule1",
                  rewrite_base => "/",
                  rewrite_rule => ['^index\.html$ - [L]']
              },
              {
                  comment => "rule2",
                  rewrite_cond => ['%{REQUEST_FILENAME} !-f', '%{REQUEST_FILENAME} !-d'],
                  rewrite_rule => ['. /index.html [L]']
              }
          ]}
    ],
}

以下是语法错误:Syntax error at 'if'; expected '}'

apache::vhost { "$name-non-ssl":
    ... same as previous ...
    directories => [
         {path => $document_root,

          if $use_authentication {
              auth_type => 'Basic',
              auth_name => "$name",
              auth_user_file => '/somefile.pwd',
              auth_require => 'valid-user',
          }

          rewrites => [
              ...same as before...
          ]}
    ],
}

1 个答案:

答案 0 :(得分:2)

这很难处理,因为你想动态地填充散列中的一些键/值对,散列是作为参数值的数组的元素。

选项1:在资源声明

之外构建哈希
:id

当然,它与变量有点疯狂。

选项2:创建自定义功能

编写一个函数,该函数采用上面的$auth_settings = { auth_type => 'Basic', auth_name => "$name", auth_user_file => '/somefile.pwd', auth_require => 'valid-user', } $base_dir1 = {path => $document_root, rewrites => [ { comment => "rule1", rewrite_base => "/", rewrite_rule => ['^index\.html$ - [L]'] }, { comment => "rule2", rewrite_cond => ['%{REQUEST_FILENAME} !-f', '%{REQUEST_FILENAME} !-d'], rewrite_rule => ['. /index.html [L]'] } ] } if $use_authentication { $real_dir1 = merge($base_dir1, $auth_settings) } else { $real_dir1 = $base_dir1 } apache::vhost { "$name-non-ssl": servername => $vhost_name, docroot => $document_root, port => 80, access_log_file => 'access.log', access_log_format => 'vhost_common', error_log_file => 'error.log', directories => [ $real_dir1 ], } $base_dir1的布尔值,并在适当的时候返回合并的哈希值。

$use_authentication

选项3:内联

您可以在资源声明中无差异地执行合并。使用选择器决定要合并的内容。可读性就在这个窗口之外。

apache::vhost { "$name-non-ssl":
    servername => $vhost_name,
    docroot => $document_root,
    port => 80,

    access_log_file => 'access.log',
    access_log_format => 'vhost_common',
    error_log_file => 'error.log',

    directories => [ add_auth($use_authentication, { ... }) ],
}

我没有费心去测试这个怪物。甚至不确定括号是否排列。

你可能会在(1)和(3)之间达成妥协,但请倾向于前者。