I have a json file ou.json:
{
"ProdInf": {
"regex": "^(?i)nyinf-p(\\d )$",
"ou": "OU=Inf,OU=Prod,OU=Servers,DC=example,DC=local"
},
"ProdHyperV": {
"regex": "^(?i)nyhyp-p(\\d )$",
"ou": "OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local"
},
"ProdRDS": {
"regex": "^(?i)nyrds-p(\\d )$",
"ou": "OU=RDS,OU=Prod,OU=Servers,DC=example,DC=local"
}
"Default": {
"regex": "zzz",
"ou": "OU=Servers,DC=example,DC=local"
}
}
I have:
require 'json'
computername = "nyhyp-p24"
json_file = File.read("./ou.json")
json_hash = JSON.parse(json_file)
then be able to retrieve all the regex in the hash, and evaluate computername against each regex, and if it is a match return the appropriate ou.first
in the example above, ou should equal "OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local"
if there is no match it should return default.ou
CodePudding user response:
I add extra slashes to escape them in the JSON
Like this: "^(?i)nyrds-p(\\d )$"
--> "^(?i)nyrds-p(\\\\d )$"
require "json"
json =
<<~JSON
{
"ProdInf": {
"regex": "^(?i)nyinf-p(\\\\d )$",
"ou": "OU=Inf,OU=Prod,OU=Servers,DC=example,DC=local"
},
"ProdHyperV": {
"regex": "^(?i)nyhyp-p(\\\\d )$",
"ou": "OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local"
},
"ProdRDS": {
"regex": "^(?i)nyrds-p(\\\\d )$",
"ou": "OU=RDS,OU=Prod,OU=Servers,DC=example,DC=local"
},
"Default": {
"regex": "zzz",
"ou": "OU=Servers,DC=example,DC=local"
}
}
JSON
configs = JSON.parse(json, symbolize_names: true)
Then you can define some method like this
def find_ou(computer_name, configs)
configs
.find { |_, config| computer_name.match?(%r{#{config[:regex]}}) }
&.last
&.dig(:ou) || configs[:Default][:ou]
end
And then
find_ou("nyhyp-p24", configs)
# => "OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local"
find_ou("nyinf-p26", configs)
# => "OU=Inf,OU=Prod,OU=Servers,DC=example,DC=local"
find_ou("something else", configs)
# => "OU=Servers,DC=example,DC=local"