To get IP addres of the specific host machine in rub - ruby

I want to find the IP address of other system. For example, I am executing my code from server wevrs1234 and I want the IP address of server apvrs1234 and store it in variable. Please help me to get this.
ip = IPSocket.getaddress(Socket.gethostname)
is the code I have so far.
AS per suggestion i have made this code but getting error. Please find my code
publish_vm = node['aem_dispatcher_cookbook']['publish'].to_s
nodes = search(:node, 'hostname:publish_vm')
node.default['aem_dispatcher_cookbook']['ip_address'] = 'nodes.first['ipaddress']'
template node['aem_dispatcher_cookbook']['owner']['home'] + '/conf.d/publish_farm.any' do
source 'publish_farm.any.erb'
owner node['aem_dispatcher_cookbook']['owner']['user']
group node['aem_dispatcher_cookbook']['owner']['group']
mode '0755'
variables(
publish_host: node['aem_dispatcher_cookbook']['publish'],
publish_port: node['aem_dispatcher_cookbook']['publish_port'],
ip_addr: node['aem_dispatcher_cookbook']['ip_address']
)
end
Error
[2020-05-20T06:09:52-05:00] DEBUG: Node wevrd64501.uhc.com loading cookbook aem_dispatcher_cookbook's attribute file /root/.chef/local-mode-cache/cache/cookbooks/aem_dispatcher_cookbook/attributes/default.rb
================================================================================
Recipe Compile Error in /root/.chef/local-mode-cache/cache/cookbooks/aem_dispatcher_cookbook/recipes/default.rb
================================================================================
SyntaxError
-----------
/root/.chef/local-mode-cache/cache/cookbooks/aem_dispatcher_cookbook/recipes/default.rb:333: syntax error, unexpected tIDENTIFIER, expecting keyword_end
...ess'] = 'nodes.first['ipaddress']'
... ^~~~~~~~~
System Info:

You tagged the question with [chef] and [chef-recipe], so I understand you are trying to get another machine's IP address inside recipe. If that another machine is also registered with Chef Server, the easiest would be search. You can search for any machine registered on the Chef Server by some attribute, in your case - hostname.
nodes = search(:node, 'hostname:<another_vm_hostname>')
p nodes.first['ipaddress']
Update:
You have an error in your 3rd line. Don't surround nodes.first['ipaddess'] with quotes.
node.default['aem_dispatcher_cookbook']['ip_address'] = nodes.first['ipaddress']

publish_vm = node['aem_dispatcher_cookbook']['publish'].to_s
ruby_block 'get_ip_from_publish' do
block do
Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)
command1 = "nslookup #{publish_vm} |grep '^Address' | awk '{print $2}'| tail -1"
command_out = shell_out(command1)
node.run_state['master_ip'] = command_out.stdout
end
action :run
end
This piece of code helped me to get ip address of desired host machine

Related

Ruby enumeration has unexpected second pass

This is making me crazy. I'm trying to loop through email messages using ".each do |one_of|…end", but inserting one innocuous statement breaks the enumeration.
Here is an almost-stand-alone snippet. The authentication info is set up immediately preceding, as is the "require net/imap"
imap = Net::IMAP.new(IMAP_server)
imap.authenticate('LOGIN', IMAP_login, IMAP_pass)
imap.select(IMAP_folder)
[1,2,3,5].each do |mnum|
#message_ids = imap.search(['SUBJECT', 'NETGEAR R7000 Log']).each do |mnum|
puts(mnum)
msg = imap.fetch(mnum, 'BODY[TEXT]')
msg[0].values[1]['BODY[TEXT]'].each_line do |full_entry|
line = String.new(full_entry)
recType = line[/^\[.*\] /]
# recType = recType.tr('[]','')
puts recType
end
puts
puts
end
It was working (and not) when I was looping through message ID numbers, but I replaced that statement with a literal array to eliminate a potential problem source.
Running it with the ".tr" statement commented out produces expected results, lines like:
1
[DHCP IP: (192.168.1.9)]
[DoS attack: FIN Scan]
[DHCP IP: (192.168.1.8)]
[Admin login]
[Admin login failure]
[Admin login]
[DHCP IP: (192.168.1.7)]
[DHCP IP: (192.168.1.5)]
[Time synchronized with NTP server]
[Internet connected]
2
[LAN access from remote]
[LAN access from remote]
[LAN access from remote]
[UPnP set event: Public_UPNP_C3]
[UPnP set event: Public_UPNP_C3]
[UPnP set event: Public_UPNP_C3]
…
Now un-comment the ".tr" line, to remove the brackets, and it goes all the way through the first iteration, but then:
1
DHCP IP: (192.168.1.9)
DoS attack: FIN Scan
DHCP IP: (192.168.1.8)
Admin login
Admin login failure
Admin login
DHCP IP: (192.168.1.7)
DHCP IP: (192.168.1.5)
Time synchronized with NTP server
Internet connected
Traceback (most recent call last):
4: from /Users/jan/bin/MassageNetgear.rb:39:in `<main>'
3: from /Users/jan/bin/MassageNetgear.rb:39:in `each'
2: from /Users/jan/bin/MassageNetgear.rb:43:in `block in <main>'
1: from /Users/jan/bin/MassageNetgear.rb:43:in `each_line'
/Users/jan/bin/MassageNetgear.rb:45:in `block (2 levels) in <main>': undefined method `tr' for nil:NilClass (NoMethodError)
So, somehow, putting this one statement in is causing the second iteration of mnum to fail. It doesn't even print "2" for the second iteration. Line 45 in the traceback is the newly inserted statement, but it doesn't even get that far! Adding another puts as the first statement in the inner loop does nothing.
I've done this before to concatenate a bunch of emails containing router log messages, but I then modified that code, and I somehow broke it! I've cut and re-typed the problem statement, thinking there may have been invisibles in there, but I'm using BBEdit, which shows such things.
Please, point out where I'm doing something stupid!
Thanks!
nil prints as an empty string, so it's possible there is actually a last line which isn't matching the regexp and which is printing as an empty string. In that case, tr would fail since nil actually doesn't have a tr method.
You could use a conditional assignment, which will not execute the right-hand side if recType is falsy.
recType = line[/^\[.*\] /]
recType &&= recType.tr('[]','')
puts recType
Or (if you want to actually treat it as an empty string), you can simply unconditionally call to_s on it.
recType = line[/^\[.*\] /].to_s
recType = recType.tr('[]','')
puts recType

Chef - Ruby - ArgumentsError expected 0

I'm trying to write a cookbook in Chef (very new) and I get the following error I cannot wrap my head around.
template node '/etc/selinux/config' do
source "config.erb"
mode "0644"
variables(
:selinux_state => node['selinux']['selinux-state'],
:selinux_type => node['selinux']['selinux-type']
)
owner duser
group dgroup
action :create
ignore_failure true
end
FATAL: ArgumentError: wrong number of arguments (given 1, expected 0)
I checked the documentation and as far as I can tell I am following the correct syntax.
Could anyone please enlighten me where the error is?
You have an extra node in the resource declaration. Change:
template node '/etc/selinux/config' do
to
template '/etc/selinux/config' do

Get current restart policy state (nodeRestartState) of AppServer using Jython

I want to get the current restart policy of an AppServer (RUNNING, STOPPED or PREVIOUS) using Jython.
servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
for server in servers:
print server
print AdminConfig.showAttribute(server, "monitoringPolicy")
break
This gave me an exception that the attribute is invalid:
An exception occurred when executing the file "test.py". Information
about the exception: com.ibm.ws.scripting.ScriptingException:
WASX7080E: Invalid attributes for type "Server" -- "monitoringPolicy".
But I could get the attribute using print AdminConfig.showall(server):
...
[monitoringPolicy [[autoRestart true]
[maximumStartupAttempts 3]
[nodeRestartState STOPPED]
[pingInterval 60]
[pingTimeout 300]]]
...
For me it looks like monitoringPolicy is the key of an array, so that it should be possible to get the restart state with
policy = AdminConfig.showAttribute(server, "monitoringPolicy")
restartState = policy["restartState"] # Should be "STOPPED"
Where is the problem?
Edit
After taking a deeper look in the list output, I saw that I missed a top level property processDefinitions, which is the parent of monitoringPolicy.
pd = AdminConfig.showAttribute(server, "processDefinitions")
print pd
This prints:
[(cells/CnxCell/nodes/CnxNode01/servers/UtilCluster_server1|server.xml#JavaProcessDef_1578492353152)]
But I'm not able to get any of the child propertys from this object:
# TypeError: sequence subscript must be integer or slice
print pd["monitoringPolicy"]
# AttributeError: 'string' object has no attribute 'monitoringPolicy'
print pd.monitoringPolicy
MonitoringPolicy has his own type. This prints the server and the state, so 'RUNNING', 'STOPPED'
servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
for server in servers:
print(server)
mpol = AdminConfig.list("MonitoringPolicy", server)
print(AdminConfig.showAttribute(mpol, 'nodeRestartState'))

How to use local variable of whitespace array in chef template resource

I am trying to use whitespace arrays in chef template, like below and when I run the chef-client to execute the recipe getting an error saying: option variables must be a kind of [Hash]! below is recipe file
abc = node['abc']
def1 = node['def']
abc_sit = abc['sit']
def_sit = def1['sit']
%w{abc_sit def_sit}.each do | client |
template "/etc/#{client}.sh" do
source 'tunnel.erb'
owner 'root'
group 'root'
variables ("#{client}") --> At this line I am getting error
end
end
The error I am getting when I run the chef-client:
option variables must be a kind of [Hash]! You passed "abc_sit"
As it says, you have to pass in a Hash. Perhaps something like variables myclient: client and then <%= #myclient %> in the template.

dynamic usage of attribute in recipe

I am trying to increment the value and use in another resource dynamically in recipe but still failing to do that.
Chef::Log.info("I am in #{cookbook_name}::#{recipe_name} and current disk count #{node[:oracle][:asm][:test]}")
bash "beforeTest" do
code lazy{ echo #{node[:oracle][:asm][:test]} }
end
ruby_block "test current disk count" do
block do
node.set[:oracle][:asm][:test] = "#{node[:oracle][:asm][:test]}".to_i+1
end
end
bash "test" do
code lazy{ echo #{node[:oracle][:asm][:test]} }
end
However I'm still getting the error bellow:
NoMethodError ------------- undefined method echo' for Chef::Resource::Bash
Cookbook Trace: ---------------
/var/chef/cache/cookbooks/Oracle11G/recipes/testSplit.rb:3:in block (2 levels) in from_file'
Resource Declaration: ---------------------
# In /var/chef/cache/cookbooks/Oracle11G/recipes/testSplit.rb
1: bash "beforeTest" do
2: code lazy{
3: echo "#{node[:oracle][:asm][:test]}"
4: }
5: end
Please can you help how lazy should be used in bash? If not lazy is there any other option?
bash "beforeTest" do
code lazy { "echo #{node[:oracle][:asm][:test]}" }
end
You should quote the command for the interpolation to work; if not, ruby would search for an echo command, which is unknown in ruby context (thus the error you get in log).
Warning: lazy has to be for the whole resource attribute; something like this WON'T work:
bash "beforeTest" do
code "echo node asm test is: #{lazy { node[:oracle][:asm][:test]} }"
end
The lazy evaluation takes a block of ruby code, as decribed here
You may have a better result with the log resource like this:
log "print before" do
message lazy { "node asm test is #{node[:oracle][:asm][:test]}" }
end
I've been drilling my head solving this problem until I came up with lambda expressions. But yet just using lambda didn't help me at all. So I thought of using both lambda and lazy evaluation. Though lambda is already lazy loading, when compiling chef recipe's, the resource where you call the lambda expression is still being evaluated. So to prevent it to being evaluated (somehow), I've put it inside a lazy evaluation string.
The lambda expression
app_version = lambda{`cat version`}
then the resource block
file 'tmp/validate.version' do
user 'user'
group 'user_group'
content lazy { app_version.call }
mode '0755'
end
Hope this can help others too :) or if you have some better solution please do let me know :)

Resources