Skip to content

Commit

Permalink
Merge pull request #16 from osanchez42/collection
Browse files Browse the repository at this point in the history
Updated based on results of ansible-test.
  • Loading branch information
cscaglioned42 committed Apr 20, 2020
2 parents 2afdede + e864628 commit ca81a92
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 71 deletions.
4 changes: 2 additions & 2 deletions LICENSE
Expand Up @@ -4,10 +4,10 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.
2 changes: 1 addition & 1 deletion contrib/inventory/conf.sample.ini
Expand Up @@ -10,4 +10,4 @@ D42_SKIP_SSL_CHECK = True
GROUP_BY_QUERY = select name, service_level from view_device_v1
GROUP_BY_FIELD = service_level
GROUP_BY_REFERENCE_FIELD = name
SPLIT_GROUP_BY_COMMA = False
SPLIT_GROUP_BY_COMMA = False
12 changes: 6 additions & 6 deletions contrib/inventory/d42_ansible_dynamic_inventory.py
@@ -1,16 +1,15 @@
#!/usr/bin/env python

from __future__ import (absolute_import, division, print_function)
import argparse
import sys
from lib import *

from contrib.inventory.lib import get_conf
from contrib.inventory.lib import get_conf, Ansible, Device42

try:
import json
except ImportError:
import simplejson as json

__metaclass__ = type


class Inventory(object):

def __init__(self):
Expand Down Expand Up @@ -39,4 +38,5 @@ def inventory(self):
def empty_inventory(self):
return {'_meta': {'hostvars': {}}}


Inventory()
7 changes: 3 additions & 4 deletions contrib/inventory/d42_ansible_inventory_hostfile.py
@@ -1,9 +1,8 @@
from __future__ import (absolute_import, division, print_function)
import sys
import json
import requests
from lib import *
from contrib.inventory.lib import get_conf, Ansible, Device42

from contrib.inventory.lib import get_conf
__metaclass__ = type

if __name__ == '__main__':
conf = get_conf()
Expand Down
9 changes: 6 additions & 3 deletions contrib/inventory/lib.py
@@ -1,18 +1,19 @@
from __future__ import (absolute_import, division, print_function)
from io import StringIO
import requests
import codecs
import base64
import configparser
import csv
import sys
import os


try:
import json
except ImportError:
import simplejson as json

__metaclass__ = type


def get_conf():

Expand Down Expand Up @@ -77,6 +78,7 @@ def get_conf():
}
return conf


class Device42:

def __init__(self, conf):
Expand Down Expand Up @@ -151,5 +153,6 @@ def write_inventory_file(groups):

return True


if __name__ == "__main__":
print(get_conf())
print(get_conf())
4 changes: 2 additions & 2 deletions galaxy.yml
@@ -1,6 +1,6 @@
namespace: "device42"
name: "d42"
version: "1.0.1"
version: "1.0.2"
readme: "README.md"
authors:
- "Will Tome (@willtome)"
Expand All @@ -12,4 +12,4 @@ tags:
- device42
- integration
- collection
repository: "https://github.com/device42/ansible_device42"
repository: "https://github.com/device42/ansible_device42"
35 changes: 15 additions & 20 deletions plugins/inventory/d42.py
@@ -1,7 +1,6 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function
from __future__ import (absolute_import, division, print_function)
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable, to_safe_group_name
import requests

__metaclass__ = type

Expand Down Expand Up @@ -61,24 +60,22 @@
separator: ''
'''

from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable, to_safe_group_name
import requests


class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
NAME = 'device42.d42.d42'

def verify_file(self, path):
valid = False
if super(InventoryModule, self).verify_file(path):
if path.endswith(('d42.yaml', 'd42.yml')):
valid = True
else:
self.display.vvv('Skipping due to inventory source not ending in "d42.yaml" nor "d42.yml"')
return valid
valid = False

if super(InventoryModule, self).verify_file(path):
if path.endswith(('d42.yaml', 'd42.yml')):
valid = True
else:
self.display.vvv('Skipping due to inventory source not ending in "d42.yaml" nor "d42.yml"')

return valid

def parse(self, inventory, loader, path, cache=False):
def parse(self, inventory, loader, path, cache=False):
super(InventoryModule, self).parse(inventory, loader, path)

self._read_config_data(path)
Expand All @@ -92,7 +89,8 @@ def parse(self, inventory, loader, path, cache=False):
try:
objects = []

response = requests.get(base_url + "/api/1.0/devices/all", auth=(username, password), verify=ssl_check, timeout=10)
response = requests.get(base_url + "/api/1.0/devices/all", auth=(username, password), verify=ssl_check,
timeout=10)

print('response code: ' + str(response.status_code))
json_response = response.json()
Expand All @@ -105,7 +103,7 @@ def parse(self, inventory, loader, path, cache=False):
for k in object_.keys():
self.inventory.set_variable(host_name, 'd42_' + k, object_[k])

if object_['ip_addresses'] != []:
if object_['ip_addresses']:
self.inventory.set_variable(host_name, 'ansible_host', object_['ip_addresses'][0]['ip'])

self._set_composite_vars(
Expand All @@ -117,6 +115,3 @@ def parse(self, inventory, loader, path, cache=False):
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), dict(), host_name, strict)
except Exception as e:
print(e)



38 changes: 20 additions & 18 deletions plugins/lookup/d42.py
@@ -1,6 +1,14 @@
from __future__ import (absolute_import, division, print_function)
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
import json, requests, sys, csv, io, os
import json
import requests
import sys
import csv
import io
import os
from ansible.utils.display import Display
display = Display()

if 'D42_SKIP_SSL_CHECK' in os.environ and os.environ['D42_SKIP_SSL_CHECK'] == 'True':
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
Expand All @@ -17,11 +25,8 @@
print('Please set D42_PWD environ.')
sys.exit()

try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()

__metaclass__ = type


class LookupModule(LookupBase):
Expand All @@ -30,12 +35,13 @@ class LookupModule(LookupBase):
def get_list_from_csv(text):
f = io.StringIO(text)
output_list = []
dict_reader = csv.DictReader(f, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True, dialect='excel')
dict_reader = csv.DictReader(f, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True,
dialect='excel')
for item in dict_reader:
output_list.append(item)

if len(output_list) == 1:
output_list = [output_list,]
output_list = [output_list, ]

return output_list

Expand All @@ -47,11 +53,11 @@ def run(self, terms, variables=None, **kwargs):
}

if terms[1] == "password":
return self.getUserPass(conf, terms[0], terms[2])
return self.get_user_pass(conf, terms[0], terms[2])
elif terms[1] == "doql":
return self.runDoql(conf, terms[0], terms[2])
return self.run_doql(conf, terms[0], terms[2])

def getUserPass(self, conf, device, username):
def get_user_pass(self, conf, device, username):
url = conf['D42_URL'] + "/api/1.0/passwords/?plain_text=yes&device=" + device + "&username=" + username
resp = requests.request("GET",
url,
Expand All @@ -72,25 +78,21 @@ def getUserPass(self, conf, device, username):
else:
raise AnsibleError("No password found for user: %s and device: %s" % (username, device))

def runDoql(self, conf, query, output_type):
def run_doql(self, conf, query, output_type):
url = conf['D42_URL'] + "/services/data/v1.0/query/"

post_data = {
"query": query.replace("@", "'"),
"header": 'yes' if output_type == 'list_dicts' else 'no'
}

resp = requests.request("POST",
url,
auth=(conf['D42_USER'], conf['D42_PWD']),
data=post_data,
verify=False)
resp = requests.request("POST", url, auth=(conf['D42_USER'], conf['D42_PWD']), data=post_data, verify=False)

if resp.status_code != 200:
raise AnsibleError("API Call failed with status code: " + str(resp.status_code))

if output_type == 'string':
return [resp.text.replace('\n', ''),]
return [resp.text.replace('\n', ''), ]
elif output_type == 'list':
return resp.text.split('\n')

Expand Down
35 changes: 20 additions & 15 deletions plugins/lookup/d42_prompt.py
@@ -1,15 +1,19 @@
from __future__ import (absolute_import, division, print_function)
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
import json, requests, imp, sys, csv, io, os
import json
import requests
import csv
import io
import os

if 'D42_SKIP_SSL_CHECK' in os.environ and os.environ['D42_SKIP_SSL_CHECK'] == 'True':
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)

try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
from ansible.utils.display import Display
display = Display()

__metaclass__ = type


class LookupModule(LookupBase):
Expand All @@ -18,27 +22,28 @@ class LookupModule(LookupBase):
def get_list_from_csv(text):
f = io.StringIO(text)
output_list = []
dict_reader = csv.DictReader(f, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True, dialect='excel')
dict_reader = csv.DictReader(f, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True,
dialect='excel')
for item in dict_reader:
output_list.append(item)

if len(output_list) == 1:
output_list = [output_list,]
output_list = [output_list, ]

return output_list

def run(self, terms, variables=None, **kwargs):
conf = {
'D42_URL': terms[0],
'D42_USER': terms[1],
'D42_URL': terms[0],
'D42_USER': terms[1],
'D42_PWD': terms[2],
}
if terms[4] == "password":
return self.getUserPass(conf, terms[3], terms[5])
return self.get_user_pass(conf, terms[3], terms[5])
elif terms[4] == "doql":
return self.runDoql(conf, terms[3], terms[5])
return self.run_doql(conf, terms[3], terms[5])

def getUserPass(self, conf, device, username):
def get_user_pass(self, conf, device, username):
url = conf['D42_URL'] + "/api/1.0/passwords/?plain_text=yes&device=" + device + "&username=" + username
resp = requests.request("GET",
url,
Expand All @@ -59,7 +64,7 @@ def getUserPass(self, conf, device, username):
else:
raise AnsibleError("No password found for user: %s and device: %s" % (username, device))

def runDoql(self, conf, query, output_type):
def run_doql(self, conf, query, output_type):
url = conf['D42_URL'] + "/services/data/v1.0/query/"

post_data = {
Expand All @@ -77,7 +82,7 @@ def runDoql(self, conf, query, output_type):
raise AnsibleError("API Call failed with status code: " + str(resp.status_code))

if output_type == 'string':
return [resp.text.replace('\n', ''),]
return [resp.text.replace('\n', ''), ]
elif output_type == 'list':
return resp.text.split('\n')

Expand Down

0 comments on commit ca81a92

Please sign in to comment.