Skip to content

Instantly share code, notes, and snippets.

@omersiar
Last active December 5, 2019 08:04
Show Gist options
  • Save omersiar/a4bff87c808caf4d55cc48653462e82c to your computer and use it in GitHub Desktop.
Save omersiar/a4bff87c808caf4d55cc48653462e82c to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'rest-client'
require 'json'
# Let there be more verbosity
debug_m = false
@ipam_user = vm_provisioning_config['ipam_user']
@ipam_password = vm_provisioning_config.decrypt('ipam_password')
@ipam_base_url = vm_provisioning_config['ipam_base_url']
# rescue JSON parser errors
def valid_json?(string)
!!JSON.parse(string)
rescue JSON::ParserError
false
end
# This method should be invoked by an another method ??
ip_address = []
# API call for retrieving objects for given IP address
ip_api_url = "#{@ipam_base_url}/ipv4address?ip_address=#{ip_address}"
# Craft API call
begin
response = RestClient::Request.execute(
method: 'GET',
user: @ipam_user,
password: @ipam_password,
url: ip_api_url,
headers: { accept: :json, content_type: 'application/json' },
verify_ssl: false
)
rescue StandardError => e
e.response
end
if valid_json?(response.body) == false
$evm.log(:info, 'response is not a valid JSON object') if debug_m == true
exit MIQ_ERROR
end
$evm.log(:info, "IPAM response: #{response.body}") if debug_m == true
objects = JSON.parse(response.body)
$evm.log(:info, JSON.pretty_generate(objects)) if debug_m == true
# It may contain more than one object so iterate over each IPAM object and DELETE
objects_api_url = "#{@ipam_base_url}/#{actual_object}"
objects['objects'].each do |object|
$evm.log(:info, JSON.pretty_generate(object)) if debug_m == true
actual_object = object['objects']
if debug_m == true
$evm.log(:info, "The actual object for using in URL is: #{actual_object}")
end
# Craft DELETE API call
begin
del_response = RestClient::Request.execute(
method: 'DELETE',
user: @ipam_user,
password: @ipam_password,
url: objects_api_url,
headers: { accept: :json, content_type: 'application/json' },
verify_ssl: false
)
rescue StandardError => e
e.response
end
$evm.log(:info, "IPAM response: #{response.body}") if debug_m == true
exit MIQ_ERROR if valid_json?(del_response.body) == false
end
exit MIQ_OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment