简体   繁体   English

将字符串数组从Facter放入Puppet

[英]Get array of strings from Facter into Puppet

In a module I'm working on, I need to check if specific users exist on a machine. 在我正在处理的模块中,我需要检查计算机上是否存在特定用户。 The idea was to create a custom fact that contains an array of all users. 这个想法是创建一个包含所有用户数组的自定义事实。 In the module, it should iterate through the array and check if a specific user is part of the array. 在模块中,它应该遍历数组,并检查特定用户是否是数组的一部分。

My Custom Fact: 我的自定义事实:

Facter.add("users") do
  setcode do
    IO.readlines("/etc/passwd").collect do |line|
      line.split(":").first
    end
  end
end

The output of the fact is a String like this: ["user1", "user2", "user3"] 事实的输出是这样的字符串:[“ user1”,“ user2”,“ user3”]

Because it is just a string and no array, I'm unable to iterate through it in my puppet module. 因为它只是一个字符串,没有数组,所以我无法在人偶模块中对其进行迭代。

I then tried 然后我尝试了

  shell_split($::users).each |String $user| {
    notify { "$user":}
  }

But now, each user contains a comma after the username. 但是现在,每个用户名后都包含一个逗号。

Do you have an idea for a working and better solution? 您是否有一个可行且更好的解决方案的想法?

The output of the fact is a String like this: ["user1", "user2", "user3"] 事实的输出是这样的字符串:[“ user1”,“ user2”,“ user3”]

No, it isn't. 不,不是。 The Ruby code you presented in the fact's setcode block evaluates to an array. 您在事实的setcode块中显示的Ruby代码将评估为一个数组。 That expression provides the value of the fact. 该表达式提供了事实的价值。 It is an array. 它是一个数组。

It is possible, however, that Puppet converts that array to a string after receiving it from Facter. 它是可能的,但是,从木偶Facter收到后该数组转换为字符串。 Puppet 3 did this by default, but had a boolean stringify_facts configuration setting that could prevent that behavior. 木偶3默认情况下会执行此操作,但是它具有布尔型stringify_facts配置设置,可以防止该行为。 Puppet 4 retained that setting but deprecated it and reversed its default value (to false ). 人偶4保留了该设置,但弃用了该设置,并将其默认值反转为false Puppet 5 removed the setting, and never stringifies fact values. 人偶5删除了该设置,并且从不对事实值进行字符串化。

Therefore, if you are using (obsolete) Puppet 3 then you can avoid fact stringification by setting 因此,如果您正在使用(过时的)Puppet 3,则可以通过设置

stringify_facts = false

in the [main] section of your puppet.conf files on the master and all agents. 在master和所有代理上的puppet.conf文件的[main]部分中。 You can do the same on Puppet 4, but there you can also just ensure that the stringify_facts setting is not explicitly set at all. 您可以在Puppet 4上执行相同的操作,但也可以只确保未明确设置stringify_facts设置。

Assuming, you have this as the output of Factor.add : 假设您将其作为Factor.add的输出:

output = '["user1", "user2", "user3"]'

You can convert it to an Array with the help of JSON : 您可以借助JSON将其转换为Array

require 'json'

JSON.parse output
 => ["user1", "user2", "user3"] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM