puppet 自定义fact变量

一、puppetmaster配置:

  1. 增加环境变量,仅用于测试编写的变量是否生效。

[root@lw-01 ~]# vi /etc/profile 增加以下内容:
#puppet facter
export FACTERLIB=/etc/puppet/modules/facts/lib/facter/        #自定义变量文件存放路径
[root@lw-01 ~]# source /etc/profile

  2. 自定义变量文件路径在: /etc/puppet/modules/$NAME/lib/facter  #$NAME随便定义,可以被其它的模块使用。

[root@lw-01 modules]# pwd
/etc/puppet/modules
[root@lw-01 modules]# tree facts/
facts/
└── lib
    └── facter                    #此目录下为每个rb文件定义一个facter变量
        ├── lannet.rb
        ├── load_avg.rb
        └── log_num.rb
2 directories, 6 files
[root@lw-01 modules]# cd facts/lib/facter/
[root@lw-01 facter]# cat log_num.rb         
Facter.add(:log_num) do                     #log_num 为自定义变量名
setcode do
%x{/usr/bin/who |wc -l}.chomp
end
end

  3. 测试变量

[root@lw-01 facter]# facter log_num
3

或者:
[root@lw-01 facter]# facter | grep log_num
log_num => 3

  4. 定义一个测试模块

[root@lw-01 modules]# tree test/
test/
├── files
├── manifests
│   └── init.pp
└── templates
    └── test.rb
3 directories, 2 files
[root@lw-01 test]# cat manifests/init.pp 
class test {
        test::pwd
}

class test::pwd{

        $log_num= "$log_num"            #调用变量
        
    file{"/root/test/test.txt":         #puppet agent端会生成test.txt
        ensure => present,
        content => template('test/test.rb'),
        mode => '644',
        owner => 'root',
        group => 'root',
        }
}
[root@lw-01 test]# cat templates/test.rb 
log_num: <%= scope.lookupvar('test::pwd::log_num') %>


二、puppet agent端测试

[root@lw-02 ~]# puppet agent --test
Info: Retrieving pluginfacts
Info: Retrieving plugin
Info: Loading facts
Info: Caching catalog for 192.168.2.11
Info: Applying configuration version '1429004437'
Notice: /Stage[main]/Test::Pwd/File[/root/test/test.txt]/ensure: created
Notice: /Stage[main]/Test::Exec/Exec[test]/returns: executed successfully
Notice: Finished catalog run in 1.77 seconds
[root@lw-02 ~]# cd /root/test/
[root@lw-02 test]# cat test.txt 
log_num: 3                    #测试成功,log_num成为变量
[root@lw-02 ~]# facter -p    #可以看到所有服务器端定义的fact变量


你可能感兴趣的:(自定义,puppet,fact变量)