管理用户的自定义文件

优质
小牛编辑
132浏览
2023-12-01

用户,与猫一样,常常觉得有必要标记他们的领地。 与猫不同,用户往往要定制自己的 shell 环境,如终端显示的颜色、别名等。 这通常是通过用户家目录下的一些以点开始的环境文件实现的,例如:.bash_profile

通过修改上一节的 user::virtual::ssh_user 类,你可以将环境文件添加到基于 Puppet 的用户管理中。 在这个类中,你可以有选择地为客户提供 Puppet 文件仓库中的任何以点开头的文件。

操作步骤

  1. user::virtual 类做如下修改:

    class user::virtual
    {
      define user_dotfile( $username )
      {
      file { "/home/${username}/.${name}":
        source => "puppet:///modules/user/${username}-${name}",
        owner  => $username,
        group  => $username,
      }
      }
    
      define ssh_user( $key, $dotfile = false )
      {
      user { $name:
        ensure   => present,
        managehome => true,
      }
    
      ssh_authorized_key { "${name}_key":
        key  => $key,
        type => "ssh-rsa",
        user => $name,
      }
    
      if $dotfile {
        user_dotfile { $dotfile:
          username => $name,
        }
      }
      }
    
      @ssh_user { "john":
      key => "AAAAB3NzaC1yc2EAAAABIwAAAIEA3ATqENg
      +GWACa2BzeqTdGnJhNoBer8x6pfWkzNzeM8Zx7/2Tf2pl7kHdbsi
      TXEUawqzXZQtZzt/j3Oya+PZjcRpWNRzprSmd2UxEEPTqDw9LqY5S2B8
      og/NyzWaIYPsKoatcgC7VgYHplcTbzEhGu8BsoEVBGYu3IRy5RkAcZik=",
      dotfile => [ "bashrc", "bash_profile" ],
      }
    }
    
  2. 使用如下内容创建 /etc/puppet/modules/user/files/john-bashrc 文件:

    export PATH=$PATH:/var/lib/gems/1.8/bin
  3. 使用如下内容创建 /etc/puppet/modules/user/files/john-bash_profile 文件:

    . ~/.bashrc
  4. 运行 Puppet。

工作原理

我们添加了一个名为 user_dotfiledefine。 对于用户要使用的每个 dotfile 都要调用这个 define 一次。 在本例中,john 用户有两个 dotfiles.bashrc.bash_profile。 其声明如下:

@ssh_user { "john":
  key => ...
  dotfile => [ "bashrc", "bash_profile" ],
}

你既可以指定一个 dotfile,也可以像本例那样指定一个数组形式的列表。

对于每个 dotfileuser_dotfile 将在 modules/user/files 目录下查找相应源的文件。 例如,对名为 bashrcdotfile,Puppet 将查找:

modules/user/files/john-bashrc

这将被拷贝为客户节点的如下文件:

/home/john/.bashrc

参见本书