コード例 #1
0
ファイル: nsxt_rest.py プロジェクト: vmware/ansible-for-nsxt
    def __init__(self, module):
        self.module = module
        self.mgr_hostname = module.params["hostname"]
        self.mgr_username = module.params["username"]
        self.mgr_password = module.params["password"]
        self.path = module.params["path"]
        self.method = module.params["method"]
        self.src = module.params["src"]
        self.content = module.params["content"]

        self.manager_url = "https://{}".format(self.mgr_hostname)
        self.headers = {
            "authorization":
            basic_auth_header(self.mgr_username, self.mgr_password),
            "Accept":
            "application/json",
            "Content-Type":
            "application/json"
        }

        if self.src:
            if os.path.isfile(self.src):
                try:
                    with open(self.src, "r") as f:
                        self.content = json.loads(f.read())
                except Exception as err:
                    self.module.fail_json(msg="src read error: %s" % err)
            else:
                self.module.fail_json(msg="cannot find/access src '%s'" %
                                      self.src)
コード例 #2
0
 def setUp(self):
     self.authorization = basic_auth_header("admin", "changeme")
     self.mock_module_helper = patch.multiple(basic.AnsibleModule,
                                              exit_json=exit_json,
                                              fail_json=fail_json)
     self.mock_module_helper.start()
     self.addCleanup(self.mock_module_helper.stop)
コード例 #3
0
 def __init__(self, username, password, url):
     urls.Request.__init__(self)
     self.username = username
     self.password = password
     self.url = url
     self.auth_header = {'Authorization':
                         urls.basic_auth_header(self.username, self.password)}
コード例 #4
0
ファイル: bitbucket.py プロジェクト: mator/community.general
    def request(self, api_url, method, data=None, headers=None):
        headers = headers or {}

        if self.access_token:
            headers.update({
                'Authorization': 'Bearer {0}'.format(self.access_token),
            })
        elif self.module.params['user'] and self.module.params['password']:
            headers.update({
                'Authorization': basic_auth_header(self.module.params['user'], self.module.params['password']),
            })

        if isinstance(data, dict):
            data = self.module.jsonify(data)
            headers.update({
                'Content-type': 'application/json',
            })

        response, info = fetch_url(
            module=self.module,
            url=api_url,
            method=method,
            headers=headers,
            data=data,
            force=True,
        )

        content = {}

        if response is not None:
            body = to_text(response.read())
            if body:
                content = json.loads(body)

        return info, content
コード例 #5
0
 def __init__(self, module):
     self._module = module
     # {{{ Authentication header
     self.headers = {"Content-Type": "application/json"}
     self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password'])
     # }}}
     self.grafana_url = module.params.get("url")
コード例 #6
0
    def grafana_headers(self):
        headers = {'content-type': 'application/json; charset=utf8'}
        if self.grafana_api_key:
            headers['Authorization'] = "Bearer %s==" % self.grafana_api_key
        else:
            headers['Authorization'] = basic_auth_header(self.grafana_user, self.grafana_password)
            self.grafana_switch_organisation(headers)

        return headers
コード例 #7
0
def get_output_format_and_apply_config_func_for_http(upload_url,
                                                     cluster_cookie):
    assert cluster_cookie is not None, 'Cluster cookie is required for HTTP mode'
    assert upload_url is not None, 'Upload URL is required for HTTP mode'

    headers = {'Authorization': basic_auth_header('admin', cluster_cookie)}

    return FILE_OUTPUT_FORMAT, lambda path: send_on_http(
        upload_url, headers, path)
コード例 #8
0
 def __init__(self, module, url, url_username, url_password, token):
     self.module = module
     self.url = url
     self.headers = {"Content-Type": "application-json", "Accept": "application/json"}
     if url_username and url_password:
         authorization = basic_auth_header(url_username, url_password)
     elif token:
         authorization = "Bearer %s" % token
     self.headers["Authorization"] = authorization
コード例 #9
0
 def __init__(self, module):
     self._module = module
     self.grafana_url = module.params.get("url")
     # {{{ Authentication header
     self.headers = {"Content-Type": "application/json"}
     if module.params.get('grafana_api_key', None):
         self.headers["Authorization"] = "Bearer %s" % module.params['grafana_api_key']
     else:
         self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password'])
         self.switch_organisation(module.params['org_id'])
コード例 #10
0
 def __init__(self, module):
     self._module = module
     # {{{ Authentication header
     self.headers = {"Content-Type": "application/json"}
     if module.params.get('grafana_api_key', None):
         self.headers["Authorization"] = "Bearer %s" % module.params['grafana_api_key']
     else:
         self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password'])
     # }}}
     self.grafana_url = module.params.get("url")
     grafana_version = self.get_version()
     if grafana_version["major"] < 5:
         self._module.fail_json(failed=True, msg="Folders API is available starting Grafana v5")
コード例 #11
0
    def __init__(self, module):
        self.module = module
        self.state = module.params['state']
        self.customer = module.params['customer']
        self.match = module.params['match']
        self.alerta_url = module.params['alerta_url']
        self.headers = {"Content-Type": "application/json"}

        if module.params.get('api_key', None):
            self.headers["Authorization"] = "Key %s" % module.params['api_key']
        else:
            self.headers["Authorization"] = basic_auth_header(
                module.params['api_username'], module.params['api_password'])
コード例 #12
0
def grafana_delete_datasource(module, data):

    # define http headers
    headers = {'content-type': 'application/json'}
    if 'grafana_api_key' in data and data['grafana_api_key']:
        headers['Authorization'] = "Bearer %s" % data['grafana_api_key']
    else:
        headers['Authorization'] = basic_auth_header(data['grafana_user'],
                                                     data['grafana_password'])
        grafana_switch_organisation(module, data['grafana_url'],
                                    data['org_id'], headers)

    # test if datasource already exists
    datasource_exists, ds = grafana_datasource_exists(module,
                                                      data['grafana_url'],
                                                      data['name'],
                                                      headers=headers)

    result = {}
    if datasource_exists is True:
        # delete
        r, info = fetch_url(module,
                            '%s/api/datasources/name/%s' %
                            (data['grafana_url'], data['name']),
                            headers=headers,
                            method='DELETE')
        if info['status'] == 200:
            res = json.loads(r.read())
            result['msg'] = "Datasource %s deleted : %s" % (data['name'],
                                                            res['message'])
            result['changed'] = True
            result['name'] = data['name']
            result['id'] = 0
        else:
            raise GrafanaAPIException(
                'Unable to update the datasource id %s : %s' %
                (ds['id'], info))
    else:
        # datasource does not exist, do nothing
        result = {
            'msg': "Datasource %s does not exist." % data['name'],
            'changed': False,
            'id': 0,
            'name': data['name']
        }

    return result
コード例 #13
0
ファイル: bitbucket.py プロジェクト: mator/community.general
    def fetch_access_token(self):
        if self.module.params['client_id'] and self.module.params['client_secret']:
            headers = {
                'Authorization': basic_auth_header(self.module.params['client_id'], self.module.params['client_secret']),
            }

            info, content = self.request(
                api_url='https://bitbucket.org/site/oauth2/access_token',
                method='POST',
                data='grant_type=client_credentials',
                headers=headers,
            )

            if info['status'] == 200:
                self.access_token = content['access_token']
            else:
                self.module.fail_json(msg='Failed to retrieve access token: {0}'.format(info))
コード例 #14
0
    def grafana_headers(self):
        headers = {'content-type': 'application/json; charset=utf8'}
        if self.grafana_api_key:
            api_key = self.grafana_api_key
            if len(api_key) % 4 == 2:
                display.deprecated(
                    "Passing a mangled version of the API key to the grafana_dashboard lookup is no longer necessary and should not be done.",
                    "2.0.0",
                    collection_name='community.grafana',
                )
                api_key += '=='
            headers['Authorization'] = "Bearer %s" % api_key
        else:
            headers['Authorization'] = basic_auth_header(
                self.grafana_user, self.grafana_password)
            self.grafana_switch_organisation(headers)

        return headers
コード例 #15
0
 def __init__(self, module):
     self._module = module
     # {{{ Authentication header
     self.headers = {"Content-Type": "application/json"}
     if module.params.get('grafana_api_key', None):
         self.headers["Authorization"] = "Bearer %s" % module.params[
             'grafana_api_key']
     else:
         self.headers["Authorization"] = basic_auth_header(
             module.params['url_username'], module.params['url_password'])
     # }}}
     self.grafana_url = base.clean_url(module.params.get("url"))
     if module.params.get("skip_version_check") is False:
         try:
             grafana_version = self.get_version()
         except GrafanaError as e:
             self._module.fail_json(failed=True, msg=to_text(e))
         if grafana_version["major"] < 5:
             self._module.fail_json(
                 failed=True,
                 msg="Teams API is available starting Grafana v5")
コード例 #16
0
def grafana_create_datasource(module, data):

    # define data payload for grafana API
    payload = {
        'orgId': data['org_id'],
        'name': data['name'],
        'type': data['ds_type'],
        'access': data['access'],
        'url': data['url'],
        'database': data['database'],
        'withCredentials': data['with_credentials'],
        'isDefault': data['is_default'],
        'user': data['user'],
        'password': data['password']
    }

    # define basic auth
    if 'basic_auth_user' in data and data[
            'basic_auth_user'] and 'basic_auth_password' in data and data[
                'basic_auth_password']:
        payload['basicAuth'] = True
        payload['basicAuthUser'] = data['basic_auth_user']
        payload['basicAuthPassword'] = data['basic_auth_password']
    else:
        payload['basicAuth'] = False

    # define tls auth
    json_data = {}
    if data.get('tls_client_cert') and data.get('tls_client_key'):
        json_data['tlsAuth'] = True
        if data.get('tls_ca_cert'):
            payload['secureJsonData'] = {
                'tlsCACert': data['tls_ca_cert'],
                'tlsClientCert': data['tls_client_cert'],
                'tlsClientKey': data['tls_client_key']
            }
            json_data['tlsAuthWithCACert'] = True
        else:
            payload['secureJsonData'] = {
                'tlsClientCert': data['tls_client_cert'],
                'tlsClientKey': data['tls_client_key']
            }
    else:
        json_data['tlsAuth'] = False
        json_data['tlsAuthWithCACert'] = False
        if data.get('tls_ca_cert'):
            payload['secureJsonData'] = {'tlsCACert': data['tls_ca_cert']}

    if data.get('tls_skip_verify'):
        json_data['tlsSkipVerify'] = True

    # datasource type related parameters
    if data['ds_type'] == 'elasticsearch':
        json_data['esVersion'] = data['es_version']
        json_data['timeField'] = data['time_field']
        if data.get('interval'):
            json_data['interval'] = data['interval']
        if data['es_version'] >= 56:
            json_data['maxConcurrentShardRequests'] = data[
                'max_concurrent_shard_requests']

    if data['ds_type'] == 'elasticsearch' or data['ds_type'] == 'influxdb':
        if data.get('time_interval'):
            json_data['timeInterval'] = data['time_interval']

    if data['ds_type'] == 'opentsdb':
        json_data['tsdbVersion'] = data['tsdb_version']
        if data['tsdb_resolution'] == 'second':
            json_data['tsdbResolution'] = 1
        else:
            json_data['tsdbResolution'] = 2

    if data['ds_type'] == 'postgres':
        json_data['sslmode'] = data['sslmode']

    if data['ds_type'] == 'alexanderzobnin-zabbix-datasource':
        if data.get('trends'):
            json_data['trends'] = True

    payload['jsonData'] = json_data

    # define http header
    headers = {'content-type': 'application/json; charset=utf8'}
    if 'grafana_api_key' in data and data['grafana_api_key'] is not None:
        headers['Authorization'] = "Bearer %s" % data['grafana_api_key']
    else:
        headers['Authorization'] = basic_auth_header(data['grafana_user'],
                                                     data['grafana_password'])
        grafana_switch_organisation(module, data['grafana_url'],
                                    data['org_id'], headers)

    # test if datasource already exists
    datasource_exists, ds = grafana_datasource_exists(module,
                                                      data['grafana_url'],
                                                      data['name'],
                                                      headers=headers)

    result = {}
    if datasource_exists is True:
        del ds['typeLogoUrl']
        if ds['basicAuth'] is False:
            del ds['basicAuthUser']
            del ds['basicAuthPassword']
        if 'jsonData' in ds:
            if 'tlsAuth' in ds[
                    'jsonData'] and ds['jsonData']['tlsAuth'] is False:
                del ds['secureJsonFields']
            if 'tlsAuth' not in ds['jsonData']:
                del ds['secureJsonFields']
        payload['id'] = ds['id']
        if ds == payload:
            # unchanged
            result['name'] = data['name']
            result['id'] = ds['id']
            result['msg'] = "Datasource %s unchanged." % data['name']
            result['changed'] = False
        else:
            # update
            r, info = fetch_url(module,
                                '%s/api/datasources/%d' %
                                (data['grafana_url'], ds['id']),
                                data=json.dumps(payload),
                                headers=headers,
                                method='PUT')
            if info['status'] == 200:
                res = json.loads(r.read())
                result['name'] = data['name']
                result['id'] = ds['id']
                result['before'] = ds
                result['after'] = payload
                result['msg'] = "Datasource %s updated %s" % (data['name'],
                                                              res['message'])
                result['changed'] = True
            else:
                raise GrafanaAPIException(
                    'Unable to update the datasource id %d : %s' %
                    (ds['id'], info))
    else:
        # create
        r, info = fetch_url(module,
                            '%s/api/datasources' % data['grafana_url'],
                            data=json.dumps(payload),
                            headers=headers,
                            method='POST')
        if info['status'] == 200:
            res = json.loads(r.read())
            result['msg'] = "Datasource %s created : %s" % (data['name'],
                                                            res['message'])
            result['changed'] = True
            result['name'] = data['name']
            result['id'] = res['id']
        else:
            raise GrafanaAPIException(
                'Unable to create the new datasource %s : %s - %s.' %
                (data['name'], info['status'], info))

    return result
コード例 #17
0
ファイル: test_urls.py プロジェクト: awiddersheim/ansible
def test_basic_auth_header():
    header = urls.basic_auth_header('user', 'passwd')
    assert header == b'Basic dXNlcjpwYXNzd2Q='
コード例 #18
0
ファイル: test_urls.py プロジェクト: zzhang01/ansible
def test_basic_auth_header():
    header = urls.basic_auth_header('user', 'passwd')
    assert header == b'Basic dXNlcjpwYXNzd2Q='
コード例 #19
0
 def _login_username_password(self):
     return dict(
         Authorization=basic_auth_header(self.username, self.password))