How to split string from attributes and assign it to new attribute

#1

Env : Windows
Automatic attribute : domain
Value : somedomain.com

want to use doamin name without .com to be used in template

"<% = node.[:domainname] %> \Administrator"
expected output should be somedomain\Administrator

0 Likes

#2

If you want to assign this value to a new attribute then add something like this to your attributes/default.rb

domain_array = node['domainname'].split('.') # Split string at dot character and return array.
default['domain_user'] = "#{domain_array.take(domain_array.length - 1)}\Administrator"

Then you can directly use it like <%= node['domain_user'] %> in your template.

0 Likes

#3

Thanks joreg for your help.

The following worked.

domain_array = node[‘domainname’].split(’.’)[0] # Split string at dot character and return array.
default[‘domain_user’] = “#{domain_array}\Administrator”

0 Likes

#4

Hi Again,

I am trying to assign attributes based ohai automatic attributes.

ex :
if (node[‘domain’].include? ‘.’)
node.default[:sql][‘domain_user’] = node[‘machinename’]
else
domain_array = node[‘domain’].split(’.’)[0] # Split string at dot character and return array.
node.default[:sql][‘domain_user’] = "#{domain_array}"
end

Explanation :
machinename = WORKGROUP
domain = example

Error : FATAL: NoMethodError: undefined method `include?’ for nil:NilClass

0 Likes

#5

The error seems strange and judging from your code it seems that you have that stuff in a recipe. Try to put something like this into attributes/default.rb (or any other attributes file):

if node['domain'].include?('.')
  default['sql']['domain_user'] = node['machinename']
else
  domain_array = node['domain'].split('.')[0] # Split string at dot character and return array.
  default['sql']['domain_user'] = domain_array
end
0 Likes

#6

Finally got it …

if %w{.}.include?(node[‘domain’])
default[:sql][‘domain_user’] = node[‘machinename’]
else
domain_array = node[‘domain’].split(’.’)[0] # Split string at dot character and return array.
default[:sql][‘domain_user’] = "#{domain_array}"
end

I have put the details in attributes/default.rb

0 Likes

#7

Ok, just to be sure you are aware of this:

%w{.} creates and Array with a single element and that is the String ‘.’. So the if condition of your code checks if node[‘domain’] is contained in the Array [’.’]. This most probably will never be the case!

For testing you can use irb which is an interactive Ruby shell. Just call “chef exec irb” from your Laptop and you can test single lines like %w{.}.include?("my.domain.com") or "my.domain.com".include?('.')

0 Likes