Class: RubyNsxCli::NSXObject

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_nsx_cli/nsx_objects/nsxobject.rb

Direct Known Subclasses

NSXEdge, NSXVirtualWire

Constant Summary collapse

XML_HEADER =
{'Content-Type': 'application/xml'}

Instance Method Summary collapse

Constructor Details

#initialize(**args) ⇒ NSXObject

Returns a new instance of NSXObject.



12
13
14
15
16
17
18
19
20
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 12

def initialize(**args)
  @logger = Logger.new(STDOUT)
  @logger.level = Logger::DEBUG

  @nsx_manager_url = args[:nsx_manager_url] || ENV['NSX_MANAGER_URL'] || (raise 'NSX Manager URL not specified!')
  @nsx_username = args[:nsx_username] || ENV['NSX_USERNAME'] || (raise 'NSX Username not specified!')
  @nsx_password = args[:nsx_password] || ENV['NSX_PASSWORD'] || (raise 'NSX Password not specified!')
  @ssl_check = args[:verify_ssl] ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
end

Instance Method Details

#create_new_request(api_endpoint, headers) ⇒ RestClient::Request

Helper method that creates the initial RestClient::Request object.

Parameters:

  • api_endpoint

    the NSX endpoint to send the request

  • headers

    the headers to include in the request

Returns:

  • (RestClient::Request)

    the initial request object to be used to call REST methods.



127
128
129
130
131
132
133
134
135
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 127

def create_new_request(api_endpoint, headers)
  return RestClient::Resource.new(
      "https://#{@nsx_manager_url}/#{api_endpoint}",
      :verify_ssl => @ssl_check,
      :user => @nsx_username,
      :password => @nsx_password,
      :headers => headers
  )
end

#delete(api_endpoint:) ⇒ RestClient::Response

Deletes an NSX object using the NSX API.

Parameters:

  • api_endpoint (String)

    NSX endpoint to send the request

Returns:

  • (RestClient::Response)

    Response from the NSX API.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 26

def delete(api_endpoint:)

  @logger.info("Deleting NSX object: #{self.class}...")
  @logger.debug("Sending request to: #{@nsx_manager_url}...")
  @logger.debug("API endpoint is: #{api_endpoint}")

  begin
    resp = create_new_request(api_endpoint, nil).delete

    if resp.code >= 200 && resp.code < 300
      @logger.info("Successfully deleted NSX object: #{self.class}")
      return resp
    else
      raise "Unexpected return code during NSX object creation: #{self.class} returned #{resp.code}"
    end

  rescue RestClient::ExceptionWithResponse => err
    puts "Failed to create NSX object: #{self.class}"
    puts "Response code: #{err.http_code}"
    puts "Response: #{err.message}"
    return resp
  end

end

#get(api_endpoint) ⇒ RestClient::Response

Sends a get request to the NSX API.

Parameters:

  • api_endpoint (String)

    NSX endpoint to send the request

Returns:

  • (RestClient::Response)

    Response from the NSX API.



117
118
119
120
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 117

def get(api_endpoint)
  resp = create_new_request(api_endpoint, nil).get
  return resp
end

#get_attr_text_from_xml(xml, attr) ⇒ Object



173
174
175
176
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 173

def get_attr_text_from_xml(xml, attr)
  doc = Nokogiri::XML(xml)
  return doc.at(attr).text
end

#inject_xml(xml, grandparent, parent, node) ⇒ String

Inserts an XML block into the provided XML at the parent node If the parent node does not exist, then the parent node will be created with the node injected into the grandparent node Returns the updated xml with the node injected

only required if the parent node is not included in the provided xml string

Parameters:

  • xml (String)

    the NSX endpoint to send the request

  • grandparent (String)

    the grandparent attribute of the node to insert;

  • parent (String)

    the parent attribute of the node to insert

  • node (String)

    the payload to send to ‘:api_endpoint`

Returns:

  • (String)

    the original XML string including the inserted node.



148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 148

def inject_xml(xml, grandparent, parent, node)
  doc = Nokogiri::XML(xml)
  parent_xml = doc.at_css(parent)
  if parent_xml.nil?
    grandparent_xml = doc.at_css(grandparent)
    raise "No valid parent to insert XML block into with nodes provided: #{parent_xml}, #{grandparent_xml}" if grandparent_xml.nil?
    parent_xml = Nokogiri::XML::Node.new(parent, doc)
    grandparent_xml << parent_xml
  end
  parent_xml << node
  return doc
end

#post(api_endpoint:, payload:) ⇒ RestClient::Response

Sends a post request to the NSX API. Usually to update an object.

Parameters:

  • api_endpoint (String)

    the NSX endpoint to send the request

  • payload (String)

    the payload to send to the ‘api_endpoint`

Returns:

  • (RestClient::Response)

    the response from the NSX API.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 56

def post(api_endpoint:, payload:)
  @logger.info("Updating NSX object: #{self.class}...")
  @logger.debug("Payload is: \n#{payload}")
  @logger.debug("API endpoint is: #{api_endpoint}")
  @logger.debug("Sending request to: #{@nsx_manager_url}...")

  begin

    resp = create_new_request(api_endpoint, XML_HEADER).post(payload)

    if resp.code >= 200 && resp.code < 300
      @logger.info("Successfully updated NSX object: #{self.class}")
      return resp
    else
      raise "Unexpected return code during NSX object update: #{self.class} returned #{resp.code}"
    end

  rescue RestClient::ExceptionWithResponse => err
    @logger.info("Failed to update NSX object: #{self.class}")
    @logger.info("Response code: #{err.http_code}")
    @logger.info("Response: #{err.message}")
    return resp
  end

end

#put(api_endpoint:, payload:) ⇒ RestClient::Response

Sends a post request to the NSX API. Usually to update an object.

Parameters:

  • api_endpoint (String)

    the NSX endpoint to send the request

  • payload (String)

    the payload to send to the ‘api_endpoint`

Returns:

  • (RestClient::Response)

    the response from the NSX API.



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 87

def put(api_endpoint:, payload:)
  @logger.info("Updating NSX object (HTTP put): #{self.class}")
  @logger.debug("Payload is: \n#{payload}")
  @logger.debug("API endpoint is: #{api_endpoint}")
  @logger.debug("Sending request to: #{@nsx_manager_url}...")


  begin
    resp = create_new_request(api_endpoint, XML_HEADER).put(payload)

    if resp.code >= 200 && resp.code < 300
      @logger.info("Successfully put NSX object: #{self.class}")
      return resp
    else
      raise "Unexpected return code during NSX object put: #{self.class} returned #{resp.code}"
    end

  rescue RestClient::ExceptionWithResponse => err
    @logger.error("Failed to put NSX object: #{self.class}")
    @logger.error("Response code: #{err.http_code}")
    @logger.error("Response: #{err.message}")
    return resp
  end

end

#render_template(template, object) ⇒ Object

Renders the specified erb file using the provided object

Parameters:

  • template (String)

    the relative path to the template

  • object (Object)

    the OpenStruct object that contains the key + values for rendering the template

Returns:

  • (Object)

    the rendered template



183
184
185
186
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 183

def render_template(template, object)
  renderer = ERB.new(File.read(File.dirname(__FILE__) + template))
  return renderer.result(object.instance_eval {binding})
end

#strip_xml_root_pi(xml) ⇒ String

Removes the <?xml version=“1.0” encoding=“UTF-8”?> processing instruction from the start of an XML string The new line character left in place is also removed to prevent issues when sending a payload to the NSX API which includes this string

Parameters:

  • xml (String)

    an XML string that includes the processing instruction ‘<?xml version=“1.0” encoding=“UTF-8”?>’

Returns:

  • (String)

    the XML string without the processing instruction



167
168
169
170
171
# File 'lib/ruby_nsx_cli/nsx_objects/nsxobject.rb', line 167

def strip_xml_root_pi(xml)
  frag = Nokogiri::XML::DocumentFragment.parse(xml)
  frag.xpath('processing-instruction()').remove
  return frag.to_s.sub("\n", '') # remove new line generated from removing root pi
end