傀儡变量并不总是有效

ujj*_*ain 5 puppet

我想通过对机器进行分组,例如 RH5 和 RH6 机器而不是为所有 RH5 和 RH6 服务器添加多行包含,在 nodes.pp 中应用“DRY”(不要重复自己)原则。

tst-01 上的 Puppet 在使用时可以正常工作:

node "tst-01" inherits basenode {
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用此配置将服务器组织成组时,它会中断:

node "tst-01" inherits redhat6server {
Run Code Online (Sandbox Code Playgroud)

“继承 redhat6server”的错误是:

err: Could not retrieve catalog; skipping run
[root@tst-01 ~]# puppet agent --test
err: Could not retrieve catalog from remote server: Error 400 on SERVER: Failed to parse template ldap/access.conf: Could not find value for 'netgroup' at 124:/etc/puppet/modules/ldap/templates/access.conf at /etc/puppet/modules/ldap/manifests/init.pp:82 on node tst-01.tst.it.test.com
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run
Run Code Online (Sandbox Code Playgroud)

这是 access.conf 文件,如果将继承设置为“继承 basenode”,则可以正常工作。

[root@puppet]# grep -v "#" /etc/puppet/modules/ldap/templates/access.conf 
+ : root : LOCAL
+ : @<%= netgroup %> : ALL
- : ALL : ALL
[root@puppet]# 
Run Code Online (Sandbox Code Playgroud)

这是/etc/puppet/manifests/nodes.pp中的配置。

# Basenode configuration
node "basenode" {
        include resolv_conf
        include sshd
        include ntpd
        include motd
}

# Groups
node "redhat6server" inherits basenode {
        include ldap_auth
}

# Testservers
node "tst-01" inherits redhat6server {
        $netgroup = tst-01
}
Run Code Online (Sandbox Code Playgroud)

daw*_*wud 5

它可能会失败,因为$netgroup评估变量之前发生了继承,因此目录编译失败。但是,使用这种方法将代码与数据分离具有局限性,应避免使用

我重构了我的 puppet 代码,以使用分层数据进行数据绑定,并实现对相似节点进行分组的相同效果。一个简化的示例,假设您只需要对 RHEL 服务器进行分组,则为:

  • 将使用以下定义检索分层数据:

    hiera.yaml
    ---
    :backends: 
      - yaml
    :hierarchy:
      - %{::operatingsystem}
      - %{::hostname}
      - common
    :yaml:
      :datadir: /etc/puppet/hieradata/
    
    Run Code Online (Sandbox Code Playgroud)

    这两个operatingsystemhostnamefacts。Hiera 将尝试按以下顺序为主机名是的 Red Hat 系统解析数据some-rhel-hostname

    • RedHat.yaml
    • some-rhel-hostname.yaml
    • 常见的.yaml

  • 这需要以下目录结构和文件:

    /etc/puppet/hieradata/
    ??? common.yaml
    ??? RedHat.yaml
    ??? some-rhel-hostname.yaml
    ??? tst-01.yaml
    
    Run Code Online (Sandbox Code Playgroud)
  • 示例 yaml 文件的内容:

    common.yaml
    ---
    classes:
      - resolv_conf
      - sshd
      - ntpd
      - motp
    
    RedHat.yaml
    ---
    classes:
      - ladp_auth
    
    some-rhel6-hostname.yaml
    ---
    classes:
      - this_host_only
    ldap_auth::netgroup: foo-bar
    
    tst-01.yaml
    ---
    ldap_auth::netgroup: tst-01
    
    nodes.pp
    default {
        hiera_include(classes)
    }
    
    Run Code Online (Sandbox Code Playgroud)

    注意使用的hiera_include 功能,将返回数组的所有值对每个节点(从那些common.yaml和那些从层级分辨率,即正在添加,some-rhel-hostname将包括所有类别的common.yaml加上ldap_authRedHat.yamlthis_host_only从自己的YAML文件)。

    如何在模块中使用数据绑定的方式因您使用的版本而异puppet。检查这里的指针。