Skip to content

Commit

Permalink
Fix Sanity Test
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Jan 23, 2022
1 parent 4ba015c commit 3c255e6
Show file tree
Hide file tree
Showing 8 changed files with 367 additions and 114 deletions.
2 changes: 1 addition & 1 deletion nutanix/ncp/plugins/module_utils/base_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class BaseModule(AnsibleModule):
action=dict(type="str", required=True, aliases=["state"]),
auth=dict(type="dict", required=True),
data=dict(type="dict", required=False),
operations=dict(type="list", required=False),
operations=dict(type="list", elements="str", required=False),
wait=dict(type="bool", required=False, default=True),
wait_timeout=dict(type="int", required=False, default=300),
validate_certs=dict(type="bool", required=False, default=False),
Expand Down
24 changes: 12 additions & 12 deletions nutanix/ncp/plugins/module_utils/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ def check_response(self):
self.result["task_information"] = task

self.result["changed"] = True
status = self.response.get("state") or self.response.get("status").get("state")
status = self.response.get(
"state") or self.response.get("status").get("state")
if status and status.lower() != "succeeded" or self.action == "list":
self.result["changed"] = False
if status.lower() != "complete":
Expand Down Expand Up @@ -156,13 +157,10 @@ def send_request(module, method, req_url, req_data, username, password, timeout=
)
if not 300 > info["status"] > 199:
module.fail_json(
msg="Fail: %s"
% (
"Status: "
+ str(info["msg"])
+ ", Message: "
+ str(info.get("body"))
)
msg="Fail: " + "Status: " +
f'{str(info["msg"])}' + ", Message: " +
f'{str(info.get("body"))}'

)

body = resp.read() if resp else info.get("body")
Expand Down Expand Up @@ -203,7 +201,7 @@ def generate_url_from_operations(self, name, netloc=None, ops=None):
elif type(each) is dict:
key = list(each.keys())[0]
val = each[key]
path += "/{0}/{1}".format(key, val)
path += f"/{key}/{val}"
url += path
return self.validate_url(url, netloc, path)

Expand All @@ -222,7 +220,8 @@ def validate_url(url, netloc, path=""):

def get_action(self):
if self.action == "present":
self.action = "update" if self.data["metadata"].get("uuid") else "create"
self.action = "update" if self.data["metadata"].get(
"uuid") else "create"
elif self.action == "absent":
self.action = self.methods_of_actions[self.action]
elif self.action not in self.methods_of_actions.keys():
Expand All @@ -241,7 +240,7 @@ def get_spec(self):
)

file_path = join(ncp_dir, self.spec_file)
with open(file_path) as f:
with open(file_path, encoding='utf_8') as f:
# spec = json.loads(str(f.read()))
spec = yaml.safe_load(f.read())
return spec
Expand Down Expand Up @@ -326,7 +325,8 @@ def run_module(self, module):

if not self.url:
self.url = (
str(self.auth.get("ip_address")) + ":" + str(self.auth.get("port"))
str(self.auth.get("ip_address")) +
":" + str(self.auth.get("port"))
)

self.netloc = self.url
Expand Down
27 changes: 19 additions & 8 deletions nutanix/ncp/plugins/module_utils/prism/vms.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ def _get_api_spec(self, param_spec, **kwargs):
pass

def get_entity_by_name(self, name="", kind=""):
url = self.generate_url_from_operations(kind, netloc=self.url, ops=["list"])
data = {"filter": "name==%s" % name, "length": 1}
url = self.generate_url_from_operations(
kind, netloc=self.url, ops=["list"])
data = {"filter": f"name=={name}", "length": 1}
resp = self.send_request(
self.module,
self.methods_of_actions["list"],
Expand All @@ -41,24 +42,32 @@ def get_entity_by_name(self, name="", kind=""):
self.credentials["username"],
self.credentials["password"],
)

try:
return resp["entities"][0]["metadata"]

except IndexError:
self.result["message"] = 'Entity with name "%s" does not exist.' % name

self.result["message"] = f'Entity with name {name} does not exist.'
self.result["failed"] = True

self.module.exit_json(**self.result)


class VMSpec:
def get_default_spec(self):
raise NotImplementedError(
"Get Default Spec helper not implemented for {0}".format(self.entity_type)

f"Get Default Spec helper not implemented for {self.entity_type}"


)

def _get_api_spec(self, param_spec, **kwargs):
raise NotImplementedError(
"Get Api Spec helper not implemented for {0}".format(self.entity_type)

f"Get Api Spec helper not implemented for {self.entity_type}"

)

def remove_null_references(self, spec, parent_spec=None, spec_key=None):
Expand Down Expand Up @@ -207,9 +216,11 @@ def _get_api_spec(self, param_spec, **kwargs):
# nic_final['subnet_reference'][k.split('_')[-1]] = v

elif k == "subnet_uuid" and v:
nic_final["subnet_reference"] = {"kind": "subnet", "uuid": v}
nic_final["subnet_reference"] = {
"kind": "subnet", "uuid": v}
elif k == "subnet_name" and not nic_param.get("subnet_uuid"):
nic_final["subnet_reference"] = self.__get_subnet_ref(v, **kwargs)
nic_final["subnet_reference"] = self.__get_subnet_ref(
v, **kwargs)

elif k == "ip_endpoint_list" and bool(v):
nic_final[k] = [{"ip": v[0]}]
Expand Down Expand Up @@ -246,7 +257,7 @@ def _get_api_spec(self, param_spec, **kwargs):

gc_spec = self.get_default_spec()
script_file_path = param_spec["script_path"]
with open(script_file_path, "r") as f:
with open(script_file_path, "r", encoding='utf_8') as f:
content = f.read()
content = b64encode(content)
type = param_spec["type"]
Expand Down
57 changes: 32 additions & 25 deletions nutanix/ncp/plugins/modules/nutanix_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,11 @@

# Copyright: (c) 2021
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function

from ..module_utils.base_module import BaseModule
from ..module_utils.prism.images import Image

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type


DOCUMENTATION = r"""
DOCUMENTATION = r'''
---
module: nutanix_images
Expand All @@ -21,36 +17,45 @@
description: This module allows to perform the following tasks on /images
options:
action:
state:
description: This is the action used to indicate the type of request
aliases: ['action']
required: true
type: str
credentials:
auth:
description: Credentials needed for authenticating to the subnet
required: true
type: dict (Variable from file)
type: dict #(Variable from file)
data:
description: This acts as either the params or the body payload depending on the HTTP action
required: false
type: dict
operation:
operations:
description: This acts as the sub_url in the requested url
required: false
type: str
ip_address:
description: This acts as the ip_address of the subnet. It can be passed as a list in ansible using with_items
required: True
type: str (Variable from file)
port:
description: This acts as the port of the subnet. It can be passed as a list in ansible using with_items
required: True
type: str (Variable from file)
type: list
elements: str
wait_timeout: ###
description: This is the wait_timeout description
required: False
type: int
default: 300
wait: ###
description: This is the wait description
required: False
type: bool
default: true
validate_certs: ###
description: This is the validate_certs description
required: False
type: bool
default: False
author:
- Gevorg Khachatryan (@gevorg_khachatryan)
"""
'''

EXAMPLES = r"""
EXAMPLES = r'''
#CREATE action, request to /images
- hosts: [hosts_group]
Expand Down Expand Up @@ -115,9 +120,9 @@
data:
metadata:
uuid: string
"""
'''

RETURN = r"""
RETURN = r'''
CREATE:
description: CREATE /images Response for nutanix imagese
returned: (for CREATE /images operation)
Expand Down Expand Up @@ -148,7 +153,9 @@
- default Internal Error
- 404 Invalid UUID provided
- 202 Request Accepted
"""
'''
from ..module_utils.prism.images import Image
from ..module_utils.base_module import BaseModule


def run_module():
Expand All @@ -160,5 +167,5 @@ def main():
run_module()


if __name__ == "__main__":
if __name__ == '__main__':
main()
59 changes: 33 additions & 26 deletions nutanix/ncp/plugins/modules/nutanix_subnets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,11 @@

# Copyright: (c) 2021
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function

from ..module_utils.base_module import BaseModule
from ..module_utils.prism.subnets import Subnet

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type


DOCUMENTATION = r"""
DOCUMENTATION = r'''
---
module: nutanix_subnets
Expand All @@ -21,36 +17,45 @@
description: This module allows to perform the following tasks on /subnets
options:
action:
description: This is the HTTP action used to indicate the type of request
state:
description: This is the action used to indicate the type of request
aliases: ['action']
required: true
type: str
credentials:
auth:
description: Credentials needed for authenticating to the subnet
required: true
type: dict (Variable from file)
type: dict #(Variable from file)
data:
description: This acts as either the params or the body payload depending on the HTTP action
required: false
type: dict
operation:
operations:
description: This acts as the sub_url in the requested url
required: false
type: str
ip_address:
description: This acts as the ip_address of the subnet. It can be passed as a list in ansible using with_items
required: True
type: str (Variable from file)
port:
description: This acts as the port of the subnet. It can be passed as a list in ansible using with_items
required: True
type: str (Variable from file)
type: list
elements: str
wait_timeout: ###
description: This is the wait_timeout description
required: False
type: int
default: 300
wait: ###
description: This is the wait description
required: False
type: bool
default: true
validate_certs: ###
description: This is the validate_certs description
required: False
type: bool
default: False
author:
- Gevorg Khachatryan (@gevorg_khachatryan-97)
"""
'''

EXAMPLES = r"""
EXAMPLES = r'''
#CREATE action, request to /subnets
- hosts: [hosts_group]
Expand Down Expand Up @@ -99,9 +104,9 @@
metadata:
uuid: string
"""
'''

RETURN = r"""
RETURN = r'''
CREATE:
description: CREATE /subnets Response for nutanix subnets
returned: (for CREATE /subnets operation)
Expand Down Expand Up @@ -132,7 +137,9 @@
- default Internal Error
- 404 Invalid UUID provided
- 202 Request Accepted
"""
'''
from ..module_utils.prism.subnets import Subnet
from ..module_utils.base_module import BaseModule


def run_module():
Expand All @@ -144,5 +151,5 @@ def main():
run_module()


if __name__ == "__main__":
if __name__ == '__main__':
main()
Loading

0 comments on commit 3c255e6

Please sign in to comment.