def get(resource):
    base_url = 'https://10.8.38.187/api/v2/%s' % resource
    headers = {'Content-Type': 'application/json'}

    req = Request(headers=headers, url_username='******', url_password='******',
                  validate_certs=False, force_basic_auth=True)

    resp = req.get(base_url)
    return resp.read()
Пример #2
0
    def run(self, terms, variables=None, **kwargs):

        base_url = "https://%s/api/v2" % variables['tower_host']
        headers = {'Content-type': 'application/json'}

        username = variables['tower_username']
        password = variables['tower_password']
        verify_ssl = variables.get('tower_verify_ssl')

        req = Request(headers=headers,
                      url_username=username,
                      url_password=password,
                      validate_certs=verify_ssl,
                      force_basic_auth=True)

        url = "%s/%s" % (base_url, terms[0])

        resp = req.get(url)
        resp = json.loads(resp.read())

        return resp['results']
Пример #3
0
    def read_tower_inventory(self,
                             tower_host,
                             tower_user,
                             tower_pass,
                             inventory,
                             verify_ssl=True):
        if not re.match('(?:http|https)://', tower_host):
            tower_host = 'https://{tower_host}'.format(tower_host=tower_host)
        inventory_id = inventory.replace('/', '')
        inventory_url = '/api/v2/inventories/{inv_id}/script/?hostvars=1&towervars=1&all=1'.format(
            inv_id=inventory_id)
        inventory_url = urljoin(tower_host, inventory_url)

        request_handler = Request(url_username=tower_user,
                                  url_password=tower_pass,
                                  force_basic_auth=True,
                                  validate_certs=verify_ssl)

        try:
            response = request_handler.get(inventory_url)
        except (ConnectionError, urllib_error.URLError, socket.error,
                httplib.HTTPException) as e:
            error_msg = 'Connection to remote host failed: {err}'.format(err=e)
            # If Tower gives a readable error message, display that message to the user.
            if callable(getattr(e, 'read', None)):
                error_msg += ' with message: {err_msg}'.format(
                    err_msg=e.read())
            raise AnsibleParserError(to_native(error_msg))

        # Attempt to parse JSON.
        try:
            return json.loads(response.read())
        except (ValueError, TypeError) as e:
            # If the JSON parse fails, print the ValueError
            raise AnsibleParserError(
                to_native(
                    'Failed to parse json from host: {err}'.format(err=e)))
Пример #4
0
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):

    NAME = 'community.digitalocean.digitalocean'

    def verify_file(self, path):
        valid = False
        if super(InventoryModule, self).verify_file(path):
            if path.endswith(('do_hosts.yaml', 'do_hosts.yml',
                              'digitalocean.yaml', 'digitalocean.yml',
                              'digital_ocean.yaml', 'digital_ocean.yml')):
                valid = True
            else:
                self.display.vvv(
                    'Skipping due to inventory source file name mismatch. '
                    'The file name has to end with one of the following: '
                    'do_hosts.yaml, do_hosts.yml '
                    'digitalocean.yaml, digitalocean.yml, '
                    'digital_ocean.yaml, digital_ocean.yml.')
        return valid

    def _get_payload(self):
        # request parameters
        api_token = self.get_option('api_token')
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer {0}'.format(api_token)
        }

        # build url
        pagination = self.get_option('pagination')
        url = 'https://api.digitalocean.com/v2/droplets?per_page=' + str(
            pagination)

        # send request(s)
        self.req = Request(headers=headers)
        payload = []
        try:
            while url:
                self.display.vvv('Sending request to {0}'.format(url))
                response = json.load(self.req.get(url))
                payload.extend(response['droplets'])
                url = response.get('links', {}).get('pages', {}).get('next')
        except ValueError:
            raise AnsibleParserError("something went wrong with JSON loading")
        except (URLError, HTTPError) as error:
            raise AnsibleParserError(error)

        return payload

    def _populate(self):
        attributes = self.get_option('attributes')
        var_prefix = self.get_option('var_prefix')
        strict = self.get_option('strict')
        for record in self._get_payload():

            # add host to inventory
            if record.get('name'):
                host_name = self.inventory.add_host(record.get('name'))
            else:
                continue

            # set variables for host
            for k, v in record.items():
                if k in attributes:
                    self.inventory.set_variable(host_name, var_prefix + k, v)

            self._set_composite_vars(
                self.get_option('compose'),
                self.inventory.get_host(host_name).get_vars(), host_name,
                strict)

            # set composed and keyed groups
            self._add_host_to_composed_groups(self.get_option('groups'),
                                              dict(), host_name, strict)
            self._add_host_to_keyed_groups(self.get_option('keyed_groups'),
                                           dict(), host_name, strict)

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

        # cache settings
        self._read_config_data(path)
        self.cache_key = self.get_cache_key(path)

        self.use_cache = self.get_option('cache') and cache
        self.update_cache = self.get_option('cache') and not cache

        results = []
        if not self.update_cache:
            try:
                results = self._cache[self.cache_key]['digitalocean']
            except KeyError:
                pass

        if not results:
            if self.cache_key not in self._cache:
                self._cache[self.cache_key] = {'digitalocean': ''}

        self._populate()
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):

    NAME = "community.digitalocean.digitalocean"

    # Constructable methods use the following function to construct group names. By
    # default, characters that are not valid in python variables, are always replaced by
    # underscores. We are overriding this with a function that respects the
    # TRANSFORM_INVALID_GROUP_CHARS configuration option and allows users to control the
    # behavior.
    _sanitize_group_name = staticmethod(to_safe_group_name)

    def verify_file(self, path):
        valid = False
        if super(InventoryModule, self).verify_file(path):
            if path.endswith((
                    "do_hosts.yaml",
                    "do_hosts.yml",
                    "digitalocean.yaml",
                    "digitalocean.yml",
                    "digital_ocean.yaml",
                    "digital_ocean.yml",
            )):
                valid = True
            else:
                self.display.vvv(
                    "Skipping due to inventory source file name mismatch. "
                    "The file name has to end with one of the following: "
                    "do_hosts.yaml, do_hosts.yml "
                    "digitalocean.yaml, digitalocean.yml, "
                    "digital_ocean.yaml, digital_ocean.yml.")
        return valid

    def _template_option(self, option):
        value = self.get_option(option)
        self.templar.available_variables = {}
        return self.templar.template(value)

    def _get_payload(self):
        # request parameters
        api_token = self._template_option("api_token")
        headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer {0}".format(api_token),
        }

        # build url
        pagination = self.get_option("pagination")
        url = "https://api.digitalocean.com/v2/droplets?per_page=" + str(
            pagination)

        # send request(s)
        self.req = Request(headers=headers)
        payload = []
        try:
            while url:
                self.display.vvv("Sending request to {0}".format(url))
                response = json.load(self.req.get(url))
                payload.extend(response["droplets"])
                url = response.get("links", {}).get("pages", {}).get("next")
        except ValueError:
            raise AnsibleParserError("something went wrong with JSON loading")
        except (URLError, HTTPError) as error:
            raise AnsibleParserError(error)

        return payload

    def _populate(self, records):
        attributes = self.get_option("attributes")
        var_prefix = self.get_option("var_prefix")
        strict = self.get_option("strict")
        host_filters = self.get_option("filters")
        for record in records:

            host_name = record.get("name")
            if not host_name:
                continue

            host_vars = {}
            for k, v in record.items():
                if k in attributes:
                    host_vars[var_prefix + k] = v

            if not self._passes_filters(host_filters, host_vars, host_name,
                                        strict):
                self.display.vvv(
                    "Host {0} did not pass all filters".format(host_name))
                continue

            # add host to inventory
            self.inventory.add_host(host_name)

            # set variables for host
            for k, v in host_vars.items():
                self.inventory.set_variable(host_name, k, v)

            self._set_composite_vars(
                self.get_option("compose"),
                self.inventory.get_host(host_name).get_vars(),
                host_name,
                strict,
            )

            # set composed and keyed groups
            self._add_host_to_composed_groups(self.get_option("groups"),
                                              dict(), host_name, strict)
            self._add_host_to_keyed_groups(self.get_option("keyed_groups"),
                                           dict(), host_name, strict)

    def _passes_filters(self, filters, variables, host, strict=False):
        if filters and isinstance(filters, list):
            for template in filters:
                try:
                    if not self._compose(template, variables):
                        return False
                except Exception as e:
                    if strict:
                        raise AnsibleError(
                            "Could not evaluate host filter {0} for host {1}: {2}"
                            .format(template, host, to_native(e)))
                    # Better be safe and not include any hosts by accident.
                    return False
        return True

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

        self._read_config_data(path)

        # cache settings
        cache_key = self.get_cache_key(path)
        use_cache = self.get_option("cache") and cache
        update_cache = self.get_option("cache") and not cache

        records = None
        if use_cache:
            try:
                records = self._cache[cache_key]
            except KeyError:
                update_cache = True

        if records is None:
            records = self._get_payload()

        if update_cache:
            self._cache[cache_key] = records

        self._populate(records)