I am creating a recipe that has two resources. The initial VPN IP address is a empty valued string. Upon execution of the first resource, a IP address within the range 10.12.xx.xx is set. Then a second resource is executed with a guard block that checks for the VPN IP.
#
# Cookbook:: test_cookbook
# Recipe:: check-vpn-ip
#
# Copyright:: 2019, The Authors, All Rights Reserved.
#Getting the IP address using the ruby's Socket class.
ip_list = Socket.ip_address_list
vpn_ip_list = ip_list.select{ |ip| ip.ip_address.match(/^10.12/) }
!vpn_ip_list.empty? ? ip_addr = vpn_ip_list.first.ip_address : ip_addr = ""
execute 'manually_start_open_vpn' do
command "sudo openvpn #{node['openvpn-conf-path']}/#{host}.conf &"
action :nothing
only_if {ip_addr.length.eql?(0)}
end
new_ip_list = Socket.ip_address_list
new_vpn_ip_list = new_ip_list.select{ |ip|
ip.ip_address.match(/^10.12/) }
!new_vpn_ip_list.empty? ? newvpn_ip_addr =
new_vpn_ip_list.first.ip_address : newvpn_ip_addr = ""
ruby_block 'chat-bot' do
block do
machine_data = {text: "OpenVPN IP not assigned to #{host}
software_version: 18.4.4 \n This is a test message please
ignore @all"}.to_json
header = {'Content-Type': 'text/json'}
http = Net::HTTP.new(google_chat_uri.host,
google_chat_uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(google_chat_uri.request_uri, header)
request.body = machine_data
response = http.request(request)
end
end
only_if {newvpn_ip_addr.length.eql?(0)}
action :nothing
end
Since there is no vpn ip address of the range 10.12.xx.xx during compile phase, the value of ip_addr.length.eql?(0)
is true and the guard block condition in first resource is satisfied and it's executed.
As the vpn ip has already been assigned, the newvpn_ip_addr.length.eql?(0)
should be false and the 2nd ruby block should not be executed. But this returns a false value as the code newvpn_ip_addr
is executed during compile time itself.
Is there any way to make sure that the value for newvpn_ip_addr
in the below code is assigned and checked during the execution phase post the execution of first resource?
new_ip_list = Socket.ip_address_list
new_vpn_ip_list = new_ip_list.select{ |ip|
ip.ip_address.match(/^10.12/) }
!new_vpn_ip_list.empty? ? newvpn_ip_addr =
new_vpn_ip_list.first.ip_address : newvpn_ip_addr = ""
So that the guard block in 2nd resource is not executed if the expected IP address is not assigned.
only_if {newvpn_ip_addr.length.eql?(0)}