From d123cd7525b462e0cf66ad02cc2450b31b114619 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Wed, 8 Nov 2023 15:44:36 +0000 Subject: [PATCH 01/40] docs: update README.md [skip ci] --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b601a44..3334529f 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ![](https://github.com/ansible-collections/grafana/workflows/CI/badge.svg?branch=master) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/community.grafana)](https://codecov.io/gh/ansible-collections/community.grafana) -[![All Contributors](https://img.shields.io/badge/all_contributors-19-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-20-orange.svg?style=flat-square)](#contributors-) This repo hosts the `community.grafana` Ansible Collection. @@ -253,6 +253,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d Pierre
Pierre

🐛 MiksonX
MiksonX

🐛 Aliaksandr Mianzhynski
Aliaksandr Mianzhynski

💻 ⚠️ + Moritz
Moritz

🐛 From 7c8f520c4e61fbe115c417bb43239c613cee136c Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Wed, 8 Nov 2023 15:44:37 +0000 Subject: [PATCH 02/40] docs: update .all-contributorsrc [skip ci] --- .all-contributorsrc | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index b7e51435..2c7b593a 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -187,6 +187,15 @@ "code", "test" ] + }, + { + "login": "Nemental", + "name": "Moritz", + "avatar_url": "https://avatars.githubusercontent.com/u/15136847?v=4", + "profile": "https://nemental.de", + "contributions": [ + "bug" + ] } ], "contributorsPerLine": 7, @@ -195,5 +204,6 @@ "repoType": "github", "repoHost": "https://github.com", "skipCi": true, - "commitConvention": "angular" + "commitConvention": "angular", + "commitType": "docs" } From cd53136f8be51e639a78baab2a6cd54bbd8e262c Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Wed, 8 Nov 2023 15:48:29 +0000 Subject: [PATCH 03/40] docs: update README.md [skip ci] --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3334529f..ce32c493 100644 --- a/README.md +++ b/README.md @@ -253,7 +253,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d Pierre
Pierre

🐛 MiksonX
MiksonX

🐛 Aliaksandr Mianzhynski
Aliaksandr Mianzhynski

💻 ⚠️ - Moritz
Moritz

🐛 + Moritz
Moritz

🐛 💻 From 21b6f4101e96247da04c61124c319a0740258a1b Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Wed, 8 Nov 2023 15:48:30 +0000 Subject: [PATCH 04/40] docs: update .all-contributorsrc [skip ci] --- .all-contributorsrc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 2c7b593a..f1a1cb6d 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -194,7 +194,8 @@ "avatar_url": "https://avatars.githubusercontent.com/u/15136847?v=4", "profile": "https://nemental.de", "contributions": [ - "bug" + "bug", + "code" ] } ], From 0100a21a4f537a381cdd5400ec810d57eb9059d9 Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Mon, 13 Nov 2023 16:40:52 +0100 Subject: [PATCH 05/40] default to true/false --- plugins/callback/grafana_annotations.py | 4 ++-- plugins/doc_fragments/basic_auth.py | 10 +++++----- plugins/modules/grafana_dashboard.py | 4 ++-- plugins/modules/grafana_datasource.py | 8 ++++---- plugins/modules/grafana_folder.py | 2 +- plugins/modules/grafana_notification_channel.py | 6 +++--- plugins/modules/grafana_plugin.py | 2 +- plugins/modules/grafana_team.py | 6 +++--- 8 files changed, 21 insertions(+), 21 deletions(-) diff --git a/plugins/callback/grafana_annotations.py b/plugins/callback/grafana_annotations.py index 04555eae..92b837c1 100644 --- a/plugins/callback/grafana_annotations.py +++ b/plugins/callback/grafana_annotations.py @@ -29,7 +29,7 @@ options: grafana_url: description: Grafana annotations api URL - required: True + required: true env: - name: GRAFANA_URL ini: @@ -45,7 +45,7 @@ key: validate_grafana_certs - section: callback_grafana_annotations key: validate_certs - default: True + default: true type: bool aliases: [ validate_grafana_certs ] http_agent: diff --git a/plugins/doc_fragments/basic_auth.py b/plugins/doc_fragments/basic_auth.py index 8c41acdb..c874457d 100644 --- a/plugins/doc_fragments/basic_auth.py +++ b/plugins/doc_fragments/basic_auth.py @@ -30,9 +30,9 @@ class ModuleDocFragment(object): aliases: [ grafana_password ] use_proxy: description: - - If C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts. + - If C(false), it will not use a proxy, even if one is defined in an environment variable on the target hosts. type: bool - default: yes + default: true client_cert: description: - PEM formatted certificate chain file to be used for SSL client authentication. @@ -45,8 +45,8 @@ class ModuleDocFragment(object): type: path validate_certs: description: - - If C(no), SSL certificates will not be validated. - - This should only set to C(no) used on personally controlled sites using self-signed certificates. + - If C(false), SSL certificates will not be validated. + - This should only set to C(false) used on personally controlled sites using self-signed certificates. type: bool - default: yes + default: true ''' diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index cc2654f6..46d3aeb1 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -58,7 +58,7 @@ description: - Override existing dashboard when state is present. type: bool - default: 'no' + default: false dashboard_id: description: - Public Grafana.com dashboard id to import @@ -92,7 +92,7 @@ grafana_api_key: "{{ grafana_api_key }}" state: present commit_message: Updated by ansible - overwrite: yes + overwrite: true path: /path/to/dashboards/foo.json - name: Import Grafana dashboard Zabbix diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 5f865ec5..0b2d1b64 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -86,7 +86,7 @@ type: str basic_auth_password: description: - - The datasource basic auth password, when C(basic auth) is C(yes). + - The datasource basic auth password, when C(basic auth) is C(true). - Stored as secure data, see C(enforce_secure_data) and notes! type: str with_credentials: @@ -94,7 +94,7 @@ - Whether credentials such as cookies or auth headers should be sent with cross-site requests. type: bool - default: 'no' + default: false tls_client_cert: description: - The client TLS certificate. @@ -123,7 +123,7 @@ description: - Make this datasource the default one. type: bool - default: 'no' + default: false org_id: description: - Grafana Organisation ID in which the datasource should be created. @@ -217,7 +217,7 @@ description: - Use trends or not for zabbix datasource type. type: bool - default: False + default: false aws_auth_type: description: - Type for AWS authentication for CloudWatch datasource type (authType of grafana diff --git a/plugins/modules/grafana_folder.py b/plugins/modules/grafana_folder.py index 380a510c..4dcb8453 100644 --- a/plugins/modules/grafana_folder.py +++ b/plugins/modules/grafana_folder.py @@ -50,7 +50,7 @@ - This parameter can be useful if you enabled `hide_version` in grafana.ini required: False type: bool - default: False + default: false version_added: "1.2.0" extends_documentation_fragment: - community.grafana.basic_auth diff --git a/plugins/modules/grafana_notification_channel.py b/plugins/modules/grafana_notification_channel.py index eb808fa1..1913c290 100644 --- a/plugins/modules/grafana_notification_channel.py +++ b/plugins/modules/grafana_notification_channel.py @@ -82,17 +82,17 @@ - Required when I(state) is C(present). is_default: type: bool - default: 'no' + default: false description: - Use this channel for all alerts. include_image: type: bool - default: 'no' + default: false description: - Capture a visualization image and attach it to notifications. disable_resolve_message: type: bool - default: 'no' + default: false description: - Disable the resolve message. reminder_frequency: diff --git a/plugins/modules/grafana_plugin.py b/plugins/modules/grafana_plugin.py index 7fd41876..073de119 100644 --- a/plugins/modules/grafana_plugin.py +++ b/plugins/modules/grafana_plugin.py @@ -50,7 +50,7 @@ validate_certs: description: - Boolean variable to include --insecure while installing pluging - default: False + default: false type: bool ''' diff --git a/plugins/modules/grafana_team.py b/plugins/modules/grafana_team.py index 7f8de845..b7b2318d 100644 --- a/plugins/modules/grafana_team.py +++ b/plugins/modules/grafana_team.py @@ -59,7 +59,7 @@ description: - Delete the members not found in the C(members) parameters from the - list of members found on the Team. - default: False + default: false type: bool skip_version_check: description: @@ -67,7 +67,7 @@ - This parameter can be useful if you enabled `hide_version` in grafana.ini required: False type: bool - default: False + default: false version_added: "1.2.0" extends_documentation_fragment: - community.grafana.basic_auth @@ -104,7 +104,7 @@ members: - john.doe@example.com - jane.doe@example.com - enforce_members: yes + enforce_members: true state: present - name: Delete a team From c57b9cdfa4de326dd348310a77a59efa68c1ac46 Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Mon, 13 Nov 2023 16:52:04 +0100 Subject: [PATCH 06/40] add changelog fragment --- changelogs/fragments/325_true_false.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 changelogs/fragments/325_true_false.yml diff --git a/changelogs/fragments/325_true_false.yml b/changelogs/fragments/325_true_false.yml new file mode 100644 index 00000000..c192d086 --- /dev/null +++ b/changelogs/fragments/325_true_false.yml @@ -0,0 +1,2 @@ +minor_changes: +- default to true/false in docs and code From 757d7ae6aa9180a42846a5e57e371395abe5c51a Mon Sep 17 00:00:00 2001 From: SHURAVIN Anatoly Date: Thu, 21 Dec 2023 13:48:03 +0300 Subject: [PATCH 07/40] Add tempo datasource support --- .../335-add-datasource-type-tempo.yml | 2 + plugins/modules/grafana_datasource.py | 4 +- .../grafana_datasource/tasks/tempo.yml | 78 +++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/335-add-datasource-type-tempo.yml create mode 100644 tests/integration/targets/grafana_datasource/tasks/tempo.yml diff --git a/changelogs/fragments/335-add-datasource-type-tempo.yml b/changelogs/fragments/335-add-datasource-type-tempo.yml new file mode 100644 index 00000000..18d34a0a --- /dev/null +++ b/changelogs/fragments/335-add-datasource-type-tempo.yml @@ -0,0 +1,2 @@ +minor_changes: + - Add support for Grafana Tempo datasource type (https://grafana.com/docs/grafana/latest/datasources/tempo/) \ No newline at end of file diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 0b2d1b64..f743303c 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -46,6 +46,7 @@ - camptocamp-prometheus-alertmanager-datasource - loki - redis-datasource + - tempo type: str ds_url: description: @@ -742,7 +743,8 @@ def setup_module_object(): 'camptocamp-prometheus-alertmanager-datasource', 'sni-thruk-datasource', 'redis-datasource', - 'loki']), + 'loki', + 'tempo']), ds_url=dict(type='str'), access=dict(default='proxy', choices=['proxy', 'direct']), database=dict(type='str', default=""), diff --git a/tests/integration/targets/grafana_datasource/tasks/tempo.yml b/tests/integration/targets/grafana_datasource/tasks/tempo.yml new file mode 100644 index 00000000..5065a6ce --- /dev/null +++ b/tests/integration/targets/grafana_datasource/tasks/tempo.yml @@ -0,0 +1,78 @@ +- name: Create tempo datasource + register: result + grafana_datasource: + name: datasource-tempo + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: tempo + ds_url: tempo.company.com:3100 + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-tempo created'" + +- name: Check tempo datasource creation idempotency + register: result + grafana_datasource: + name: datasource-tempo + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: tempo + ds_url: tempo.company.com:3100 + +- debug: + var: result + +- assert: + that: + - not result.changed + - result.datasource.basicAuth == false + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.secureJsonFields.httpHeaderValue1 == true + - result.datasource.name == 'datasource-tempo' + - result.datasource.orgId == 1 + - result.datasource.type == 'tempo' + - result.datasource.url == 'tempo.company.com:3100' + - result.datasource.withCredentials == false + +- name: Delete tempo datasource + register: result + grafana_datasource: + name: datasource-tempo + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: absent + +- debug: + var: result + +- assert: + that: + - result.changed + +- name: Delete tempo datasource + register: result + grafana_datasource: + name: datasource-tempo + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: absent + +- debug: + var: result + +- assert: + that: + - not result.changed From fff29cd0ad0b9463cfcc6735870be5b99d5c8412 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 16:33:09 +0100 Subject: [PATCH 08/40] feat: added org_name param and get id by name function --- plugins/modules/grafana_dashboard.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 46d3aeb1..20658d3e 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -157,6 +157,14 @@ class GrafanaDeleteException(Exception): pass +def grafana_organization_id_by_name(module, org_name): + r, info = fetch_url(module, '%s/orgs/name/%s' % (grafana_url, org_name), headers=headers, method='GET') + if info['status'] != 200: + raise GrafanaAPIException("Unable to retrieve organization: %s" % info) + + return json.loads(to_text(r.read())) + + def grafana_switch_organisation(module, grafana_url, org_id, headers): r, info = fetch_url(module, '%s/api/user/using/%s' % (grafana_url, org_id), headers=headers, method='POST') if info['status'] != 200: @@ -169,6 +177,10 @@ def grafana_headers(module, data): headers['Authorization'] = "Bearer %s" % data['grafana_api_key'] else: module.params['force_basic_auth'] = True + if module.params['org_name']: + org_name = module.params['org_name'] + organization = grafana_organization_id_by_name(module, org_name) + data['org_id'] = organization['id'] grafana_switch_organisation(module, data['url'], data['org_id'], headers) return headers @@ -186,7 +198,7 @@ def get_grafana_version(module, grafana_url, headers): except Exception as e: raise GrafanaAPIException(e) else: - raise GrafanaAPIException('Unable to get grafana version : %s' % info) + raise GrafanaAPIException('Unable to get grafana version: %s' % info) return int(grafana_version) @@ -490,6 +502,7 @@ def main(): argument_spec.update( state=dict(choices=['present', 'absent', 'export'], default='present'), org_id=dict(default=1, type='int'), + org_name=dict(type='str'), folder=dict(type='str', default='General'), uid=dict(type='str'), slug=dict(type='str'), @@ -507,8 +520,8 @@ def main(): required_if=[ ['state', 'export', ['path']], ], - required_together=[['url_username', 'url_password', 'org_id']], - mutually_exclusive=[['url_username', 'grafana_api_key'], ['uid', 'slug'], ['path', 'dashboard_id']], + required_together=[['url_username', 'url_password', 'org_id'], ['url_username', 'url_password', 'org_name']], + mutually_exclusive=[['url_username', 'grafana_api_key'], ['uid', 'slug'], ['path', 'dashboard_id'], ['org_id', 'org_name']], ) module.params["url"] = clean_url(module.params["url"]) From a89a2023e8e662ad0e4e9916e82929c2d4f56e8b Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:11:09 +0100 Subject: [PATCH 09/40] test: rewrite grafana_dashboard test --- .../grafana_dashboard/defaults/main.yml | 3 -- .../tasks/dashboard-export.yml | 25 ++++------- .../tasks/dashboard-folder-destination.yml | 45 +++++++------------ .../tasks/dashboard-from-file.yml | 29 +++++------- .../tasks/dashboard-from-id.yml | 20 +++------ .../tasks/dashboard-from-url.yml | 21 +++------ .../tasks/delete-dashboard.yml | 13 +++--- .../targets/grafana_dashboard/tasks/main.yml | 19 +++++--- 8 files changed, 67 insertions(+), 108 deletions(-) diff --git a/tests/integration/targets/grafana_dashboard/defaults/main.yml b/tests/integration/targets/grafana_dashboard/defaults/main.yml index 8b9c9348..7bb77ea3 100644 --- a/tests/integration/targets/grafana_dashboard/defaults/main.yml +++ b/tests/integration/targets/grafana_dashboard/defaults/main.yml @@ -1,7 +1,4 @@ --- - grafana_url: "http://grafana:3000/" grafana_username: "admin" grafana_password: "admin" - -... diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml index 04b17f72..e497d507 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml @@ -1,32 +1,25 @@ --- -- set_fact: - dashboard_uid: "{{ result.uid }}" - - name: Check export grafana dashboard to file - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: export - path: /tmp/dashboard.json + path: /tmp/dashboard_export.json overwrite: true - uid: "{{ dashboard_uid }}" + uid: "{{ result.uid }}" register: result - -- debug: - var: result - -- assert: +- ansible.builtin.assert: that: + - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard {{ dashboard_uid }} exported to /tmp/dashboard.json'" -- name: Load /tmp/dashboard.json or fail if missing - set_fact: - exported_dashboard_lines: "{{ lookup('file', '/tmp/dashboard.json').splitlines() }}" +- name: Load /tmp/dashboard_export.json or fail if missing + ansible.builtin.set_fact: + exported_dashboard_lines: "{{ lookup('file', '/tmp/dashboard_export.json').splitlines() }}" - name: Assert that exported dashboard contains formatted JSON - assert: + ansible.builtin.assert: that: - "exported_dashboard_lines | length >= 2" - "exported_dashboard_lines[0] == '{'" diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml index f4f3d9f4..4faf28bd 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml @@ -1,33 +1,18 @@ --- -- name: copy dashboard file - copy: - src: "files/dashboard.json" - dest: "/tmp/dashboard.json" - -- block: - - name: Check import grafana dashboard from file to unknown folder fails - grafana_dashboard: - grafana_url: "{{ grafana_url }}" - grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password }}" - state: present - commit_message: Updated by ansible - path: /tmp/dashboard.json - overwrite: true - folder: inexistent - register: result - ignore_errors: true - -- debug: - var: result - -- set_fact: - # XXX: Too many quotes of different types to do inline. - # I did not manage to find a good way of having it inline. - expected_error: "error : Dashboard folder 'inexistent' does not exist." - -- assert: +- name: Check import grafana dashboard from file to unknown folder fails + community.grafana.grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + path: /tmp/dashboard.json + overwrite: true + folder: inexistent + register: result + ignore_errors: true +- ansible.builtin.assert: that: - - "result.changed == false" - "result.failed == true" - - "result.msg == expected_error" + - "result.changed == false" + - "result.msg == 'error : Dashboard folder \\'inexistent\\' does not exist.'" diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml index 93df1666..d883cedd 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml @@ -1,12 +1,11 @@ --- -- name: copy dashboard file - copy: +- name: Copy dashboard file + ansible.builtin.copy: src: "files/dashboard.json" dest: "/tmp/dashboard.json" - - name: Check import grafana dashboard from file - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" @@ -15,17 +14,13 @@ path: /tmp/dashboard.json overwrite: true register: result - -- debug: - var: result - -- assert: +- ansible.builtin.assert: that: + - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard test created'" - name: Check import grafana dashboard from file idempotency - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" @@ -34,11 +29,11 @@ path: /tmp/dashboard.json overwrite: true register: result - -- debug: - var: result - -- assert: +- ansible.builtin.assert: that: + - "result.failed == false" - "result.changed == false" - - "result.msg == 'Dashboard test unchanged.'" + +- ansible.builtin.include_tasks: dashboard-export.yml + +- ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml index 3b81ebf7..1c2336b9 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml @@ -1,6 +1,6 @@ --- - name: Check import grafana dashboard from id - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" @@ -10,17 +10,13 @@ dashboard_revision: "1" overwrite: true register: result - -- debug: - var: result - - assert: that: + - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard Zabbix Host Status created'" - name: Check import grafana dashboard from id idempotency - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" @@ -30,11 +26,9 @@ dashboard_revision: "1" overwrite: true register: result - -- debug: - var: result - -- assert: +- ansible.builtin.assert: that: + - "result.failed == false" - "result.changed == false" - - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" + +- ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml index 5146fc9a..34336b96 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml @@ -1,7 +1,6 @@ --- - - name: Check import grafana dashboard from url - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" @@ -10,17 +9,13 @@ dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download overwrite: true register: result - -- debug: - var: result - - assert: that: + - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard Zabbix Host Status created'" - name: Check import grafana dashboard from url idempotency - grafana_dashboard: + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" @@ -29,11 +24,9 @@ dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download overwrite: true register: result - -- debug: - var: result - -- assert: +- ansible.builtin.assert: that: + - "result.failed == false" - "result.changed == false" - - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" + +- ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml index 2013324f..a0ccb487 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml @@ -1,16 +1,13 @@ -- name: Check delete dashboard is working - grafana_dashboard: +--- +- name: Delete dashboard + community.grafana.grafana_dashboard: grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent uid: "{{ result.uid }}" register: result - -- debug: - var: result - -- assert: +- ansible.builtin.assert: that: + - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard {{ result.uid }} deleted'" diff --git a/tests/integration/targets/grafana_dashboard/tasks/main.yml b/tests/integration/targets/grafana_dashboard/tasks/main.yml index 570fb4d8..65e9a611 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/main.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/main.yml @@ -1,7 +1,12 @@ -- block: - - include_tasks: dashboard-from-url.yml - - include_tasks: delete-dashboard.yml - - include_tasks: dashboard-from-id.yml - - include_tasks: dashboard-from-file.yml - - include_tasks: dashboard-export.yml - - include_tasks: dashboard-folder-destination.yml +--- +- name: Create dashboard from url and delete it + ansible.builtin.include_tasks: dashboard-from-url.yml + +- name: Create dashboard from id and delete it + ansible.builtin.include_tasks: dashboard-from-id.yml + +- name: Create dashboard from file, export and delete it + ansible.builtin.include_tasks: dashboard-from-file.yml + +- name: Create dashboard in non existing folder + ansible.builtin.include_tasks: dashboard-folder-destination.yml From dc353fdb306b9bd3134abb2bd11afc0e69df48fe Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:12:14 +0100 Subject: [PATCH 10/40] test: indention --- .../integration/targets/grafana_dashboard/tasks/main.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/integration/targets/grafana_dashboard/tasks/main.yml b/tests/integration/targets/grafana_dashboard/tasks/main.yml index 65e9a611..fce2aeaa 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/main.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/main.yml @@ -1,12 +1,12 @@ --- - name: Create dashboard from url and delete it - ansible.builtin.include_tasks: dashboard-from-url.yml + ansible.builtin.include_tasks: dashboard-from-url.yml - name: Create dashboard from id and delete it - ansible.builtin.include_tasks: dashboard-from-id.yml + ansible.builtin.include_tasks: dashboard-from-id.yml - name: Create dashboard from file, export and delete it - ansible.builtin.include_tasks: dashboard-from-file.yml + ansible.builtin.include_tasks: dashboard-from-file.yml - name: Create dashboard in non existing folder - ansible.builtin.include_tasks: dashboard-folder-destination.yml + ansible.builtin.include_tasks: dashboard-folder-destination.yml From e235c70f10e44e5745de4ea0a8b607eafe523b4e Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:15:03 +0100 Subject: [PATCH 11/40] fix: remove required_together --- plugins/modules/grafana_dashboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 20658d3e..57c88cf0 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -520,7 +520,7 @@ def main(): required_if=[ ['state', 'export', ['path']], ], - required_together=[['url_username', 'url_password', 'org_id'], ['url_username', 'url_password', 'org_name']], + required_together=[['url_username', 'url_password', 'org_id']], mutually_exclusive=[['url_username', 'grafana_api_key'], ['uid', 'slug'], ['path', 'dashboard_id'], ['org_id', 'org_name']], ) From 8f5a8039d6eba6885d9b1fd8ae281eb57f75acaf Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:48:56 +0100 Subject: [PATCH 12/40] test: create dashboard by file org_name --- .../tasks/dashboard-by-org-name.yml | 36 +++++++++++++++++++ ...ile.yml => dashboard-from-file-export.yml} | 0 .../targets/grafana_dashboard/tasks/main.yml | 11 +++--- 3 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml rename tests/integration/targets/grafana_dashboard/tasks/{dashboard-from-file.yml => dashboard-from-file-export.yml} (100%) diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml new file mode 100644 index 00000000..b8b9d3fe --- /dev/null +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml @@ -0,0 +1,36 @@ +--- +- module_defaults: + community.grafana.grafana_dashboard: + org_name: Main Org. + block: + - name: Check import grafana dashboard from file + community.grafana.grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + path: /tmp/dashboard.json + overwrite: true + register: result + - ansible.builtin.assert: + that: + - "result.failed == false" + - "result.changed == true" + + - name: Check import grafana dashboard from file idempotency + community.grafana.grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + path: /tmp/dashboard.json + overwrite: true + register: result + - ansible.builtin.assert: + that: + - "result.failed == false" + - "result.changed == false" + + - ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml similarity index 100% rename from tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml rename to tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/main.yml b/tests/integration/targets/grafana_dashboard/tasks/main.yml index fce2aeaa..0a082d43 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/main.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/main.yml @@ -1,12 +1,15 @@ --- -- name: Create dashboard from url and delete it +- name: Create dashboard from url ansible.builtin.include_tasks: dashboard-from-url.yml -- name: Create dashboard from id and delete it +- name: Create dashboard from id ansible.builtin.include_tasks: dashboard-from-id.yml -- name: Create dashboard from file, export and delete it - ansible.builtin.include_tasks: dashboard-from-file.yml +- name: Create dashboard from file and export + ansible.builtin.include_tasks: dashboard-from-file-export.yml + +- name: Create dashboard from file by org_name + ansible.builtin.include_tasks: dashboard-by-org-name.yml - name: Create dashboard in non existing folder ansible.builtin.include_tasks: dashboard-folder-destination.yml From 996f4dafee0795ed49ded665916fe19d51ecbfde Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:59:13 +0100 Subject: [PATCH 13/40] docs: org_name added --- plugins/modules/grafana_dashboard.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 57c88cf0..10d585ab 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -18,10 +18,17 @@ options: org_id: description: - - The Grafana Organisation ID where the dashboard will be imported / exported. - - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organisation.. + - The Grafana Organisation ID where the dashboard will be imported / exported / deleted. + - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organisation. + - Mutually exclusive with `org_name`. default: 1 type: int + org_name: + description: + - The Grafana Organisation name where the dashboard will be imported / exported / deleted. + - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organisation. + - Mutually exclusive with `org_id`. + type: str folder: description: - The Grafana folder where this dashboard will be imported to. From 55fffb458517ea0b846c7d901c982b144429ff59 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 18:09:26 +0100 Subject: [PATCH 14/40] fix: function arguments, url encode url --- plugins/modules/grafana_dashboard.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 10d585ab..ec8b19d9 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -138,6 +138,7 @@ ''' import json +import urllib.parse from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url from ansible.module_utils.six.moves.urllib.parse import urlencode @@ -164,8 +165,9 @@ class GrafanaDeleteException(Exception): pass -def grafana_organization_id_by_name(module, org_name): - r, info = fetch_url(module, '%s/orgs/name/%s' % (grafana_url, org_name), headers=headers, method='GET') +def grafana_organization_id_by_name(module, grafana_url, org_name, headers): + org_name = urllib.parse.quote(org_name) + r, info = fetch_url(module, '%s/api/orgs/name/%s' % (grafana_url, org_name), headers=headers, method='GET') if info['status'] != 200: raise GrafanaAPIException("Unable to retrieve organization: %s" % info) @@ -186,7 +188,7 @@ def grafana_headers(module, data): module.params['force_basic_auth'] = True if module.params['org_name']: org_name = module.params['org_name'] - organization = grafana_organization_id_by_name(module, org_name) + organization = grafana_organization_id_by_name(module, data['url'], org_name, headers) data['org_id'] = organization['id'] grafana_switch_organisation(module, data['url'], data['org_id'], headers) From c61e6995d883bb494efc0181a6ad415bb4bb66f4 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 29 Nov 2023 18:14:23 +0100 Subject: [PATCH 15/40] docs: changelog fragment --- changelogs/fragments/331-dashboard-by-org-name.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 changelogs/fragments/331-dashboard-by-org-name.yml diff --git a/changelogs/fragments/331-dashboard-by-org-name.yml b/changelogs/fragments/331-dashboard-by-org-name.yml new file mode 100644 index 00000000..576c8c14 --- /dev/null +++ b/changelogs/fragments/331-dashboard-by-org-name.yml @@ -0,0 +1,8 @@ +--- + +minor_changes: + - Add parameter `org_name` to `grafana_dashboard` + +trivial: + - Add tests for new `grafana_dashboard`-parameter `org_name` + - Refactor tests for `grafana_dashboard` From a87414e21620ada49e4c4f856721f6e43ee2b843 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 11:12:41 +0100 Subject: [PATCH 16/40] fix: get org_id by list of users orgs --- plugins/modules/grafana_dashboard.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index ec8b19d9..98316e16 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -18,15 +18,15 @@ options: org_id: description: - - The Grafana Organisation ID where the dashboard will be imported / exported / deleted. - - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organisation. + - The Grafana organization ID where the dashboard will be imported / exported / deleted. + - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organization. - Mutually exclusive with `org_name`. default: 1 type: int org_name: description: - - The Grafana Organisation name where the dashboard will be imported / exported / deleted. - - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organisation. + - The Grafana organization name where the dashboard will be imported / exported / deleted. + - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organization. - Mutually exclusive with `org_id`. type: str folder: @@ -166,15 +166,18 @@ class GrafanaDeleteException(Exception): def grafana_organization_id_by_name(module, grafana_url, org_name, headers): - org_name = urllib.parse.quote(org_name) - r, info = fetch_url(module, '%s/api/orgs/name/%s' % (grafana_url, org_name), headers=headers, method='GET') + r, info = fetch_url(module, '%s/api/user/orgs' % grafana_url, headers=headers, method='GET') if info['status'] != 200: raise GrafanaAPIException("Unable to retrieve organization: %s" % info) + organizations = json.loads(to_text(r.read())) + for org in organizations: + if org['name'] == org_name: + return org['orgId'] - return json.loads(to_text(r.read())) + raise GrafanaAPIException("Current user isn't member of organization: %s" % org_name) -def grafana_switch_organisation(module, grafana_url, org_id, headers): +def grafana_switch_organization(module, grafana_url, org_id, headers): r, info = fetch_url(module, '%s/api/user/using/%s' % (grafana_url, org_id), headers=headers, method='POST') if info['status'] != 200: raise GrafanaAPIException('Unable to switch to organization %s : %s' % (org_id, info)) @@ -188,9 +191,8 @@ def grafana_headers(module, data): module.params['force_basic_auth'] = True if module.params['org_name']: org_name = module.params['org_name'] - organization = grafana_organization_id_by_name(module, data['url'], org_name, headers) - data['org_id'] = organization['id'] - grafana_switch_organisation(module, data['url'], data['org_id'], headers) + data['org_id'] = grafana_organization_id_by_name(module, data['url'], org_name, headers) + grafana_switch_organization(module, data['url'], data['org_id'], headers) return headers From ae66576b0025af87bb873ea3c3e8a7e6ea663174 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 11:15:46 +0100 Subject: [PATCH 17/40] chore: excpetion msg user orgs --- plugins/modules/grafana_dashboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 98316e16..373b4756 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -168,7 +168,7 @@ class GrafanaDeleteException(Exception): def grafana_organization_id_by_name(module, grafana_url, org_name, headers): r, info = fetch_url(module, '%s/api/user/orgs' % grafana_url, headers=headers, method='GET') if info['status'] != 200: - raise GrafanaAPIException("Unable to retrieve organization: %s" % info) + raise GrafanaAPIException("Unable to retrieve users organizations: %s" % info) organizations = json.loads(to_text(r.read())) for org in organizations: if org['name'] == org_name: From 445b2c6b942618f1992e10ea7e08ec30eea35f91 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 11:21:05 +0100 Subject: [PATCH 18/40] chore: removed unused urllib.parse --- plugins/modules/grafana_dashboard.py | 1 - 1 file changed, 1 deletion(-) diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 373b4756..6e8c8ba6 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -138,7 +138,6 @@ ''' import json -import urllib.parse from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url from ansible.module_utils.six.moves.urllib.parse import urlencode From bd2c90c875210bebb3835580d1e77f8dcd501db5 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Tue, 2 Jan 2024 10:29:18 +0100 Subject: [PATCH 19/40] test: readded assert result msg --- .../targets/grafana_dashboard/tasks/dashboard-by-org-name.yml | 2 ++ .../grafana_dashboard/tasks/dashboard-from-file-export.yml | 2 ++ .../targets/grafana_dashboard/tasks/dashboard-from-id.yml | 2 ++ .../targets/grafana_dashboard/tasks/dashboard-from-url.yml | 2 ++ .../targets/grafana_dashboard/tasks/delete-dashboard.yml | 1 + 5 files changed, 9 insertions(+) diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml index b8b9d3fe..538e7c26 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml @@ -17,6 +17,7 @@ that: - "result.failed == false" - "result.changed == true" + - "result.msg == 'Dashboard test created'" - name: Check import grafana dashboard from file idempotency community.grafana.grafana_dashboard: @@ -32,5 +33,6 @@ that: - "result.failed == false" - "result.changed == false" + - "result.msg == 'Dashboard test unchanged.'" - ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml index d883cedd..2e54d110 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml @@ -18,6 +18,7 @@ that: - "result.failed == false" - "result.changed == true" + - "result.msg == 'Dashboard test created'" - name: Check import grafana dashboard from file idempotency community.grafana.grafana_dashboard: @@ -33,6 +34,7 @@ that: - "result.failed == false" - "result.changed == false" + - "result.msg == 'Dashboard test unchanged.'" - ansible.builtin.include_tasks: dashboard-export.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml index 1c2336b9..d2d248de 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml @@ -14,6 +14,7 @@ that: - "result.failed == false" - "result.changed == true" + - "result.msg == 'Dashboard Zabbix Host Status created'" - name: Check import grafana dashboard from id idempotency community.grafana.grafana_dashboard: @@ -30,5 +31,6 @@ that: - "result.failed == false" - "result.changed == false" + - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" - ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml index 34336b96..13c6555c 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml @@ -13,6 +13,7 @@ that: - "result.failed == false" - "result.changed == true" + - "result.msg == 'Dashboard Zabbix Host Status created'" - name: Check import grafana dashboard from url idempotency community.grafana.grafana_dashboard: @@ -28,5 +29,6 @@ that: - "result.failed == false" - "result.changed == false" + - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" - ansible.builtin.include_tasks: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml index a0ccb487..fc1e0f07 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml @@ -11,3 +11,4 @@ that: - "result.failed == false" - "result.changed == true" + - "result.msg == 'Dashboard {{ result.uid }} deleted'" From 409e2614a83e06c1dedc222b9781eeb1c59d4895 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Tue, 2 Jan 2024 10:39:37 +0100 Subject: [PATCH 20/40] test: unsafe conditional --- .../targets/grafana_dashboard/tasks/delete-dashboard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml index fc1e0f07..c9f04898 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml @@ -11,4 +11,4 @@ that: - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard {{ result.uid }} deleted'" + - "result.msg == 'Dashboard ' ~ result.uid ~ ' deleted'" From 245b82ff2b023fb88c5b36771a91a373b58ed095 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Tue, 2 Jan 2024 13:37:38 +0100 Subject: [PATCH 21/40] test: dashboard export result msg --- .../targets/grafana_dashboard/tasks/dashboard-export.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml index e497d507..3d4c000a 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml @@ -13,6 +13,7 @@ that: - "result.failed == false" - "result.changed == true" + - "result.msg == 'Dashboard ' ~ dashboard_uid ~ ' exported to /tmp/dashboard.json'" - name: Load /tmp/dashboard_export.json or fail if missing ansible.builtin.set_fact: From 943b0fa8c8fb1030c2cb6236b56350e7289ef83c Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 3 Jan 2024 09:28:52 +0100 Subject: [PATCH 22/40] test: fix dashboard uid check --- .../targets/grafana_dashboard/tasks/dashboard-export.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml index 3d4c000a..b8470739 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml @@ -13,7 +13,7 @@ that: - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard ' ~ dashboard_uid ~ ' exported to /tmp/dashboard.json'" + - "result.msg == 'Dashboard ' ~ result.uid ~ ' exported to /tmp/dashboard.json'" - name: Load /tmp/dashboard_export.json or fail if missing ansible.builtin.set_fact: From c4da526680b2472349c0cd01e9b4f45f5ad71520 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Wed, 3 Jan 2024 11:06:49 +0100 Subject: [PATCH 23/40] test: fix dashboard export path check --- .../targets/grafana_dashboard/tasks/dashboard-export.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml index b8470739..7a2354ea 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml @@ -13,7 +13,7 @@ that: - "result.failed == false" - "result.changed == true" - - "result.msg == 'Dashboard ' ~ result.uid ~ ' exported to /tmp/dashboard.json'" + - "result.msg == 'Dashboard ' ~ result.uid ~ ' exported to /tmp/dashboard_export.json'" - name: Load /tmp/dashboard_export.json or fail if missing ansible.builtin.set_fact: From 3e46a9f61f30207628fe3e137c8307add65adcac Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Mon, 13 Nov 2023 16:22:33 +0100 Subject: [PATCH 24/40] ignore pycache dir --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 9f11b755..2483976d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ .idea/ +__pycache__/ From 60e0764e28cb2b46f7cb03e5f9c08f6b2ff92764 Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Mon, 13 Nov 2023 16:50:46 +0100 Subject: [PATCH 25/40] add changelog fragment --- changelogs/fragments/324_formatting.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 changelogs/fragments/324_formatting.yml diff --git a/changelogs/fragments/324_formatting.yml b/changelogs/fragments/324_formatting.yml new file mode 100644 index 00000000..db7b9609 --- /dev/null +++ b/changelogs/fragments/324_formatting.yml @@ -0,0 +1,2 @@ +trivial: + - Format with black, remove unused variables From db35d140b60a9f667835b4b4c20a19f596f416a9 Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Thu, 4 Jan 2024 09:20:35 +0100 Subject: [PATCH 26/40] formatting with black --- hacking/find_grafana_versions.py | 7 +- plugins/callback/grafana_annotations.py | 115 +-- plugins/doc_fragments/api_key.py | 6 +- plugins/doc_fragments/basic_auth.py | 6 +- plugins/lookup/grafana_dashboard.py | 105 +-- plugins/module_utils/base.py | 24 +- plugins/modules/grafana_dashboard.py | 456 +++++++----- plugins/modules/grafana_datasource.py | 538 ++++++++------ plugins/modules/grafana_folder.py | 66 +- .../modules/grafana_notification_channel.py | 654 ++++++++++-------- plugins/modules/grafana_organization.py | 70 +- plugins/modules/grafana_organization_user.py | 141 ++-- plugins/modules/grafana_plugin.py | 201 +++--- plugins/modules/grafana_team.py | 84 ++- plugins/modules/grafana_user.py | 87 ++- tests/requirements.yml | 3 + .../test_grafana_datasource.py | 281 ++++---- .../grafana_plugin/test_grafana_plugin.py | 35 +- .../grafana/grafana_team/test_grafana_team.py | 534 +++++++++----- .../grafana/grafana_user/test_grafana_user.py | 235 ++++--- 20 files changed, 2114 insertions(+), 1534 deletions(-) create mode 100644 tests/requirements.yml diff --git a/hacking/find_grafana_versions.py b/hacking/find_grafana_versions.py index 06625a2d..b31fc530 100644 --- a/hacking/find_grafana_versions.py +++ b/hacking/find_grafana_versions.py @@ -7,11 +7,14 @@ def get_by_major(version): if version.startswith("v"): version = version[1:] - return (version[0], version, int(version.replace('.', ''))) + return (version[0], version, int(version.replace(".", ""))) def get_grafana_releases(): - r = requests.get('https://api.github.com/repos/grafana/grafana/releases?per_page=50', headers={"Accept": "application/vnd.github.v3+json"}) + r = requests.get( + "https://api.github.com/repos/grafana/grafana/releases?per_page=50", + headers={"Accept": "application/vnd.github.v3+json"}, + ) if r.status_code != 200: raise Exception("Failed to get releases from GitHub") return r.json() diff --git a/plugins/callback/grafana_annotations.py b/plugins/callback/grafana_annotations.py index 92b837c1..c488505c 100644 --- a/plugins/callback/grafana_annotations.py +++ b/plugins/callback/grafana_annotations.py @@ -14,10 +14,11 @@ # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ name: grafana_annotations type: notification short_description: send ansible events as annotations on charts to grafana over http api. @@ -104,7 +105,7 @@ default: [] type: list elements: integer -''' +""" import json import socket @@ -148,7 +149,7 @@ def to_millis(dt): - return int(dt.strftime('%s')) * 1000 + return int(dt.strftime("%s")) * 1000 class CallbackModule(CallbackBase): @@ -161,15 +162,15 @@ class CallbackModule(CallbackBase): """ CALLBACK_VERSION = 2.0 - CALLBACK_TYPE = 'aggregate' - CALLBACK_NAME = 'community.grafana.grafana_annotations' + CALLBACK_TYPE = "aggregate" + CALLBACK_NAME = "community.grafana.grafana_annotations" CALLBACK_NEEDS_WHITELIST = True def __init__(self, display=None): super(CallbackModule, self).__init__(display=display) - self.headers = {'Content-Type': 'application/json'} + self.headers = {"Content-Type": "application/json"} self.force_basic_auth = False self.hostname = socket.gethostname() self.username = getpass.getuser() @@ -178,37 +179,42 @@ def __init__(self, display=None): def set_options(self, task_keys=None, var_options=None, direct=None): - super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct) + super(CallbackModule, self).set_options( + task_keys=task_keys, var_options=var_options, direct=direct + ) - self.grafana_api_key = self.get_option('grafana_api_key') - self.grafana_url = self.get_option('grafana_url') - self.validate_grafana_certs = self.get_option('validate_certs') - self.http_agent = self.get_option('http_agent') - self.grafana_user = self.get_option('grafana_user') - self.grafana_password = self.get_option('grafana_password') - self.dashboard_id = self.get_option('grafana_dashboard_id') - self.panel_ids = self.get_option('grafana_panel_ids') + self.grafana_api_key = self.get_option("grafana_api_key") + self.grafana_url = self.get_option("grafana_url") + self.validate_grafana_certs = self.get_option("validate_certs") + self.http_agent = self.get_option("http_agent") + self.grafana_user = self.get_option("grafana_user") + self.grafana_password = self.get_option("grafana_password") + self.dashboard_id = self.get_option("grafana_dashboard_id") + self.panel_ids = self.get_option("grafana_panel_ids") if self.grafana_api_key: - self.headers['Authorization'] = "Bearer %s" % self.grafana_api_key + self.headers["Authorization"] = "Bearer %s" % self.grafana_api_key else: self.force_basic_auth = True if self.grafana_url is None: self.disabled = True - self._display.warning('Grafana URL was not provided. The ' - 'Grafana URL can be provided using ' - 'the `GRAFANA_URL` environment variable.') - self._display.debug('Grafana URL: %s' % self.grafana_url) + self._display.warning( + "Grafana URL was not provided. The " + "Grafana URL can be provided using " + "the `GRAFANA_URL` environment variable." + ) + self._display.debug("Grafana URL: %s" % self.grafana_url) def v2_playbook_on_start(self, playbook): self.playbook = playbook._file_name - text = PLAYBOOK_START_TXT.format(playbook=self.playbook, hostname=self.hostname, - username=self.username) + text = PLAYBOOK_START_TXT.format( + playbook=self.playbook, hostname=self.hostname, username=self.username + ) data = { - 'time': to_millis(self.start_time), - 'text': text, - 'tags': ['ansible', 'ansible_event_start', self.playbook, self.hostname] + "time": to_millis(self.start_time), + "text": text, + "tags": ["ansible", "ansible_event_start", self.playbook, self.hostname], } self._send_annotation(data) @@ -223,30 +229,39 @@ def v2_playbook_on_stats(self, stats): if self.errors == 0: status = "OK" - text = PLAYBOOK_STATS_TXT.format(playbook=self.playbook, hostname=self.hostname, - duration=duration.total_seconds(), - status=status, username=self.username, - summary=json.dumps(summarize_stat)) + text = PLAYBOOK_STATS_TXT.format( + playbook=self.playbook, + hostname=self.hostname, + duration=duration.total_seconds(), + status=status, + username=self.username, + summary=json.dumps(summarize_stat), + ) data = { - 'time': to_millis(self.start_time), - 'timeEnd': to_millis(end_time), - 'isRegion': True, - 'text': text, - 'tags': ['ansible', 'ansible_report', self.playbook, self.hostname] + "time": to_millis(self.start_time), + "timeEnd": to_millis(end_time), + "isRegion": True, + "text": text, + "tags": ["ansible", "ansible_report", self.playbook, self.hostname], } self._send_annotations(data) def v2_runner_on_failed(self, result, ignore_errors=False, **kwargs): - text = PLAYBOOK_ERROR_TXT.format(playbook=self.playbook, hostname=self.hostname, - username=self.username, task=result._task, - host=result._host.name, result=self._dump_results(result._result)) + text = PLAYBOOK_ERROR_TXT.format( + playbook=self.playbook, + hostname=self.hostname, + username=self.username, + task=result._task, + host=result._host.name, + result=self._dump_results(result._result), + ) if ignore_errors: return data = { - 'time': to_millis(datetime.now()), - 'text': text, - 'tags': ['ansible', 'ansible_event_failure', self.playbook, self.hostname] + "time": to_millis(datetime.now()), + "text": text, + "tags": ["ansible", "ansible_event_failure", self.playbook, self.hostname], } self.errors += 1 self._send_annotations(data) @@ -263,10 +278,16 @@ def _send_annotations(self, data): def _send_annotation(self, annotation): try: - open_url(self.grafana_url, data=json.dumps(annotation), headers=self.headers, - method="POST", - validate_certs=self.validate_grafana_certs, - url_username=self.grafana_user, url_password=self.grafana_password, - http_agent=self.http_agent, force_basic_auth=self.force_basic_auth) + open_url( + self.grafana_url, + data=json.dumps(annotation), + headers=self.headers, + method="POST", + validate_certs=self.validate_grafana_certs, + url_username=self.grafana_user, + url_password=self.grafana_password, + http_agent=self.http_agent, + force_basic_auth=self.force_basic_auth, + ) except Exception as e: - self._display.error(u'Could not submit message to Grafana: %s' % to_text(e)) + self._display.error("Could not submit message to Grafana: %s" % to_text(e)) diff --git a/plugins/doc_fragments/api_key.py b/plugins/doc_fragments/api_key.py index ffea714e..aa2e30c2 100644 --- a/plugins/doc_fragments/api_key.py +++ b/plugins/doc_fragments/api_key.py @@ -2,17 +2,17 @@ # Copyright: (c) 2019, Rémi REY (@rrey) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function __metaclass__ = type class ModuleDocFragment(object): - DOCUMENTATION = r'''options: + DOCUMENTATION = r"""options: grafana_api_key: description: - The Grafana API key. - If set, C(url_username) and C(url_password) will be ignored. type: str - ''' + """ diff --git a/plugins/doc_fragments/basic_auth.py b/plugins/doc_fragments/basic_auth.py index c874457d..6efe48c4 100644 --- a/plugins/doc_fragments/basic_auth.py +++ b/plugins/doc_fragments/basic_auth.py @@ -2,14 +2,14 @@ # Copyright: (c) 2019, Rémi REY (@rrey) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function __metaclass__ = type class ModuleDocFragment(object): - DOCUMENTATION = r'''options: + DOCUMENTATION = r"""options: url: description: - The Grafana URL. @@ -49,4 +49,4 @@ class ModuleDocFragment(object): - This should only set to C(false) used on personally controlled sites using self-signed certificates. type: bool default: true - ''' + """ diff --git a/plugins/lookup/grafana_dashboard.py b/plugins/lookup/grafana_dashboard.py index ff288a1f..7105ce0a 100644 --- a/plugins/lookup/grafana_dashboard.py +++ b/plugins/lookup/grafana_dashboard.py @@ -1,9 +1,10 @@ # (c) 2018 Ansible Project # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ name: grafana_dashboard author: Thierry Salle (@seuf) short_description: list or search grafana dashboards @@ -40,7 +41,7 @@ description: optional filter for dashboard search. env: - name: GRAFANA_DASHBOARD_SEARCH -''' +""" EXAMPLES = """ - name: get project foo grafana dashboards @@ -64,30 +65,30 @@ display = Display() -ANSIBLE_GRAFANA_URL = 'http://127.0.0.1:3000' +ANSIBLE_GRAFANA_URL = "http://127.0.0.1:3000" ANSIBLE_GRAFANA_API_KEY = None -ANSIBLE_GRAFANA_USER = 'admin' -ANSIBLE_GRAFANA_PASSWORD = 'admin' +ANSIBLE_GRAFANA_USER = "admin" +ANSIBLE_GRAFANA_PASSWORD = "admin" ANSIBLE_GRAFANA_ORG_ID = 1 ANSIBLE_GRAFANA_DASHBOARD_SEARCH = None -if os.getenv('GRAFANA_URL') is not None: - ANSIBLE_GRAFANA_URL = os.environ['GRAFANA_URL'] +if os.getenv("GRAFANA_URL") is not None: + ANSIBLE_GRAFANA_URL = os.environ["GRAFANA_URL"] -if os.getenv('GRAFANA_API_KEY') is not None: - ANSIBLE_GRAFANA_API_KEY = os.environ['GRAFANA_API_KEY'] +if os.getenv("GRAFANA_API_KEY") is not None: + ANSIBLE_GRAFANA_API_KEY = os.environ["GRAFANA_API_KEY"] -if os.getenv('GRAFANA_USER') is not None: - ANSIBLE_GRAFANA_USER = os.environ['GRAFANA_USER'] +if os.getenv("GRAFANA_USER") is not None: + ANSIBLE_GRAFANA_USER = os.environ["GRAFANA_USER"] -if os.getenv('GRAFANA_PASSWORD') is not None: - ANSIBLE_GRAFANA_PASSWORD = os.environ['GRAFANA_PASSWORD'] +if os.getenv("GRAFANA_PASSWORD") is not None: + ANSIBLE_GRAFANA_PASSWORD = os.environ["GRAFANA_PASSWORD"] -if os.getenv('GRAFANA_ORG_ID') is not None: - ANSIBLE_GRAFANA_ORG_ID = os.environ['GRAFANA_ORG_ID'] +if os.getenv("GRAFANA_ORG_ID") is not None: + ANSIBLE_GRAFANA_ORG_ID = os.environ["GRAFANA_ORG_ID"] -if os.getenv('GRAFANA_DASHBOARD_SEARCH') is not None: - ANSIBLE_GRAFANA_DASHBOARD_SEARCH = os.environ['GRAFANA_DASHBOARD_SEARCH'] +if os.getenv("GRAFANA_DASHBOARD_SEARCH") is not None: + ANSIBLE_GRAFANA_DASHBOARD_SEARCH = os.environ["GRAFANA_DASHBOARD_SEARCH"] class GrafanaAPIException(Exception): @@ -96,35 +97,47 @@ class GrafanaAPIException(Exception): class GrafanaAPI: def __init__(self, **kwargs): - self.grafana_url = kwargs.get('grafana_url', ANSIBLE_GRAFANA_URL) - self.grafana_api_key = kwargs.get('grafana_api_key', ANSIBLE_GRAFANA_API_KEY) - self.grafana_user = kwargs.get('grafana_user', ANSIBLE_GRAFANA_USER) - self.grafana_password = kwargs.get('grafana_password', ANSIBLE_GRAFANA_PASSWORD) - self.grafana_org_id = kwargs.get('grafana_org_id', ANSIBLE_GRAFANA_ORG_ID) - self.search = kwargs.get('search', ANSIBLE_GRAFANA_DASHBOARD_SEARCH) + self.grafana_url = kwargs.get("grafana_url", ANSIBLE_GRAFANA_URL) + self.grafana_api_key = kwargs.get("grafana_api_key", ANSIBLE_GRAFANA_API_KEY) + self.grafana_user = kwargs.get("grafana_user", ANSIBLE_GRAFANA_USER) + self.grafana_password = kwargs.get("grafana_password", ANSIBLE_GRAFANA_PASSWORD) + self.grafana_org_id = kwargs.get("grafana_org_id", ANSIBLE_GRAFANA_ORG_ID) + self.search = kwargs.get("search", ANSIBLE_GRAFANA_DASHBOARD_SEARCH) def grafana_switch_organisation(self, headers): try: - r = open_url('%s/api/user/using/%s' % (self.grafana_url, self.grafana_org_id), headers=headers, method='POST') + r = open_url( + "%s/api/user/using/%s" % (self.grafana_url, self.grafana_org_id), + headers=headers, + method="POST", + ) except HTTPError as e: - raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, to_native(e))) + raise GrafanaAPIException( + "Unable to switch to organization %s : %s" + % (self.grafana_org_id, to_native(e)) + ) if r.getcode() != 200: - raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(r.getcode()))) + raise GrafanaAPIException( + "Unable to switch to organization %s : %s" + % (self.grafana_org_id, str(r.getcode())) + ) def grafana_headers(self): - headers = {'content-type': 'application/json; charset=utf8'} + 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', + collection_name="community.grafana", ) - api_key += '==' - headers['Authorization'] = "Bearer %s" % api_key + api_key += "==" + headers["Authorization"] = "Bearer %s" % api_key else: - headers['Authorization'] = basic_auth_header(self.grafana_user, self.grafana_password) + headers["Authorization"] = basic_auth_header( + self.grafana_user, self.grafana_password + ) self.grafana_switch_organisation(headers) return headers @@ -136,35 +149,45 @@ def grafana_list_dashboards(self): dashboard_list = [] try: if self.search: - r = open_url('%s/api/search?query=%s' % (self.grafana_url, self.search), headers=headers, method='GET') + r = open_url( + "%s/api/search?query=%s" % (self.grafana_url, self.search), + headers=headers, + method="GET", + ) else: - r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET') + r = open_url( + "%s/api/search/" % self.grafana_url, headers=headers, method="GET" + ) except HTTPError as e: - raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e)) + raise GrafanaAPIException("Unable to search dashboards : %s" % to_native(e)) if r.getcode() == 200: try: dashboard_list = json.loads(r.read()) except Exception as e: - raise GrafanaAPIException('Unable to parse json list %s' % to_native(e)) + raise GrafanaAPIException("Unable to parse json list %s" % to_native(e)) else: - raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode())) + raise GrafanaAPIException( + "Unable to list grafana dashboards : %s" % str(r.getcode()) + ) return dashboard_list class LookupModule(LookupBase): - def run(self, terms, variables=None, **kwargs): - grafana_args = terms[0].split(' ') + grafana_args = terms[0].split(" ") grafana_dict = {} ret = [] for param in grafana_args: try: - key, value = param.split('=', 1) + key, value = param.split("=", 1) except ValueError: - raise AnsibleError("grafana_dashboard lookup plugin needs key=value pairs, but received %s" % terms) + raise AnsibleError( + "grafana_dashboard lookup plugin needs key=value pairs, but received %s" + % terms + ) grafana_dict[key] = value grafana = GrafanaAPI(**grafana_dict) diff --git a/plugins/module_utils/base.py b/plugins/module_utils/base.py index 3a0174bb..7d51601d 100644 --- a/plugins/module_utils/base.py +++ b/plugins/module_utils/base.py @@ -16,7 +16,7 @@ # # Copyright: (c) 2019, Rémi REY (@rrey) -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function from ansible.module_utils.urls import url_argument_spec __metaclass__ = type @@ -29,26 +29,26 @@ def clean_url(url): def grafana_argument_spec(): argument_spec = url_argument_spec() - del argument_spec['force'] - del argument_spec['force_basic_auth'] - del argument_spec['http_agent'] + del argument_spec["force"] + del argument_spec["force_basic_auth"] + del argument_spec["http_agent"] # Avoid sanity error with devel if "use_gssapi" in argument_spec: - del argument_spec['use_gssapi'] + del argument_spec["use_gssapi"] argument_spec.update( - state=dict(choices=['present', 'absent'], default='present'), - url=dict(aliases=['grafana_url'], type='str', required=True), - grafana_api_key=dict(type='str', no_log=True), - url_username=dict(aliases=['grafana_user'], default='admin'), - url_password=dict(aliases=['grafana_password'], default='admin', no_log=True), + state=dict(choices=["present", "absent"], default="present"), + url=dict(aliases=["grafana_url"], type="str", required=True), + grafana_api_key=dict(type="str", no_log=True), + url_username=dict(aliases=["grafana_user"], default="admin"), + url_password=dict(aliases=["grafana_password"], default="admin", no_log=True), ) return argument_spec def grafana_required_together(): - return [['url_username', 'url_password']] + return [["url_username", "url_password"]] def grafana_mutually_exclusive(): - return [['url_username', 'grafana_api_key']] + return [["url_username", "grafana_api_key"]] diff --git a/plugins/modules/grafana_dashboard.py b/plugins/modules/grafana_dashboard.py index 6e8c8ba6..8ae8eb4f 100644 --- a/plugins/modules/grafana_dashboard.py +++ b/plugins/modules/grafana_dashboard.py @@ -6,7 +6,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_dashboard author: @@ -87,9 +87,9 @@ extends_documentation_fragment: - community.grafana.basic_auth - community.grafana.api_key -''' +""" -EXAMPLES = ''' +EXAMPLES = """ - hosts: localhost connection: local tasks: @@ -126,16 +126,16 @@ state: export uid: "000000653" path: "/path/to/dashboards/000000653.json" -''' +""" -RETURN = ''' +RETURN = """ --- uid: description: uid or slug of the created / deleted / exported dashboard. returned: success type: str sample: 000000063 -''' +""" import json from ansible.module_utils.basic import AnsibleModule @@ -143,7 +143,10 @@ from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils._text import to_native from ansible.module_utils._text import to_text -from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, clean_url +from ansible_collections.community.grafana.plugins.module_utils.base import ( + grafana_argument_spec, + clean_url, +) __metaclass__ = type @@ -165,70 +168,90 @@ class GrafanaDeleteException(Exception): def grafana_organization_id_by_name(module, grafana_url, org_name, headers): - r, info = fetch_url(module, '%s/api/user/orgs' % grafana_url, headers=headers, method='GET') - if info['status'] != 200: + r, info = fetch_url( + module, "%s/api/user/orgs" % grafana_url, headers=headers, method="GET" + ) + if info["status"] != 200: raise GrafanaAPIException("Unable to retrieve users organizations: %s" % info) organizations = json.loads(to_text(r.read())) for org in organizations: - if org['name'] == org_name: - return org['orgId'] + if org["name"] == org_name: + return org["orgId"] - raise GrafanaAPIException("Current user isn't member of organization: %s" % org_name) + raise GrafanaAPIException( + "Current user isn't member of organization: %s" % org_name + ) def grafana_switch_organization(module, grafana_url, org_id, headers): - r, info = fetch_url(module, '%s/api/user/using/%s' % (grafana_url, org_id), headers=headers, method='POST') - if info['status'] != 200: - raise GrafanaAPIException('Unable to switch to organization %s : %s' % (org_id, info)) + r, info = fetch_url( + module, + "%s/api/user/using/%s" % (grafana_url, org_id), + headers=headers, + method="POST", + ) + if info["status"] != 200: + raise GrafanaAPIException( + "Unable to switch to organization %s : %s" % (org_id, info) + ) def grafana_headers(module, data): - headers = {'content-type': 'application/json; charset=utf8'} - if 'grafana_api_key' in data and data['grafana_api_key']: - headers['Authorization'] = "Bearer %s" % data['grafana_api_key'] + headers = {"content-type": "application/json; charset=utf8"} + if "grafana_api_key" in data and data["grafana_api_key"]: + headers["Authorization"] = "Bearer %s" % data["grafana_api_key"] else: - module.params['force_basic_auth'] = True - if module.params['org_name']: - org_name = module.params['org_name'] - data['org_id'] = grafana_organization_id_by_name(module, data['url'], org_name, headers) - grafana_switch_organization(module, data['url'], data['org_id'], headers) + module.params["force_basic_auth"] = True + if module.params["org_name"]: + org_name = module.params["org_name"] + data["org_id"] = grafana_organization_id_by_name( + module, data["url"], org_name, headers + ) + grafana_switch_organization(module, data["url"], data["org_id"], headers) return headers def get_grafana_version(module, grafana_url, headers): grafana_version = None - r, info = fetch_url(module, '%s/api/frontend/settings' % grafana_url, headers=headers, method='GET') - if info['status'] == 200: + r, info = fetch_url( + module, "%s/api/frontend/settings" % grafana_url, headers=headers, method="GET" + ) + if info["status"] == 200: try: settings = json.loads(to_text(r.read())) - grafana_version = settings['buildInfo']['version'].split('.')[0] + grafana_version = settings["buildInfo"]["version"].split(".")[0] except UnicodeError as e: - raise GrafanaAPIException('Unable to decode version string to Unicode') + raise GrafanaAPIException("Unable to decode version string to Unicode") except Exception as e: raise GrafanaAPIException(e) else: - raise GrafanaAPIException('Unable to get grafana version: %s' % info) + raise GrafanaAPIException("Unable to get grafana version: %s" % info) return int(grafana_version) def grafana_folder_exists(module, grafana_url, folder_name, headers): # the 'General' folder is a special case, it's ID is always '0' - if folder_name == 'General': + if folder_name == "General": return True, 0 try: - r, info = fetch_url(module, '%s/api/folders' % grafana_url, headers=headers, method='GET') + r, info = fetch_url( + module, "%s/api/folders" % grafana_url, headers=headers, method="GET" + ) - if info['status'] != 200: - raise GrafanaAPIException("Unable to query Grafana API for folders (name: %s): %d" % (folder_name, info['status'])) + if info["status"] != 200: + raise GrafanaAPIException( + "Unable to query Grafana API for folders (name: %s): %d" + % (folder_name, info["status"]) + ) folders = json.loads(r.read()) for folder in folders: - if folder['title'] == folder_name: - return True, folder['id'] + if folder["title"] == folder_name: + return True, folder["id"] except Exception as e: raise GrafanaAPIException(e) @@ -241,22 +264,22 @@ def grafana_dashboard_exists(module, grafana_url, uid, headers): grafana_version = get_grafana_version(module, grafana_url, headers) if grafana_version >= 5: - uri = '%s/api/dashboards/uid/%s' % (grafana_url, uid) + uri = "%s/api/dashboards/uid/%s" % (grafana_url, uid) else: - uri = '%s/api/dashboards/db/%s' % (grafana_url, uid) + uri = "%s/api/dashboards/db/%s" % (grafana_url, uid) - r, info = fetch_url(module, uri, headers=headers, method='GET') + r, info = fetch_url(module, uri, headers=headers, method="GET") - if info['status'] == 200: + if info["status"] == 200: dashboard_exists = True try: dashboard = json.loads(r.read()) except Exception as e: raise GrafanaAPIException(e) - elif info['status'] == 404: + elif info["status"] == 404: dashboard_exists = False else: - raise GrafanaAPIException('Unable to get dashboard %s : %s' % (uid, info)) + raise GrafanaAPIException("Unable to get dashboard %s : %s" % (uid, info)) return dashboard_exists, dashboard @@ -264,23 +287,24 @@ def grafana_dashboard_exists(module, grafana_url, uid, headers): def grafana_dashboard_search(module, grafana_url, folder_id, title, headers): # search by title - uri = '%s/api/search?%s' % (grafana_url, urlencode({ - 'folderIds': folder_id, - 'query': title, - 'type': 'dash-db' - })) - r, info = fetch_url(module, uri, headers=headers, method='GET') - - if info['status'] == 200: + uri = "%s/api/search?%s" % ( + grafana_url, + urlencode({"folderIds": folder_id, "query": title, "type": "dash-db"}), + ) + r, info = fetch_url(module, uri, headers=headers, method="GET") + + if info["status"] == 200: try: dashboards = json.loads(r.read()) for d in dashboards: - if d['title'] == title: - return grafana_dashboard_exists(module, grafana_url, d['uid'], headers) + if d["title"] == title: + return grafana_dashboard_exists( + module, grafana_url, d["uid"], headers + ) except Exception as e: raise GrafanaAPIException(e) else: - raise GrafanaAPIException('Unable to search dashboard %s : %s' % (title, info)) + raise GrafanaAPIException("Unable to search dashboard %s : %s" % (title, info)) return False, None @@ -288,26 +312,26 @@ def grafana_dashboard_search(module, grafana_url, folder_id, title, headers): # for comparison, we sometimes need to ignore a few keys def grafana_dashboard_changed(payload, dashboard): # you don't need to set the version, but '0' is incremented to '1' by Grafana's API - if 'version' in payload['dashboard']: - del payload['dashboard']['version'] - if 'version' in dashboard['dashboard']: - del dashboard['dashboard']['version'] + if "version" in payload["dashboard"]: + del payload["dashboard"]["version"] + if "version" in dashboard["dashboard"]: + del dashboard["dashboard"]["version"] # remove meta key if exists for compare - if 'meta' in dashboard: - del dashboard['meta'] - if 'meta' in payload: - del payload['meta'] + if "meta" in dashboard: + del dashboard["meta"] + if "meta" in payload: + del payload["meta"] # if folderId is not provided in dashboard, set default folderId - if 'folderId' not in dashboard: - dashboard['folderId'] = 0 + if "folderId" not in dashboard: + dashboard["folderId"] = 0 # Ignore dashboard ids since real identifier is uuid - if 'id' in dashboard['dashboard']: - del dashboard['dashboard']['id'] - if 'id' in payload['dashboard']: - del payload['dashboard']['id'] + if "id" in dashboard["dashboard"]: + del dashboard["dashboard"]["id"] + if "id" in payload["dashboard"]: + del payload["dashboard"]["id"] if payload == dashboard: return False @@ -318,40 +342,46 @@ def grafana_create_dashboard(module, data): # define data payload for grafana API payload = {} - if data.get('dashboard_id'): - data['path'] = "https://grafana.com/api/dashboards/%s/revisions/%s/download" % (data['dashboard_id'], data['dashboard_revision']) - if data['path'].startswith('http'): - r, info = fetch_url(module, data['path']) - if info['status'] != 200: - raise GrafanaAPIException('Unable to download grafana dashboard from url %s : %s' % (data['path'], info)) + if data.get("dashboard_id"): + data["path"] = "https://grafana.com/api/dashboards/%s/revisions/%s/download" % ( + data["dashboard_id"], + data["dashboard_revision"], + ) + if data["path"].startswith("http"): + r, info = fetch_url(module, data["path"]) + if info["status"] != 200: + raise GrafanaAPIException( + "Unable to download grafana dashboard from url %s : %s" + % (data["path"], info) + ) payload = json.loads(r.read()) else: try: - with open(data['path'], 'r', encoding="utf-8") as json_file: + with open(data["path"], "r", encoding="utf-8") as json_file: payload = json.load(json_file) except Exception as e: raise GrafanaAPIException("Can't load json file %s" % to_native(e)) # Check that the dashboard JSON is nested under the 'dashboard' key - if 'dashboard' not in payload: - payload = {'dashboard': payload} + if "dashboard" not in payload: + payload = {"dashboard": payload} # define http header headers = grafana_headers(module, data) - grafana_version = get_grafana_version(module, data['url'], headers) + grafana_version = get_grafana_version(module, data["url"], headers) if grafana_version < 5: - if data.get('slug'): - uid = data['slug'] - elif 'meta' in payload and 'slug' in payload['meta']: - uid = payload['meta']['slug'] + if data.get("slug"): + uid = data["slug"] + elif "meta" in payload and "slug" in payload["meta"]: + uid = payload["meta"]["slug"] else: - raise GrafanaMalformedJson('No slug found in json. Needed with grafana < 5') + raise GrafanaMalformedJson("No slug found in json. Needed with grafana < 5") else: - if data.get('uid'): - uid = data['uid'] - elif 'uid' in payload['dashboard']: - uid = payload['dashboard']['uid'] + if data.get("uid"): + uid = data["uid"] + elif "uid" in payload["dashboard"]: + uid = payload["dashboard"]["uid"] else: uid = None @@ -360,69 +390,93 @@ def grafana_create_dashboard(module, data): # test if the folder exists folder_exists = False if grafana_version >= 5: - folder_exists, folder_id = grafana_folder_exists(module, data['url'], data['folder'], headers) + folder_exists, folder_id = grafana_folder_exists( + module, data["url"], data["folder"], headers + ) if folder_exists is False: - raise GrafanaAPIException("Dashboard folder '%s' does not exist." % data['folder']) + raise GrafanaAPIException( + "Dashboard folder '%s' does not exist." % data["folder"] + ) - payload['folderId'] = folder_id + payload["folderId"] = folder_id # test if dashboard already exists if uid: dashboard_exists, dashboard = grafana_dashboard_exists( - module, data['url'], uid, headers=headers) + module, data["url"], uid, headers=headers + ) else: dashboard_exists, dashboard = grafana_dashboard_search( - module, data['url'], folder_id, payload['dashboard']['title'], headers=headers) + module, + data["url"], + folder_id, + payload["dashboard"]["title"], + headers=headers, + ) if dashboard_exists is True: if grafana_dashboard_changed(payload, dashboard): # update - if 'overwrite' in data and data['overwrite']: - payload['overwrite'] = True - if 'commit_message' in data and data['commit_message']: - payload['message'] = data['commit_message'] - - r, info = fetch_url(module, '%s/api/dashboards/db' % data['url'], - data=json.dumps(payload), headers=headers, method='POST') - if info['status'] == 200: + if "overwrite" in data and data["overwrite"]: + payload["overwrite"] = True + if "commit_message" in data and data["commit_message"]: + payload["message"] = data["commit_message"] + + r, info = fetch_url( + module, + "%s/api/dashboards/db" % data["url"], + data=json.dumps(payload), + headers=headers, + method="POST", + ) + if info["status"] == 200: if grafana_version >= 5: try: dashboard = json.loads(r.read()) - uid = dashboard['uid'] + uid = dashboard["uid"] except Exception as e: raise GrafanaAPIException(e) - result['uid'] = uid - result['msg'] = "Dashboard %s updated" % payload['dashboard']['title'] - result['changed'] = True + result["uid"] = uid + result["msg"] = "Dashboard %s updated" % payload["dashboard"]["title"] + result["changed"] = True else: - body = json.loads(info['body']) - raise GrafanaAPIException('Unable to update the dashboard %s : %s (HTTP: %d)' % - (uid, body['message'], info['status'])) + body = json.loads(info["body"]) + raise GrafanaAPIException( + "Unable to update the dashboard %s : %s (HTTP: %d)" + % (uid, body["message"], info["status"]) + ) else: # unchanged - result['uid'] = uid - result['msg'] = "Dashboard %s unchanged." % payload['dashboard']['title'] - result['changed'] = False + result["uid"] = uid + result["msg"] = "Dashboard %s unchanged." % payload["dashboard"]["title"] + result["changed"] = False else: # Ensure there is no id in payload - if 'id' in payload['dashboard']: - del payload['dashboard']['id'] - - r, info = fetch_url(module, '%s/api/dashboards/db' % data['url'], - data=json.dumps(payload), headers=headers, method='POST') - if info['status'] == 200: - result['msg'] = "Dashboard %s created" % payload['dashboard']['title'] - result['changed'] = True + if "id" in payload["dashboard"]: + del payload["dashboard"]["id"] + + r, info = fetch_url( + module, + "%s/api/dashboards/db" % data["url"], + data=json.dumps(payload), + headers=headers, + method="POST", + ) + if info["status"] == 200: + result["msg"] = "Dashboard %s created" % payload["dashboard"]["title"] + result["changed"] = True if grafana_version >= 5: try: dashboard = json.loads(r.read()) - uid = dashboard['uid'] + uid = dashboard["uid"] except Exception as e: raise GrafanaAPIException(e) - result['uid'] = uid + result["uid"] = uid else: - raise GrafanaAPIException('Unable to create the new dashboard %s : %s - %s. (headers : %s)' % - (payload['dashboard']['title'], info['status'], info, headers)) + raise GrafanaAPIException( + "Unable to create the new dashboard %s : %s - %s. (headers : %s)" + % (payload["dashboard"]["title"], info["status"], info, headers) + ) return result @@ -432,39 +486,55 @@ def grafana_delete_dashboard(module, data): # define http headers headers = grafana_headers(module, data) - grafana_version = get_grafana_version(module, data['url'], headers) + grafana_version = get_grafana_version(module, data["url"], headers) if grafana_version < 5: - if data.get('slug'): - uid = data['slug'] + if data.get("slug"): + uid = data["slug"] else: - raise GrafanaMalformedJson('No slug parameter. Needed with grafana < 5') + raise GrafanaMalformedJson("No slug parameter. Needed with grafana < 5") else: - if data.get('uid'): - uid = data['uid'] + if data.get("uid"): + uid = data["uid"] else: - raise GrafanaDeleteException('No uid specified %s') + raise GrafanaDeleteException("No uid specified %s") # test if dashboard already exists - dashboard_exists, dashboard = grafana_dashboard_exists(module, data['url'], uid, headers=headers) + dashboard_exists, dashboard = grafana_dashboard_exists( + module, data["url"], uid, headers=headers + ) result = {} if dashboard_exists is True: # delete if grafana_version < 5: - r, info = fetch_url(module, '%s/api/dashboards/db/%s' % (data['url'], uid), headers=headers, method='DELETE') + r, info = fetch_url( + module, + "%s/api/dashboards/db/%s" % (data["url"], uid), + headers=headers, + method="DELETE", + ) else: - r, info = fetch_url(module, '%s/api/dashboards/uid/%s' % (data['url'], uid), headers=headers, method='DELETE') - if info['status'] == 200: - result['msg'] = "Dashboard %s deleted" % uid - result['changed'] = True - result['uid'] = uid + r, info = fetch_url( + module, + "%s/api/dashboards/uid/%s" % (data["url"], uid), + headers=headers, + method="DELETE", + ) + if info["status"] == 200: + result["msg"] = "Dashboard %s deleted" % uid + result["changed"] = True + result["uid"] = uid else: - raise GrafanaAPIException('Unable to update the dashboard %s : %s' % (uid, info)) + raise GrafanaAPIException( + "Unable to update the dashboard %s : %s" % (uid, info) + ) else: # dashboard does not exist, do nothing - result = {'msg': "Dashboard %s does not exist." % uid, - 'changed': False, - 'uid': uid} + result = { + "msg": "Dashboard %s does not exist." % uid, + "changed": False, + "uid": uid, + } return result @@ -474,34 +544,40 @@ def grafana_export_dashboard(module, data): # define http headers headers = grafana_headers(module, data) - grafana_version = get_grafana_version(module, data['url'], headers) + grafana_version = get_grafana_version(module, data["url"], headers) if grafana_version < 5: - if data.get('slug'): - uid = data['slug'] + if data.get("slug"): + uid = data["slug"] else: - raise GrafanaMalformedJson('No slug parameter. Needed with grafana < 5') + raise GrafanaMalformedJson("No slug parameter. Needed with grafana < 5") else: - if data.get('uid'): - uid = data['uid'] + if data.get("uid"): + uid = data["uid"] else: - raise GrafanaExportException('No uid specified') + raise GrafanaExportException("No uid specified") # test if dashboard already exists - dashboard_exists, dashboard = grafana_dashboard_exists(module, data['url'], uid, headers=headers) + dashboard_exists, dashboard = grafana_dashboard_exists( + module, data["url"], uid, headers=headers + ) if dashboard_exists is True: try: - with open(data['path'], 'w', encoding="utf-8") as f: + with open(data["path"], "w", encoding="utf-8") as f: f.write(json.dumps(dashboard, indent=2)) except Exception as e: raise GrafanaExportException("Can't write json file : %s" % to_native(e)) - result = {'msg': "Dashboard %s exported to %s" % (uid, data['path']), - 'uid': uid, - 'changed': True} + result = { + "msg": "Dashboard %s exported to %s" % (uid, data["path"]), + "uid": uid, + "changed": True, + } else: - result = {'msg': "Dashboard %s does not exist." % uid, - 'uid': uid, - 'changed': False} + result = { + "msg": "Dashboard %s does not exist." % uid, + "uid": uid, + "changed": False, + } return result @@ -510,73 +586,75 @@ def main(): # use the predefined argument spec for url argument_spec = grafana_argument_spec() argument_spec.update( - state=dict(choices=['present', 'absent', 'export'], default='present'), - org_id=dict(default=1, type='int'), - org_name=dict(type='str'), - folder=dict(type='str', default='General'), - uid=dict(type='str'), - slug=dict(type='str'), - path=dict(aliases=['dashboard_url'], type='str'), - dashboard_id=dict(type='str'), - dashboard_revision=dict(type='str', default='1'), - overwrite=dict(type='bool', default=False), - commit_message=dict(type='str', aliases=['message'], - deprecated_aliases=[dict(name='message', - version='2.0.0', collection_name="community.grafana")]), + state=dict(choices=["present", "absent", "export"], default="present"), + org_id=dict(default=1, type="int"), + org_name=dict(type="str"), + folder=dict(type="str", default="General"), + uid=dict(type="str"), + slug=dict(type="str"), + path=dict(aliases=["dashboard_url"], type="str"), + dashboard_id=dict(type="str"), + dashboard_revision=dict(type="str", default="1"), + overwrite=dict(type="bool", default=False), + commit_message=dict( + type="str", + aliases=["message"], + deprecated_aliases=[ + dict( + name="message", version="2.0.0", collection_name="community.grafana" + ) + ], + ), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, required_if=[ - ['state', 'export', ['path']], + ["state", "export", ["path"]], + ], + required_together=[["url_username", "url_password", "org_id"]], + mutually_exclusive=[ + ["url_username", "grafana_api_key"], + ["uid", "slug"], + ["path", "dashboard_id"], + ["org_id", "org_name"], ], - required_together=[['url_username', 'url_password', 'org_id']], - mutually_exclusive=[['url_username', 'grafana_api_key'], ['uid', 'slug'], ['path', 'dashboard_id'], ['org_id', 'org_name']], ) module.params["url"] = clean_url(module.params["url"]) - if 'message' in module.params: - module.fail_json(msg="'message' is reserved keyword, please change this parameter to 'commit_message'") + if "message" in module.params: + module.fail_json( + msg="'message' is reserved keyword, please change this parameter to 'commit_message'" + ) try: - if module.params['state'] == 'present': + if module.params["state"] == "present": result = grafana_create_dashboard(module, module.params) - elif module.params['state'] == 'absent': + elif module.params["state"] == "absent": result = grafana_delete_dashboard(module, module.params) else: result = grafana_export_dashboard(module, module.params) except GrafanaAPIException as e: - module.fail_json( - failed=True, - msg="error : %s" % to_native(e) - ) + module.fail_json(failed=True, msg="error : %s" % to_native(e)) return except GrafanaMalformedJson as e: - module.fail_json( - failed=True, - msg="error : %s" % to_native(e) - ) + module.fail_json(failed=True, msg="error : %s" % to_native(e)) return except GrafanaDeleteException as e: module.fail_json( - failed=True, - msg="error : Can't delete dashboard : %s" % to_native(e) + failed=True, msg="error : Can't delete dashboard : %s" % to_native(e) ) return except GrafanaExportException as e: module.fail_json( - failed=True, - msg="error : Can't export dashboard : %s" % to_native(e) + failed=True, msg="error : Can't export dashboard : %s" % to_native(e) ) return - module.exit_json( - failed=False, - **result - ) + module.exit_json(failed=False, **result) return -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index f743303c..468313cb 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -5,9 +5,10 @@ # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ module: grafana_datasource author: - Thierry Sallé (@seuf) @@ -354,9 +355,9 @@ data will not be updated after initial creation! To force the secure data update you have to set I(enforce_secure_data=True). - Hint, with the C(enforce_secure_data) always reporting changed=True, you might just do one Task updating the datasource without any secure data and make a separate playbook/task also changing the secure data. This way it will not break any workflow. -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Create elasticsearch datasource community.grafana.grafana_datasource: @@ -464,9 +465,9 @@ additional_secure_json_data: httpHeaderValue1: "Bearer ihavenogroot" enforce_secure_data: true -''' +""" -RETURN = ''' +RETURN = """ --- datasource: description: datasource created/updated by module @@ -492,7 +493,7 @@ "user": "", "password": "", "withCredentials": false } -''' +""" import json @@ -510,176 +511,186 @@ def compare_datasources(new, current, compareSecureData=True): - if new['uid'] is None: - del current['uid'] - del new['uid'] - del current['typeLogoUrl'] - del current['id'] - if 'version' in current: - del current['version'] - if 'readOnly' in current: - del current['readOnly'] - if current['basicAuth'] is False: - if 'basicAuthUser' in current: - del current['basicAuthUser'] - if 'password' in current: - del current['password'] - if 'basicAuthPassword' in current: - del current['basicAuthPassword'] + if new["uid"] is None: + del current["uid"] + del new["uid"] + del current["typeLogoUrl"] + del current["id"] + if "version" in current: + del current["version"] + if "readOnly" in current: + del current["readOnly"] + if current["basicAuth"] is False: + if "basicAuthUser" in current: + del current["basicAuthUser"] + if "password" in current: + del current["password"] + if "basicAuthPassword" in current: + del current["basicAuthPassword"] # check if secureJsonData should be compared if not compareSecureData: # if we should ignore it just drop alltogether - new.pop('secureJsonData', None) - new.pop('secureJsonFields', None) - current.pop('secureJsonData', None) - current.pop('secureJsonFields', None) + new.pop("secureJsonData", None) + new.pop("secureJsonFields", None) + current.pop("secureJsonData", None) + current.pop("secureJsonFields", None) else: # handle secureJsonData/secureJsonFields, some current facts: # - secureJsonFields is reporting each field set as true # - secureJsonFields once set cant be removed (DS has to be deleted) - if not new.get('secureJsonData'): + if not new.get("secureJsonData"): # secureJsonData is not provided so just remove both for comparision - new.pop('secureJsonData', None) - current.pop('secureJsonFields', None) + new.pop("secureJsonData", None) + current.pop("secureJsonFields", None) else: # we have some secure data so just "rename" secureJsonFields for comparison as it will change anyhow everytime - current['secureJsonData'] = current.pop('secureJsonFields') + current["secureJsonData"] = current.pop("secureJsonFields") return dict(before=current, after=new) def get_datasource_payload(data): payload = { - 'orgId': data['org_id'], - 'name': data['name'], - 'uid': data['uid'], - 'type': data['ds_type'], - 'access': data['access'], - 'url': data['ds_url'], - 'database': data['database'], - 'withCredentials': data['with_credentials'], - 'isDefault': data['is_default'], - 'user': data['user'], - 'jsonData': data['additional_json_data'], - 'secureJsonData': data['additional_secure_json_data'] + "orgId": data["org_id"], + "name": data["name"], + "uid": data["uid"], + "type": data["ds_type"], + "access": data["access"], + "url": data["ds_url"], + "database": data["database"], + "withCredentials": data["with_credentials"], + "isDefault": data["is_default"], + "user": data["user"], + "jsonData": data["additional_json_data"], + "secureJsonData": data["additional_secure_json_data"], } - json_data = payload['jsonData'] - secure_json_data = payload['secureJsonData'] + json_data = payload["jsonData"] + secure_json_data = payload["secureJsonData"] # define password - if data.get('password'): - secure_json_data['password'] = data['password'] + if data.get("password"): + secure_json_data["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'] - secure_json_data['basicAuthPassword'] = data['basic_auth_password'] + 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"] + secure_json_data["basicAuthPassword"] = data["basic_auth_password"] else: - payload['basicAuth'] = False + payload["basicAuth"] = False # define tls auth - if data.get('tls_client_cert') and data.get('tls_client_key'): - json_data['tlsAuth'] = True - if data.get('tls_ca_cert'): - secure_json_data['tlsCACert'] = data['tls_ca_cert'] - secure_json_data['tlsClientCert'] = data['tls_client_cert'] - secure_json_data['tlsClientKey'] = data['tls_client_key'] - json_data['tlsAuthWithCACert'] = True + if data.get("tls_client_cert") and data.get("tls_client_key"): + json_data["tlsAuth"] = True + if data.get("tls_ca_cert"): + secure_json_data["tlsCACert"] = data["tls_ca_cert"] + secure_json_data["tlsClientCert"] = data["tls_client_cert"] + secure_json_data["tlsClientKey"] = data["tls_client_key"] + json_data["tlsAuthWithCACert"] = True else: - secure_json_data['tlsClientCert'] = data['tls_client_cert'] - secure_json_data['tlsClientKey'] = data['tls_client_key'] + secure_json_data["tlsClientCert"] = data["tls_client_cert"] + secure_json_data["tlsClientKey"] = data["tls_client_key"] else: - json_data['tlsAuth'] = False - json_data['tlsAuthWithCACert'] = False - if data.get('tls_ca_cert'): - json_data['tlsAuthWithCACert'] = True - secure_json_data['tlsCACert'] = data['tls_ca_cert'] + json_data["tlsAuth"] = False + json_data["tlsAuthWithCACert"] = False + if data.get("tls_ca_cert"): + json_data["tlsAuthWithCACert"] = True + secure_json_data["tlsCACert"] = data["tls_ca_cert"] - if data.get('tls_skip_verify'): - json_data['tlsSkipVerify'] = True + if data.get("tls_skip_verify"): + json_data["tlsSkipVerify"] = True # datasource type related parameters - if data['ds_type'] == 'elasticsearch': + if data["ds_type"] == "elasticsearch": - json_data['maxConcurrentShardRequests'] = data['max_concurrent_shard_requests'] - json_data['timeField'] = data['time_field'] - if data.get('interval'): - json_data['interval'] = data['interval'] + json_data["maxConcurrentShardRequests"] = data["max_concurrent_shard_requests"] + json_data["timeField"] = data["time_field"] + if data.get("interval"): + json_data["interval"] = data["interval"] # Handle changes in es_version format in Grafana < 8.x which used to # be integers and is now semver format try: - es_version = int(data['es_version']) + es_version = int(data["es_version"]) if es_version < 56: - json_data.pop('maxConcurrentShardRequests') + json_data.pop("maxConcurrentShardRequests") except ValueError: # Retrieve the Semver format expected by API - es_version = ES_VERSION_MAPPING.get(data['es_version']) - json_data['esVersion'] = es_version + es_version = ES_VERSION_MAPPING.get(data["es_version"]) + json_data["esVersion"] = es_version - if data['ds_type'] in ['elasticsearch', 'influxdb', 'prometheus']: - if data.get('time_interval'): - json_data['timeInterval'] = data['time_interval'] + if data["ds_type"] in ["elasticsearch", "influxdb", "prometheus"]: + 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 + 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 - json_data['username'] = data['zabbix_user'] - json_data['password'] = data['zabbix_password'] - - if data['ds_type'] == 'grafana-azure-monitor-datasource': - json_data['tenantId'] = data['azure_tenant'] - json_data['clientId'] = data['azure_client'] - json_data['cloudName'] = data['azure_cloud'] - json_data['clientsecret'] = 'clientsecret' - if data.get('azure_secret'): - secure_json_data['clientSecret'] = data['azure_secret'] - - if data['ds_type'] == 'cloudwatch': - if data.get('aws_credentials_profile'): - payload['database'] = data.get('aws_credentials_profile') - - json_data['authType'] = data['aws_auth_type'] - json_data['defaultRegion'] = data['aws_default_region'] - - if data.get('aws_custom_metrics_namespaces'): - json_data['customMetricsNamespaces'] = data.get('aws_custom_metrics_namespaces') - if data.get('aws_assume_role_arn'): - json_data['assumeRoleArn'] = data.get('aws_assume_role_arn') - if data.get('aws_access_key') and data.get('aws_secret_key'): - secure_json_data['accessKey'] = data.get('aws_access_key') - secure_json_data['secretKey'] = data.get('aws_secret_key') - - payload['jsonData'] = json_data - payload['secureJsonData'] = secure_json_data + 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 + json_data["username"] = data["zabbix_user"] + json_data["password"] = data["zabbix_password"] + + if data["ds_type"] == "grafana-azure-monitor-datasource": + json_data["tenantId"] = data["azure_tenant"] + json_data["clientId"] = data["azure_client"] + json_data["cloudName"] = data["azure_cloud"] + json_data["clientsecret"] = "clientsecret" + if data.get("azure_secret"): + secure_json_data["clientSecret"] = data["azure_secret"] + + if data["ds_type"] == "cloudwatch": + if data.get("aws_credentials_profile"): + payload["database"] = data.get("aws_credentials_profile") + + json_data["authType"] = data["aws_auth_type"] + json_data["defaultRegion"] = data["aws_default_region"] + + if data.get("aws_custom_metrics_namespaces"): + json_data["customMetricsNamespaces"] = data.get( + "aws_custom_metrics_namespaces" + ) + if data.get("aws_assume_role_arn"): + json_data["assumeRoleArn"] = data.get("aws_assume_role_arn") + if data.get("aws_access_key") and data.get("aws_secret_key"): + secure_json_data["accessKey"] = data.get("aws_access_key") + secure_json_data["secretKey"] = data.get("aws_secret_key") + + payload["jsonData"] = json_data + payload["secureJsonData"] = secure_json_data return payload class GrafanaInterface(object): - def __init__(self, module): self._module = module self.grafana_url = base.clean_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'] + 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']) + self.headers["Authorization"] = basic_auth_header( + module.params["url_username"], module.params["url_password"] + ) + self.switch_organisation(module.params["org_id"]) # }}} def _send_request(self, url, data=None, headers=None, method="GET"): @@ -689,126 +700,188 @@ def _send_request(self, url, data=None, headers=None, method="GET"): headers = [] full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url) - resp, info = fetch_url(self._module, full_url, data=data, headers=headers, method=method) + resp, info = fetch_url( + self._module, full_url, data=data, headers=headers, method=method + ) status_code = info["status"] if status_code == 404: return None elif status_code == 401: - self._module.fail_json(failed=True, msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url)) + self._module.fail_json( + failed=True, + msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url), + ) elif status_code == 403: self._module.fail_json(failed=True, msg="Permission Denied") elif status_code == 200: return self._module.from_json(resp.read()) - self._module.fail_json(failed=True, msg="Grafana API answered with HTTP %d for url %s and data %s" % (status_code, url, data)) + self._module.fail_json( + failed=True, + msg="Grafana API answered with HTTP %d for url %s and data %s" + % (status_code, url, data), + ) def switch_organisation(self, org_id): url = "/api/user/using/%d" % org_id - response = self._send_request(url, headers=self.headers, method='POST') + response = self._send_request(url, headers=self.headers, method="POST") def datasource_by_name(self, name): datasource_exists = False ds = {} - url = "/api/datasources/name/%s" % quote(name, safe='') - return self._send_request(url, headers=self.headers, method='GET') + url = "/api/datasources/name/%s" % quote(name, safe="") + return self._send_request(url, headers=self.headers, method="GET") def delete_datasource(self, name): - url = "/api/datasources/name/%s" % quote(name, safe='') - self._send_request(url, headers=self.headers, method='DELETE') + url = "/api/datasources/name/%s" % quote(name, safe="") + self._send_request(url, headers=self.headers, method="DELETE") def update_datasource(self, ds_id, data): url = "/api/datasources/%d" % ds_id - self._send_request(url, data=data, headers=self.headers, method='PUT') + self._send_request(url, data=data, headers=self.headers, method="PUT") def create_datasource(self, data): url = "/api/datasources" - self._send_request(url, data=data, headers=self.headers, method='POST') + self._send_request(url, data=data, headers=self.headers, method="POST") def setup_module_object(): argument_spec = base.grafana_argument_spec() argument_spec.update( - name=dict(required=True, type='str'), - uid=dict(type='str'), - ds_type=dict(choices=['graphite', - 'prometheus', - 'elasticsearch', - 'influxdb', - 'opentsdb', - 'mysql', - 'postgres', - 'cloudwatch', - 'alexanderzobnin-zabbix-datasource', - 'grafana-azure-monitor-datasource', - 'camptocamp-prometheus-alertmanager-datasource', - 'sni-thruk-datasource', - 'redis-datasource', - 'loki', - 'tempo']), - ds_url=dict(type='str'), - access=dict(default='proxy', choices=['proxy', 'direct']), - database=dict(type='str', default=""), - user=dict(default='', type='str'), - password=dict(default='', no_log=True, type='str'), - basic_auth_user=dict(type='str'), - basic_auth_password=dict(type='str', no_log=True), - with_credentials=dict(default=False, type='bool'), - tls_client_cert=dict(type='str', no_log=True), - tls_client_key=dict(type='str', no_log=True), - tls_ca_cert=dict(type='str', no_log=True), - tls_skip_verify=dict(type='bool', default=False), - is_default=dict(default=False, type='bool'), - org_id=dict(default=1, type='int'), - es_version=dict(type='str', default="7.10+", choices=["2", "5", "56", "60", - "70", "7.7+", "7.10+", - "8.0+"]), - max_concurrent_shard_requests=dict(type='int', default=256), - time_field=dict(default='@timestamp', type='str'), - time_interval=dict(type='str'), - interval=dict(type='str', choices=['', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'], default=''), - tsdb_version=dict(type='int', default=1, choices=[1, 2, 3]), - tsdb_resolution=dict(type='str', default='second', choices=['second', 'millisecond']), - sslmode=dict(default='disable', choices=['disable', 'require', 'verify-ca', 'verify-full']), - trends=dict(default=False, type='bool'), - aws_auth_type=dict(default='keys', choices=['keys', 'credentials', 'arn', 'default']), - aws_default_region=dict(default='us-east-1', choices=['ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1', - 'ca-central-1', - 'cn-north-1', 'cn-northwest-1', - 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', - 'sa-east-1', - 'us-east-1', 'us-east-2', 'us-gov-west-1', 'us-west-1', 'us-west-2']), - aws_access_key=dict(default='', no_log=True, type='str'), - aws_secret_key=dict(default='', no_log=True, type='str'), - aws_credentials_profile=dict(default='', type='str'), - aws_assume_role_arn=dict(default='', type='str'), - aws_custom_metrics_namespaces=dict(type='str'), - azure_cloud=dict(type='str', default='azuremonitor', choices=['azuremonitor', 'chinaazuremonitor', 'govazuremonitor', 'germanyazuremonitor']), - azure_tenant=dict(type='str'), - azure_client=dict(type='str'), - azure_secret=dict(type='str', no_log=True), - zabbix_user=dict(type='str'), - zabbix_password=dict(type='str', no_log=True), - additional_json_data=dict(type='dict', default={}, required=False), - additional_secure_json_data=dict(type='dict', default={}, required=False), - enforce_secure_data=dict(type='bool', default=False, required=False) + name=dict(required=True, type="str"), + uid=dict(type="str"), + ds_type=dict( + choices=[ + "graphite", + "prometheus", + "elasticsearch", + "influxdb", + "opentsdb", + "mysql", + "postgres", + "cloudwatch", + "alexanderzobnin-zabbix-datasource", + "grafana-azure-monitor-datasource", + "camptocamp-prometheus-alertmanager-datasource", + "sni-thruk-datasource", + "redis-datasource", + "loki", + "tempo", + ] + ), + ds_url=dict(type="str"), + access=dict(default="proxy", choices=["proxy", "direct"]), + database=dict(type="str", default=""), + user=dict(default="", type="str"), + password=dict(default="", no_log=True, type="str"), + basic_auth_user=dict(type="str"), + basic_auth_password=dict(type="str", no_log=True), + with_credentials=dict(default=False, type="bool"), + tls_client_cert=dict(type="str", no_log=True), + tls_client_key=dict(type="str", no_log=True), + tls_ca_cert=dict(type="str", no_log=True), + tls_skip_verify=dict(type="bool", default=False), + is_default=dict(default=False, type="bool"), + org_id=dict(default=1, type="int"), + es_version=dict( + type="str", + default="7.10+", + choices=["2", "5", "56", "60", "70", "7.7+", "7.10+", "8.0+"], + ), + max_concurrent_shard_requests=dict(type="int", default=256), + time_field=dict(default="@timestamp", type="str"), + time_interval=dict(type="str"), + interval=dict( + type="str", + choices=["", "Hourly", "Daily", "Weekly", "Monthly", "Yearly"], + default="", + ), + tsdb_version=dict(type="int", default=1, choices=[1, 2, 3]), + tsdb_resolution=dict( + type="str", default="second", choices=["second", "millisecond"] + ), + sslmode=dict( + default="disable", + choices=["disable", "require", "verify-ca", "verify-full"], + ), + trends=dict(default=False, type="bool"), + aws_auth_type=dict( + default="keys", choices=["keys", "credentials", "arn", "default"] + ), + aws_default_region=dict( + default="us-east-1", + choices=[ + "ap-northeast-1", + "ap-northeast-2", + "ap-southeast-1", + "ap-southeast-2", + "ap-south-1", + "ca-central-1", + "cn-north-1", + "cn-northwest-1", + "eu-central-1", + "eu-west-1", + "eu-west-2", + "eu-west-3", + "sa-east-1", + "us-east-1", + "us-east-2", + "us-gov-west-1", + "us-west-1", + "us-west-2", + ], + ), + aws_access_key=dict(default="", no_log=True, type="str"), + aws_secret_key=dict(default="", no_log=True, type="str"), + aws_credentials_profile=dict(default="", type="str"), + aws_assume_role_arn=dict(default="", type="str"), + aws_custom_metrics_namespaces=dict(type="str"), + azure_cloud=dict( + type="str", + default="azuremonitor", + choices=[ + "azuremonitor", + "chinaazuremonitor", + "govazuremonitor", + "germanyazuremonitor", + ], + ), + azure_tenant=dict(type="str"), + azure_client=dict(type="str"), + azure_secret=dict(type="str", no_log=True), + zabbix_user=dict(type="str"), + zabbix_password=dict(type="str", no_log=True), + additional_json_data=dict(type="dict", default={}, required=False), + additional_secure_json_data=dict(type="dict", default={}, required=False), + enforce_secure_data=dict(type="bool", default=False, required=False), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, - required_together=[['url_username', 'url_password', 'org_id'], ['tls_client_cert', 'tls_client_key']], - mutually_exclusive=[['url_username', 'grafana_api_key'], ['tls_ca_cert', 'tls_skip_verify']], + required_together=[ + ["url_username", "url_password", "org_id"], + ["tls_client_cert", "tls_client_key"], + ], + mutually_exclusive=[ + ["url_username", "grafana_api_key"], + ["tls_ca_cert", "tls_skip_verify"], + ], required_if=[ - ['state', 'present', ['ds_type', 'ds_url']], - ['ds_type', 'opentsdb', ['tsdb_version', 'tsdb_resolution']], - ['ds_type', 'influxdb', ['database']], - ['ds_type', 'elasticsearch', ['database', 'es_version', 'time_field', 'interval']], - ['ds_type', 'mysql', ['database']], - ['ds_type', 'postgres', ['database', 'sslmode']], - ['ds_type', 'cloudwatch', ['aws_auth_type', 'aws_default_region']], - ['es_version', "56", ['max_concurrent_shard_requests']], - ['es_version', "60", ['max_concurrent_shard_requests']], - ['es_version', "70", ['max_concurrent_shard_requests']] + ["state", "present", ["ds_type", "ds_url"]], + ["ds_type", "opentsdb", ["tsdb_version", "tsdb_resolution"]], + ["ds_type", "influxdb", ["database"]], + [ + "ds_type", + "elasticsearch", + ["database", "es_version", "time_field", "interval"], + ], + ["ds_type", "mysql", ["database"]], + ["ds_type", "postgres", ["database", "sslmode"]], + ["ds_type", "cloudwatch", ["aws_auth_type", "aws_default_region"]], + ["es_version", "56", ["max_concurrent_shard_requests"]], + ["es_version", "60", ["max_concurrent_shard_requests"]], + ["es_version", "70", ["max_concurrent_shard_requests"]], ], ) return module @@ -817,35 +890,52 @@ def setup_module_object(): def main(): module = setup_module_object() - state = module.params['state'] - name = module.params['name'] - enforce_secure_data = module.params['enforce_secure_data'] + state = module.params["state"] + name = module.params["name"] + enforce_secure_data = module.params["enforce_secure_data"] grafana_iface = GrafanaInterface(module) ds = grafana_iface.datasource_by_name(name) - if state == 'present': + if state == "present": payload = get_datasource_payload(module.params) if ds is None: grafana_iface.create_datasource(payload) ds = grafana_iface.datasource_by_name(name) - module.exit_json(changed=True, datasource=ds, msg='Datasource %s created' % name) + module.exit_json( + changed=True, datasource=ds, msg="Datasource %s created" % name + ) else: diff = compare_datasources(payload.copy(), ds.copy(), enforce_secure_data) - if diff.get('before') == diff.get('after'): - module.exit_json(changed=False, datasource=ds, msg='Datasource %s unchanged' % name) - grafana_iface.update_datasource(ds.get('id'), payload) + if diff.get("before") == diff.get("after"): + module.exit_json( + changed=False, datasource=ds, msg="Datasource %s unchanged" % name + ) + grafana_iface.update_datasource(ds.get("id"), payload) ds = grafana_iface.datasource_by_name(name) - if diff.get('before') == diff.get('after'): - module.exit_json(changed=False, datasource=ds, msg='Datasource %s unchanged' % name) - - module.exit_json(changed=True, diff=diff, datasource=ds, msg='Datasource %s updated' % name) + if diff.get("before") == diff.get("after"): + module.exit_json( + changed=False, datasource=ds, msg="Datasource %s unchanged" % name + ) + + module.exit_json( + changed=True, + diff=diff, + datasource=ds, + msg="Datasource %s updated" % name, + ) else: if ds is None: - module.exit_json(changed=False, datasource=None, msg='Datasource %s does not exist.' % name) + module.exit_json( + changed=False, + datasource=None, + msg="Datasource %s does not exist." % name, + ) grafana_iface.delete_datasource(name) - module.exit_json(changed=True, datasource=None, msg='Datasource %s deleted.' % name) + module.exit_json( + changed=True, datasource=None, msg="Datasource %s deleted." % name + ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_folder.py b/plugins/modules/grafana_folder.py index 4dcb8453..07a3400a 100644 --- a/plugins/modules/grafana_folder.py +++ b/plugins/modules/grafana_folder.py @@ -19,7 +19,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_folder author: @@ -55,9 +55,9 @@ extends_documentation_fragment: - community.grafana.basic_auth - community.grafana.api_key -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Create a folder community.grafana.grafana_folder: @@ -72,9 +72,9 @@ grafana_api_key: "{{ some_api_token_value }}" title: "grafana_working_group" state: absent -''' +""" -RETURN = ''' +RETURN = """ --- folder: description: Information about the Folder @@ -159,7 +159,7 @@ type: int sample: - 1 -''' +""" import json @@ -177,15 +177,18 @@ class GrafanaError(Exception): class GrafanaFolderInterface(object): - 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'] + 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.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: @@ -194,7 +197,9 @@ def __init__(self, module): 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="Folders API is available starting Grafana v5") + self._module.fail_json( + failed=True, msg="Folders API is available starting Grafana v5" + ) def _send_request(self, url, data=None, headers=None, method="GET"): if data is not None: @@ -203,27 +208,36 @@ def _send_request(self, url, data=None, headers=None, method="GET"): headers = [] full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url) - resp, info = fetch_url(self._module, full_url, data=data, headers=headers, method=method) + resp, info = fetch_url( + self._module, full_url, data=data, headers=headers, method=method + ) status_code = info["status"] if status_code == 404: return None elif status_code == 401: - self._module.fail_json(failed=True, msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url)) + self._module.fail_json( + failed=True, + msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url), + ) elif status_code == 403: self._module.fail_json(failed=True, msg="Permission Denied") elif status_code == 412: - error_msg = resp.read()['message'] + error_msg = resp.read()["message"] self._module.fail_json(failed=True, msg=error_msg) elif status_code == 200: # XXX: Grafana folders endpoint stopped sending back json in response for delete operations # see https://github.com/grafana/grafana/issues/77673 response = resp.read() or "{}" return self._module.from_json(response) - self._module.fail_json(failed=True, msg="Grafana Folders API answered with HTTP %d" % status_code) + self._module.fail_json( + failed=True, msg="Grafana Folders API answered with HTTP %d" % status_code + ) def get_version(self): url = "/api/health" - response = self._send_request(url, data=None, headers=self.headers, method="GET") + response = self._send_request( + url, data=None, headers=self.headers, method="GET" + ) version = response.get("version") if version is not None: major, minor, rev = version.split(".") @@ -233,7 +247,9 @@ def get_version(self): def create_folder(self, title): url = "/api/folders" folder = dict(title=title) - response = self._send_request(url, data=folder, headers=self.headers, method="POST") + response = self._send_request( + url, data=folder, headers=self.headers, method="POST" + ) return response def get_folder(self, title): @@ -262,22 +278,22 @@ def setup_module_object(): argument_spec = base.grafana_argument_spec() argument_spec.update( - name=dict(type='str', aliases=['title'], required=True), - state=dict(type='str', default='present', choices=['present', 'absent']), - skip_version_check=dict(type='bool', default=False), + name=dict(type="str", aliases=["title"], required=True), + state=dict(type="str", default="present", choices=["present", "absent"]), + skip_version_check=dict(type="bool", default=False), ) def main(): module = setup_module_object() - state = module.params['state'] - title = module.params['name'] + state = module.params["state"] + title = module.params["name"] grafana_iface = GrafanaFolderInterface(module) changed = False - if state == 'present': + if state == "present": folder = grafana_iface.get_folder(title) if folder is None: grafana_iface.create_folder(title) @@ -285,7 +301,7 @@ def main(): changed = True folder = grafana_iface.get_folder(title) module.exit_json(changed=changed, folder=folder) - elif state == 'absent': + elif state == "absent": folder = grafana_iface.get_folder(title) if folder is None: module.exit_json(changed=False, message="No folder found") @@ -293,5 +309,5 @@ def main(): module.exit_json(changed=True, message=result) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_notification_channel.py b/plugins/modules/grafana_notification_channel.py index 1913c290..30b5b112 100644 --- a/plugins/modules/grafana_notification_channel.py +++ b/plugins/modules/grafana_notification_channel.py @@ -16,9 +16,10 @@ # along with Ansible. If not, see . from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_notification_channel notes: @@ -368,10 +369,10 @@ extends_documentation_fragment: - community.grafana.basic_auth - community.grafana.api_key -''' +""" -EXAMPLES = ''' +EXAMPLES = """ - name: Create slack notification channel register: result grafana_notification_channel: @@ -391,9 +392,9 @@ grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password}}" -''' +""" -RETURN = ''' +RETURN = """ notification_channel: description: Notification channel created or updated by the module. returned: changed @@ -416,14 +417,17 @@ "uid": "slack-oops", "updated": "2020-11-10T21:10:19.675308112+03:00" } -''' +""" import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url from ansible.module_utils._text import to_text -from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, clean_url +from ansible_collections.community.grafana.plugins.module_utils.base import ( + grafana_argument_spec, + clean_url, +) from ansible.module_utils.urls import basic_auth_header @@ -432,412 +436,448 @@ class GrafanaAPIException(Exception): def dingding_channel_payload(data, payload): - payload['settings']['url'] = data['dingding_url'] - if data.get('dingding_message_type'): - payload['settings']['msgType'] = { - 'link': 'link', - 'action_card': 'actionCard', - }[data['dingding_message_type']] + payload["settings"]["url"] = data["dingding_url"] + if data.get("dingding_message_type"): + payload["settings"]["msgType"] = { + "link": "link", + "action_card": "actionCard", + }[data["dingding_message_type"]] def discord_channel_payload(data, payload): - payload['settings']['url'] = data['discord_url'] - if data.get('discord_message_content'): - payload['settings']['content'] = data['discord_message_content'] + payload["settings"]["url"] = data["discord_url"] + if data.get("discord_message_content"): + payload["settings"]["content"] = data["discord_message_content"] def email_channel_payload(data, payload): - payload['settings']['addresses'] = ';'.join(data['email_addresses']) - if data.get('email_single'): - payload['settings']['singleEmail'] = data['email_single'] + payload["settings"]["addresses"] = ";".join(data["email_addresses"]) + if data.get("email_single"): + payload["settings"]["singleEmail"] = data["email_single"] def hipchat_channel_payload(data, payload): - payload['settings']['url'] = data['hipchat_url'] - if data.get('hipchat_api_key'): - payload['settings']['apiKey'] = data['hipchat_api_key'] - if data.get('hipchat_room_id'): - payload['settings']['roomid'] = data['hipchat_room_id'] + payload["settings"]["url"] = data["hipchat_url"] + if data.get("hipchat_api_key"): + payload["settings"]["apiKey"] = data["hipchat_api_key"] + if data.get("hipchat_room_id"): + payload["settings"]["roomid"] = data["hipchat_room_id"] def pagerduty_channel_payload(data, payload): - payload['settings']['integrationKey'] = data['pagerduty_integration_key'] - if data.get('pagerduty_severity'): - payload['settings']['severity'] = data['pagerduty_severity'] - if data.get('pagerduty_auto_resolve'): - payload['settings']['autoResolve'] = data['pagerduty_auto_resolve'] - if data.get('pagerduty_message_in_details'): - payload['settings']['messageInDetails'] = data['pagerduty_message_in_details'] + payload["settings"]["integrationKey"] = data["pagerduty_integration_key"] + if data.get("pagerduty_severity"): + payload["settings"]["severity"] = data["pagerduty_severity"] + if data.get("pagerduty_auto_resolve"): + payload["settings"]["autoResolve"] = data["pagerduty_auto_resolve"] + if data.get("pagerduty_message_in_details"): + payload["settings"]["messageInDetails"] = data["pagerduty_message_in_details"] def prometheus_channel_payload(data, payload): - payload['type'] = 'prometheus-alertmanager' - payload['settings']['url'] = data['prometheus_url'] - if data.get('prometheus_username'): - payload['settings']['basicAuthUser'] = data['prometheus_username'] - if data.get('prometheus_password'): - payload['settings']['basicAuthPassword'] = data['prometheus_password'] + payload["type"] = "prometheus-alertmanager" + payload["settings"]["url"] = data["prometheus_url"] + if data.get("prometheus_username"): + payload["settings"]["basicAuthUser"] = data["prometheus_username"] + if data.get("prometheus_password"): + payload["settings"]["basicAuthPassword"] = data["prometheus_password"] def pushover_channel_payload(data, payload): - payload['settings']['apiToken'] = data['pushover_api_token'] - payload['settings']['userKey'] = data['pushover_user_key'] - if data.get('pushover_devices'): - payload['settings']['device'] = ';'.join(data['pushover_devices']) - if data.get('pushover_priority'): - payload['settings']['priority'] = { - 'emergency': '2', - 'high': '1', - 'normal': '0', - 'low': '-1', - 'lowest': '-2' - }[data['pushover_priority']] - if data.get('pushover_retry'): - payload['settings']['retry'] = str(data['pushover_retry']) - if data.get('pushover_expire'): - payload['settings']['expire'] = str(data['pushover_expire']) - if data.get('pushover_alert_sound'): - payload['settings']['sound'] = data['pushover_alert_sound'] - if data.get('pushover_ok_sound'): - payload['settings']['okSound'] = data['pushover_ok_sound'] + payload["settings"]["apiToken"] = data["pushover_api_token"] + payload["settings"]["userKey"] = data["pushover_user_key"] + if data.get("pushover_devices"): + payload["settings"]["device"] = ";".join(data["pushover_devices"]) + if data.get("pushover_priority"): + payload["settings"]["priority"] = { + "emergency": "2", + "high": "1", + "normal": "0", + "low": "-1", + "lowest": "-2", + }[data["pushover_priority"]] + if data.get("pushover_retry"): + payload["settings"]["retry"] = str(data["pushover_retry"]) + if data.get("pushover_expire"): + payload["settings"]["expire"] = str(data["pushover_expire"]) + if data.get("pushover_alert_sound"): + payload["settings"]["sound"] = data["pushover_alert_sound"] + if data.get("pushover_ok_sound"): + payload["settings"]["okSound"] = data["pushover_ok_sound"] def sensu_channel_payload(data, payload): - payload['settings']['url'] = data['sensu_url'] - if data.get('sensu_source'): - payload['settings']['source'] = data['sensu_source'] - if data.get('sensu_handler'): - payload['settings']['handler'] = data['sensu_handler'] - if data.get('sensu_username'): - payload['settings']['username'] = data['sensu_username'] - if data.get('sensu_password'): - payload['settings']['password'] = data['sensu_password'] + payload["settings"]["url"] = data["sensu_url"] + if data.get("sensu_source"): + payload["settings"]["source"] = data["sensu_source"] + if data.get("sensu_handler"): + payload["settings"]["handler"] = data["sensu_handler"] + if data.get("sensu_username"): + payload["settings"]["username"] = data["sensu_username"] + if data.get("sensu_password"): + payload["settings"]["password"] = data["sensu_password"] def slack_channel_payload(data, payload): - payload['settings']['url'] = data['slack_url'] - if data.get('slack_recipient'): - payload['settings']['recipient'] = data['slack_recipient'] - if data.get('slack_username'): - payload['settings']['username'] = data['slack_username'] - if data.get('slack_icon_emoji'): - payload['settings']['iconEmoji'] = data['slack_icon_emoji'] - if data.get('slack_icon_url'): - payload['settings']['iconUrl'] = data['slack_icon_url'] - if data.get('slack_mention_users'): - payload['settings']['mentionUsers'] = ','.join(data['slack_mention_users']) - if data.get('slack_mention_groups'): - payload['settings']['mentionGroups'] = ','.join(data['slack_mention_groups']) - if data.get('slack_mention_channel'): - payload['settings']['mentionChannel'] = data['slack_mention_channel'] - if data.get('slack_token'): - payload['settings']['token'] = data['slack_token'] + payload["settings"]["url"] = data["slack_url"] + if data.get("slack_recipient"): + payload["settings"]["recipient"] = data["slack_recipient"] + if data.get("slack_username"): + payload["settings"]["username"] = data["slack_username"] + if data.get("slack_icon_emoji"): + payload["settings"]["iconEmoji"] = data["slack_icon_emoji"] + if data.get("slack_icon_url"): + payload["settings"]["iconUrl"] = data["slack_icon_url"] + if data.get("slack_mention_users"): + payload["settings"]["mentionUsers"] = ",".join(data["slack_mention_users"]) + if data.get("slack_mention_groups"): + payload["settings"]["mentionGroups"] = ",".join(data["slack_mention_groups"]) + if data.get("slack_mention_channel"): + payload["settings"]["mentionChannel"] = data["slack_mention_channel"] + if data.get("slack_token"): + payload["settings"]["token"] = data["slack_token"] def webhook_channel_payload(data, payload): - payload['settings']['url'] = data['webhook_url'] - if data.get('webhook_http_method'): - payload['settings']['httpMethod'] = data['webhook_http_method'] - if data.get('webhook_username'): - payload['settings']['username'] = data['webhook_username'] - if data.get('webhook_password'): - payload['settings']['password'] = data['webhook_password'] + payload["settings"]["url"] = data["webhook_url"] + if data.get("webhook_http_method"): + payload["settings"]["httpMethod"] = data["webhook_http_method"] + if data.get("webhook_username"): + payload["settings"]["username"] = data["webhook_username"] + if data.get("webhook_password"): + payload["settings"]["password"] = data["webhook_password"] def grafana_notification_channel_payload(data): payload = { - 'uid': data['uid'], - 'name': data['name'], - 'type': data['type'], - 'isDefault': data['is_default'], - 'disableResolveMessage': data['disable_resolve_message'], - 'settings': { - 'uploadImage': data['include_image'] - } + "uid": data["uid"], + "name": data["name"], + "type": data["type"], + "isDefault": data["is_default"], + "disableResolveMessage": data["disable_resolve_message"], + "settings": {"uploadImage": data["include_image"]}, } - if data.get('reminder_frequency'): - payload['sendReminder'] = True - payload['frequency'] = data['reminder_frequency'] + if data.get("reminder_frequency"): + payload["sendReminder"] = True + payload["frequency"] = data["reminder_frequency"] - if data['type'] == 'dingding': + if data["type"] == "dingding": dingding_channel_payload(data, payload) - elif data['type'] == 'discord': + elif data["type"] == "discord": discord_channel_payload(data, payload) - elif data['type'] == 'email': + elif data["type"] == "email": email_channel_payload(data, payload) - elif data['type'] == 'googlechat': - payload['settings']['url'] = data['googlechat_url'] - elif data['type'] == 'hipchat': + elif data["type"] == "googlechat": + payload["settings"]["url"] = data["googlechat_url"] + elif data["type"] == "hipchat": hipchat_channel_payload(data, payload) - elif data['type'] == 'kafka': - payload['settings']['kafkaRestProxy'] = data['kafka_url'] - payload['settings']['kafkaTopic'] = data['kafka_topic'] - elif data['type'] == 'line': - payload['settings']['token'] = data['line_token'] - elif data['type'] == 'teams': - payload['settings']['url'] = data['teams_url'] - elif data['type'] == 'opsgenie': - payload['settings']['apiUrl'] = data['opsgenie_url'] - payload['settings']['apiKey'] = data['opsgenie_api_key'] - elif data['type'] == 'pagerduty': + elif data["type"] == "kafka": + payload["settings"]["kafkaRestProxy"] = data["kafka_url"] + payload["settings"]["kafkaTopic"] = data["kafka_topic"] + elif data["type"] == "line": + payload["settings"]["token"] = data["line_token"] + elif data["type"] == "teams": + payload["settings"]["url"] = data["teams_url"] + elif data["type"] == "opsgenie": + payload["settings"]["apiUrl"] = data["opsgenie_url"] + payload["settings"]["apiKey"] = data["opsgenie_api_key"] + elif data["type"] == "pagerduty": pagerduty_channel_payload(data, payload) - elif data['type'] == 'prometheus': + elif data["type"] == "prometheus": prometheus_channel_payload(data, payload) - elif data['type'] == 'pushover': + elif data["type"] == "pushover": pushover_channel_payload(data, payload) - elif data['type'] == 'sensu': + elif data["type"] == "sensu": sensu_channel_payload(data, payload) - elif data['type'] == 'slack': + elif data["type"] == "slack": slack_channel_payload(data, payload) - elif data['type'] == 'telegram': - payload['settings']['bottoken'] = data['telegram_bot_token'] - payload['settings']['chatid'] = data['telegram_chat_id'] - elif data['type'] == 'threema': - payload['settings']['gateway_id'] = data['threema_gateway_id'] - payload['settings']['recipient_id'] = data['threema_recipient_id'] - payload['settings']['api_secret'] = data['threema_api_secret'] - elif data['type'] == 'victorops': - payload['settings']['url'] = data['victorops_url'] - if data.get('victorops_auto_resolve'): - payload['settings']['autoResolve'] = data['victorops_auto_resolve'] - elif data['type'] == 'webhook': + elif data["type"] == "telegram": + payload["settings"]["bottoken"] = data["telegram_bot_token"] + payload["settings"]["chatid"] = data["telegram_chat_id"] + elif data["type"] == "threema": + payload["settings"]["gateway_id"] = data["threema_gateway_id"] + payload["settings"]["recipient_id"] = data["threema_recipient_id"] + payload["settings"]["api_secret"] = data["threema_api_secret"] + elif data["type"] == "victorops": + payload["settings"]["url"] = data["victorops_url"] + if data.get("victorops_auto_resolve"): + payload["settings"]["autoResolve"] = data["victorops_auto_resolve"] + elif data["type"] == "webhook": webhook_channel_payload(data, payload) return payload class GrafanaNotificationChannelInterface(object): - 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'] + 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.headers["Authorization"] = basic_auth_header( + module.params["url_username"], module.params["url_password"] + ) # }}} self.grafana_url = clean_url(module.params.get("url")) def grafana_switch_organisation(self, grafana_url, org_id): - r, info = fetch_url(self._module, '%s/api/user/using/%s' % (grafana_url, org_id), - headers=self.headers, method='POST') - if info['status'] != 200: - raise GrafanaAPIException('Unable to switch to organization %s : %s' % - (org_id, info)) + r, info = fetch_url( + self._module, + "%s/api/user/using/%s" % (grafana_url, org_id), + headers=self.headers, + method="POST", + ) + if info["status"] != 200: + raise GrafanaAPIException( + "Unable to switch to organization %s : %s" % (org_id, info) + ) def grafana_create_notification_channel(self, data, payload): - r, info = fetch_url(self._module, '%s/api/alert-notifications' % data['url'], - data=json.dumps(payload), headers=self.headers, method='POST') - if info['status'] == 200: + r, info = fetch_url( + self._module, + "%s/api/alert-notifications" % data["url"], + data=json.dumps(payload), + headers=self.headers, + method="POST", + ) + if info["status"] == 200: return { - 'state': 'present', - 'changed': True, - 'channel': json.loads(to_text(r.read())), + "state": "present", + "changed": True, + "channel": json.loads(to_text(r.read())), } else: - raise GrafanaAPIException("Unable to create notification channel: %s" % info) + raise GrafanaAPIException( + "Unable to create notification channel: %s" % info + ) def grafana_update_notification_channel(self, data, payload, before): - r, info = fetch_url(self._module, '%s/api/alert-notifications/uid/%s' % - (data['url'], data['uid']), - data=json.dumps(payload), headers=self.headers, method='PUT') - if info['status'] == 200: - del before['created'] - del before['updated'] + r, info = fetch_url( + self._module, + "%s/api/alert-notifications/uid/%s" % (data["url"], data["uid"]), + data=json.dumps(payload), + headers=self.headers, + method="PUT", + ) + if info["status"] == 200: + del before["created"] + del before["updated"] channel = json.loads(to_text(r.read())) after = channel.copy() - del after['created'] - del after['updated'] + del after["created"] + del after["updated"] if before == after: return { - 'changed': False, - 'channel': channel, + "changed": False, + "channel": channel, } else: return { - 'changed': True, - 'diff': { - 'before': before, - 'after': after, + "changed": True, + "diff": { + "before": before, + "after": after, }, - 'channel': channel, + "channel": channel, } else: - raise GrafanaAPIException("Unable to update notification channel %s : %s" % - (data['uid'], info)) + raise GrafanaAPIException( + "Unable to update notification channel %s : %s" % (data["uid"], info) + ) def grafana_create_or_update_notification_channel(self, data): payload = grafana_notification_channel_payload(data) - r, info = fetch_url(self._module, '%s/api/alert-notifications/uid/%s' % - (data['url'], data['uid']), headers=self.headers) - if info['status'] == 200: + r, info = fetch_url( + self._module, + "%s/api/alert-notifications/uid/%s" % (data["url"], data["uid"]), + headers=self.headers, + ) + if info["status"] == 200: before = json.loads(to_text(r.read())) return self.grafana_update_notification_channel(data, payload, before) - elif info['status'] == 404: + elif info["status"] == 404: return self.grafana_create_notification_channel(data, payload) else: - raise GrafanaAPIException("Unable to get notification channel %s : %s" % - (data['uid'], info)) + raise GrafanaAPIException( + "Unable to get notification channel %s : %s" % (data["uid"], info) + ) def grafana_delete_notification_channel(self, data): - r, info = fetch_url(self._module, '%s/api/alert-notifications/uid/%s' % - (data['url'], data['uid']), - headers=self.headers, method='DELETE') - if info['status'] == 200: - return { - 'state': 'absent', - 'changed': True - } - elif info['status'] == 404: - return { - 'changed': False - } + r, info = fetch_url( + self._module, + "%s/api/alert-notifications/uid/%s" % (data["url"], data["uid"]), + headers=self.headers, + method="DELETE", + ) + if info["status"] == 200: + return {"state": "absent", "changed": True} + elif info["status"] == 404: + return {"changed": False} else: - raise GrafanaAPIException("Unable to delete notification channel %s : %s" % - (data['uid'], info)) + raise GrafanaAPIException( + "Unable to delete notification channel %s : %s" % (data["uid"], info) + ) def main(): argument_spec = grafana_argument_spec() argument_spec.update( - org_id=dict(type='int', default=1), - uid=dict(type='str'), - name=dict(type='str'), - type=dict(type='str', - choices=['dingding', 'discord', 'email', 'googlechat', 'hipchat', - 'kafka', 'line', 'teams', 'opsgenie', 'pagerduty', - 'prometheus', 'pushover', 'sensu', 'slack', 'telegram', - 'threema', 'victorops', 'webhook']), - is_default=dict(type='bool', default=False), - include_image=dict(type='bool', default=False), - disable_resolve_message=dict(type='bool', default=False), - reminder_frequency=dict(type='str'), - - dingding_url=dict(type='str'), - dingding_message_type=dict(type='list', elements='str', - choices=['link', 'action_card']), - - discord_url=dict(type='str'), - discord_message_content=dict(type='str'), - - email_addresses=dict(type='list', elements='str'), - email_single=dict(type='bool'), - - googlechat_url=dict(type='str'), - - hipchat_url=dict(type='str'), - hipchat_api_key=dict(type='str', no_log=True), - hipchat_room_id=dict(type='str'), - - kafka_url=dict(type='str'), - kafka_topic=dict(type='str'), - - line_token=dict(type='str', no_log=True), - - teams_url=dict(type='str'), - - opsgenie_url=dict(type='str'), - opsgenie_api_key=dict(type='str', no_log=True), - opsgenie_auto_close=dict(type='bool'), - opsgenie_override_priority=dict(type='bool'), - - pagerduty_integration_key=dict(type='str', no_log=True), - pagerduty_severity=dict(type='list', elements='str', - choices=['critical', 'error', 'warning', 'info']), - pagerduty_auto_resolve=dict(type='bool'), - pagerduty_message_in_details=dict(type='bool'), - - prometheus_url=dict(type='str'), - prometheus_username=dict(type='str'), - prometheus_password=dict(type='str', no_log=True), - - pushover_api_token=dict(type='str', no_log=True), - pushover_user_key=dict(type='str', no_log=True), - pushover_devices=dict(type='list', elements='str'), - pushover_priority=dict(type='list', elements='str', - choices=['emergency', 'high', 'normal', 'low', 'lowest']), - pushover_retry=dict(type='int'), # TODO: only when priority==emergency - pushover_expire=dict(type='int'), # TODO: only when priority==emergency - pushover_alert_sound=dict(type='str'), # TODO: add sound choices - pushover_ok_sound=dict(type='str'), # TODO: add sound choices - - sensu_url=dict(type='str'), - sensu_source=dict(type='str'), - sensu_handler=dict(type='str'), - sensu_username=dict(type='str'), - sensu_password=dict(type='str', no_log=True), - - slack_url=dict(type='str', no_log=True), - slack_recipient=dict(type='str'), - slack_username=dict(type='str'), - slack_icon_emoji=dict(type='str'), - slack_icon_url=dict(type='str'), - slack_mention_users=dict(type='list', elements='str'), - slack_mention_groups=dict(type='list', elements='str'), - slack_mention_channel=dict(type='list', elements='str', - choices=['here', 'channel']), - slack_token=dict(type='str', no_log=True), - - telegram_bot_token=dict(type='str', no_log=True), - telegram_chat_id=dict(type='str'), - - threema_gateway_id=dict(type='str'), - threema_recipient_id=dict(type='str'), - threema_api_secret=dict(type='str', no_log=True), - - victorops_url=dict(type='str'), - victorops_auto_resolve=dict(type='bool'), - - webhook_url=dict(type='str'), - webhook_username=dict(type='str'), - webhook_password=dict(type='str', no_log=True), - webhook_http_method=dict(type='list', elements='str', choices=['POST', 'PUT']) + org_id=dict(type="int", default=1), + uid=dict(type="str"), + name=dict(type="str"), + type=dict( + type="str", + choices=[ + "dingding", + "discord", + "email", + "googlechat", + "hipchat", + "kafka", + "line", + "teams", + "opsgenie", + "pagerduty", + "prometheus", + "pushover", + "sensu", + "slack", + "telegram", + "threema", + "victorops", + "webhook", + ], + ), + is_default=dict(type="bool", default=False), + include_image=dict(type="bool", default=False), + disable_resolve_message=dict(type="bool", default=False), + reminder_frequency=dict(type="str"), + dingding_url=dict(type="str"), + dingding_message_type=dict( + type="list", elements="str", choices=["link", "action_card"] + ), + discord_url=dict(type="str"), + discord_message_content=dict(type="str"), + email_addresses=dict(type="list", elements="str"), + email_single=dict(type="bool"), + googlechat_url=dict(type="str"), + hipchat_url=dict(type="str"), + hipchat_api_key=dict(type="str", no_log=True), + hipchat_room_id=dict(type="str"), + kafka_url=dict(type="str"), + kafka_topic=dict(type="str"), + line_token=dict(type="str", no_log=True), + teams_url=dict(type="str"), + opsgenie_url=dict(type="str"), + opsgenie_api_key=dict(type="str", no_log=True), + opsgenie_auto_close=dict(type="bool"), + opsgenie_override_priority=dict(type="bool"), + pagerduty_integration_key=dict(type="str", no_log=True), + pagerduty_severity=dict( + type="list", + elements="str", + choices=["critical", "error", "warning", "info"], + ), + pagerduty_auto_resolve=dict(type="bool"), + pagerduty_message_in_details=dict(type="bool"), + prometheus_url=dict(type="str"), + prometheus_username=dict(type="str"), + prometheus_password=dict(type="str", no_log=True), + pushover_api_token=dict(type="str", no_log=True), + pushover_user_key=dict(type="str", no_log=True), + pushover_devices=dict(type="list", elements="str"), + pushover_priority=dict( + type="list", + elements="str", + choices=["emergency", "high", "normal", "low", "lowest"], + ), + pushover_retry=dict(type="int"), # TODO: only when priority==emergency + pushover_expire=dict(type="int"), # TODO: only when priority==emergency + pushover_alert_sound=dict(type="str"), # TODO: add sound choices + pushover_ok_sound=dict(type="str"), # TODO: add sound choices + sensu_url=dict(type="str"), + sensu_source=dict(type="str"), + sensu_handler=dict(type="str"), + sensu_username=dict(type="str"), + sensu_password=dict(type="str", no_log=True), + slack_url=dict(type="str", no_log=True), + slack_recipient=dict(type="str"), + slack_username=dict(type="str"), + slack_icon_emoji=dict(type="str"), + slack_icon_url=dict(type="str"), + slack_mention_users=dict(type="list", elements="str"), + slack_mention_groups=dict(type="list", elements="str"), + slack_mention_channel=dict( + type="list", elements="str", choices=["here", "channel"] + ), + slack_token=dict(type="str", no_log=True), + telegram_bot_token=dict(type="str", no_log=True), + telegram_chat_id=dict(type="str"), + threema_gateway_id=dict(type="str"), + threema_recipient_id=dict(type="str"), + threema_api_secret=dict(type="str", no_log=True), + victorops_url=dict(type="str"), + victorops_auto_resolve=dict(type="bool"), + webhook_url=dict(type="str"), + webhook_username=dict(type="str"), + webhook_password=dict(type="str", no_log=True), + webhook_http_method=dict(type="list", elements="str", choices=["POST", "PUT"]), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, - required_together=[['url_username', 'url_password', 'org_id'], - ['prometheus_username', 'prometheus_password'], - ['sensu_username', 'sensu_password']], - mutually_exclusive=[['url_username', 'grafana_api_key']], + required_together=[ + ["url_username", "url_password", "org_id"], + ["prometheus_username", "prometheus_password"], + ["sensu_username", "sensu_password"], + ], + mutually_exclusive=[["url_username", "grafana_api_key"]], required_if=[ - ['state', 'present', ['name', 'type']], - ['type', 'dingding', ['dingding_url']], - ['type', 'discord', ['discord_url']], - ['type', 'email', ['email_addresses']], - ['type', 'googlechat', ['googlechat_url']], - ['type', 'hipchat', ['hipchat_url']], - ['type', 'kafka', ['kafka_url', 'kafka_topic']], - ['type', 'line', ['line_token']], - ['type', 'teams', ['teams_url']], - ['type', 'opsgenie', ['opsgenie_url', 'opsgenie_api_key']], - ['type', 'pagerduty', ['pagerduty_integration_key']], - ['type', 'prometheus', ['prometheus_url']], - ['type', 'pushover', ['pushover_api_token', 'pushover_user_key']], - ['type', 'sensu', ['sensu_url']], - ['type', 'slack', ['slack_url']], - ['type', 'telegram', ['telegram_bot_token', 'telegram_chat_id']], - ['type', 'threema', ['threema_gateway_id', 'threema_recipient_id', - 'threema_api_secret']], - ['type', 'victorops', ['victorops_url']], - ['type', 'webhook', ['webhook_url']] - ] + ["state", "present", ["name", "type"]], + ["type", "dingding", ["dingding_url"]], + ["type", "discord", ["discord_url"]], + ["type", "email", ["email_addresses"]], + ["type", "googlechat", ["googlechat_url"]], + ["type", "hipchat", ["hipchat_url"]], + ["type", "kafka", ["kafka_url", "kafka_topic"]], + ["type", "line", ["line_token"]], + ["type", "teams", ["teams_url"]], + ["type", "opsgenie", ["opsgenie_url", "opsgenie_api_key"]], + ["type", "pagerduty", ["pagerduty_integration_key"]], + ["type", "prometheus", ["prometheus_url"]], + ["type", "pushover", ["pushover_api_token", "pushover_user_key"]], + ["type", "sensu", ["sensu_url"]], + ["type", "slack", ["slack_url"]], + ["type", "telegram", ["telegram_bot_token", "telegram_chat_id"]], + [ + "type", + "threema", + ["threema_gateway_id", "threema_recipient_id", "threema_api_secret"], + ], + ["type", "victorops", ["victorops_url"]], + ["type", "webhook", ["webhook_url"]], + ], ) module.params["url"] = clean_url(module.params["url"]) alert_channel_iface = GrafanaNotificationChannelInterface(module) - if module.params['state'] == 'present': - result = alert_channel_iface.grafana_create_or_update_notification_channel(module.params) + if module.params["state"] == "present": + result = alert_channel_iface.grafana_create_or_update_notification_channel( + module.params + ) module.exit_json(failed=False, **result) else: result = alert_channel_iface.grafana_delete_notification_channel(module.params) module.exit_json(failed=False, **result) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_organization.py b/plugins/modules/grafana_organization.py index 7fad4c87..7bddcb3f 100644 --- a/plugins/modules/grafana_organization.py +++ b/plugins/modules/grafana_organization.py @@ -19,7 +19,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_organization author: @@ -43,9 +43,9 @@ choices: ["present", "absent"] extends_documentation_fragment: - community.grafana.basic_auth -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Create a Grafana organization community.grafana.grafana_organization: @@ -62,9 +62,9 @@ url_password: changeme name: orgtest state: absent -''' +""" -RETURN = ''' +RETURN = """ --- org: description: Information about the organization @@ -94,7 +94,7 @@ country: "" state: "" zipCode: "" -''' +""" import json @@ -107,12 +107,13 @@ class GrafanaOrgInterface(object): - 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.headers["Authorization"] = basic_auth_header( + module.params["url_username"], module.params["url_password"] + ) # }}} self.grafana_url = base.clean_url(module.params.get("url")) @@ -123,20 +124,35 @@ def _send_request(self, url, data=None, headers=None, method="GET"): headers = [] full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url) - resp, info = fetch_url(self._module, full_url, data=data, headers=headers, method=method) + resp, info = fetch_url( + self._module, full_url, data=data, headers=headers, method=method + ) status_code = info["status"] if status_code == 404: return None elif status_code == 401: - self._module.fail_json(failed=True, msg="Unauthorized to perform action '%s' on '%s' header: %s" % (method, full_url, self.headers)) + self._module.fail_json( + failed=True, + msg="Unauthorized to perform action '%s' on '%s' header: %s" + % (method, full_url, self.headers), + ) elif status_code == 403: self._module.fail_json(failed=True, msg="Permission Denied") elif status_code == 200: return self._module.from_json(resp.read()) if resp is None: - self._module.fail_json(failed=True, msg="Cannot connect to API Grafana %s" % info['msg'], status=status_code, url=info['url']) + self._module.fail_json( + failed=True, + msg="Cannot connect to API Grafana %s" % info["msg"], + status=status_code, + url=info["url"], + ) else: - self._module.fail_json(failed=True, msg="Grafana Org API answered with HTTP %d" % status_code, body=self._module.from_json(resp.read())) + self._module.fail_json( + failed=True, + msg="Grafana Org API answered with HTTP %d" % status_code, + body=self._module.from_json(resp.read()), + ) def get_actual_org(self, name): # https://grafana.com/docs/grafana/latest/http_api/org/#get-organization-by-name @@ -160,40 +176,48 @@ def setup_module_object(): module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, - required_together=base.grafana_required_together() + required_together=base.grafana_required_together(), ) return module argument_spec = base.grafana_argument_spec() argument_spec.update( - state=dict(choices=['present', 'absent'], default='present'), - name=dict(type='str', required=True), + state=dict(choices=["present", "absent"], default="present"), + name=dict(type="str", required=True), ) -argument_spec.pop('grafana_api_key') +argument_spec.pop("grafana_api_key") def main(): module = setup_module_object() - state = module.params['state'] - name = module.params['name'] + state = module.params["state"] + name = module.params["name"] grafana_iface = GrafanaOrgInterface(module) # search org by name actual_org = grafana_iface.get_actual_org(name) - if state == 'present': + if state == "present": has_changed = False if actual_org is None: # create new org actual_org = grafana_iface.create_org(name) has_changed = True - module.exit_json(changed=has_changed, msg='Organization %s created.' % name, org=actual_org) + module.exit_json( + changed=has_changed, + msg="Organization %s created." % name, + org=actual_org, + ) else: - module.exit_json(changed=has_changed, msg='Organization %s already created.' % name, org=actual_org) + module.exit_json( + changed=has_changed, + msg="Organization %s already created." % name, + org=actual_org, + ) - elif state == 'absent': + elif state == "absent": if actual_org is None: module.exit_json(msg="No org found, nothing to do") # delete org @@ -201,5 +225,5 @@ def main(): module.exit_json(changed=True, msg=result.get("message")) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_organization_user.py b/plugins/modules/grafana_organization_user.py index 14195fdb..a56f5a0d 100644 --- a/plugins/modules/grafana_organization_user.py +++ b/plugins/modules/grafana_organization_user.py @@ -19,7 +19,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_organization_user author: @@ -66,9 +66,9 @@ extends_documentation_fragment: - community.grafana.basic_auth -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Add user to organization community.grafana.grafana_organization_user: @@ -85,9 +85,9 @@ url_password: "{{ grafana_password }}" login: john state: absent -''' +""" -RETURN = ''' +RETURN = """ --- user: description: Information about the organization user @@ -128,7 +128,7 @@ - Admin sample: - Viewer -''' +""" import json @@ -136,7 +136,10 @@ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url from ansible.module_utils._text import to_text -from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, clean_url +from ansible_collections.community.grafana.plugins.module_utils.base import ( + grafana_argument_spec, + clean_url, +) from ansible.module_utils.urls import basic_auth_header __metaclass__ = type @@ -147,12 +150,13 @@ class GrafanaAPIException(Exception): class GrafanaOrganizationUserInterface(object): - 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.headers["Authorization"] = basic_auth_header( + module.params["url_username"], module.params["url_password"] + ) # }}} self.grafana_url = clean_url(module.params.get("url")) @@ -160,114 +164,125 @@ def _api_call(self, method, path, payload): data = None if payload: data = json.dumps(payload) - return fetch_url(self._module, self.grafana_url + '/api/' + path, headers=self.headers, method=method, data=data) + return fetch_url( + self._module, + self.grafana_url + "/api/" + path, + headers=self.headers, + method=method, + data=data, + ) def _organization_by_name(self, org_name): - r, info = self._api_call('GET', 'orgs/name/%s' % org_name, None) - if info['status'] != 200: + r, info = self._api_call("GET", "orgs/name/%s" % org_name, None) + if info["status"] != 200: raise GrafanaAPIException("Unable to retrieve organization: %s" % info) return json.loads(to_text(r.read())) def _organization_users(self, org_id): - r, info = self._api_call('GET', 'orgs/%d/users' % org_id, None) - if info['status'] != 200: - raise GrafanaAPIException("Unable to retrieve organization users: %s" % info) + r, info = self._api_call("GET", "orgs/%d/users" % org_id, None) + if info["status"] != 200: + raise GrafanaAPIException( + "Unable to retrieve organization users: %s" % info + ) return json.loads(to_text(r.read())) def _create_organization_user(self, org_id, login, role): - return self._api_call('POST', 'orgs/%d/users' % org_id, { - "loginOrEmail": login, - "role": role, - }) + return self._api_call( + "POST", + "orgs/%d/users" % org_id, + { + "loginOrEmail": login, + "role": role, + }, + ) def _update_organization_user_role(self, org_id, user_id, role): - return self._api_call('PATCH', 'orgs/%d/users/%s' % (org_id, user_id), { - "role": role, - }) + return self._api_call( + "PATCH", + "orgs/%d/users/%s" % (org_id, user_id), + { + "role": role, + }, + ) def _remove_organization_user(self, org_id, user_id): - return self._api_call('DELETE', 'orgs/%d/users/%s' % (org_id, user_id), None) + return self._api_call("DELETE", "orgs/%d/users/%s" % (org_id, user_id), None) def _organization_user_by_login(self, org_id, login): for user in self._organization_users(org_id): - if login in (user['login'], user['email']): + if login in (user["login"], user["email"]): return user def create_or_update_user(self, org_id, login, role): r, info = self._create_organization_user(org_id, login, role) - if info['status'] == 200: + if info["status"] == 200: return { - 'state': 'present', - 'changed': True, - 'user': self._organization_user_by_login(org_id, login), + "state": "present", + "changed": True, + "user": self._organization_user_by_login(org_id, login), } - if info['status'] == 409: # already member + if info["status"] == 409: # already member user = self._organization_user_by_login(org_id, login) if not user: raise Exception("[BUG] User not found in organization") - if user['role'] == role: - return { - 'changed': False - } + if user["role"] == role: + return {"changed": False} - r, info = self._update_organization_user_role(org_id, user['userId'], role) - if info['status'] == 200: + r, info = self._update_organization_user_role(org_id, user["userId"], role) + if info["status"] == 200: return { - 'changed': True, - 'user': self._organization_user_by_login(org_id, login), + "changed": True, + "user": self._organization_user_by_login(org_id, login), } else: - raise GrafanaAPIException("Unable to update organization user: %s" % info) + raise GrafanaAPIException( + "Unable to update organization user: %s" % info + ) else: raise GrafanaAPIException("Unable to add user to organization: %s" % info) def remove_user(self, org_id, login): user = self._organization_user_by_login(org_id, login) if not user: - return { - 'changed': False - } + return {"changed": False} - r, info = self._remove_organization_user(org_id, user['userId']) - if info['status'] == 200: - return { - 'state': 'absent', - 'changed': True - } + r, info = self._remove_organization_user(org_id, user["userId"]) + if info["status"] == 200: + return {"state": "absent", "changed": True} else: raise GrafanaAPIException("Unable to delete organization user: %s" % info) def main(): argument_spec = grafana_argument_spec() - argument_spec.pop('grafana_api_key') + argument_spec.pop("grafana_api_key") argument_spec.update( - org_id=dict(type='int', default=1), - org_name=dict(type='str'), - login=dict(type='str', required=True), - role=dict(type='str', choices=['viewer', 'editor', 'admin'], default='viewer'), + org_id=dict(type="int", default=1), + org_name=dict(type="str"), + login=dict(type="str", required=True), + role=dict(type="str", choices=["viewer", "editor", "admin"], default="viewer"), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, mutually_exclusive=[ - ('org_id', 'org_name'), + ("org_id", "org_name"), ], required_if=[ - ['state', 'present', ['role']], - ] + ["state", "present", ["role"]], + ], ) - org_id = module.params['org_id'] - login = module.params['login'] + org_id = module.params["org_id"] + login = module.params["login"] iface = GrafanaOrganizationUserInterface(module) - if module.params['org_name']: - org_name = module.params['org_name'] + if module.params["org_name"]: + org_name = module.params["org_name"] organization = iface._organization_by_name(org_name) - org_id = organization['id'] - if module.params['state'] == 'present': - role = module.params['role'].capitalize() + org_id = organization["id"] + if module.params["state"] == "present": + role = module.params["role"].capitalize() result = iface.create_or_update_user(org_id, login, role) module.exit_json(failed=False, **result) else: @@ -275,5 +290,5 @@ def main(): module.exit_json(failed=False, **result) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_plugin.py b/plugins/modules/grafana_plugin.py index 073de119..c510f02b 100644 --- a/plugins/modules/grafana_plugin.py +++ b/plugins/modules/grafana_plugin.py @@ -6,7 +6,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = '''module: grafana_plugin +DOCUMENTATION = """module: grafana_plugin author: - Thierry Sallé (@seuf) short_description: Manage Grafana plugins via grafana-cli @@ -52,24 +52,24 @@ - Boolean variable to include --insecure while installing pluging default: false type: bool -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Install/update Grafana piechart panel plugin community.grafana.grafana_plugin: name: grafana-piechart-panel version: latest state: present -''' +""" -RETURN = ''' +RETURN = """ --- version: description: version of the installed/removed/updated plugin. type: str returned: always -''' +""" import os from ansible.module_utils.basic import AnsibleModule @@ -82,18 +82,18 @@ class GrafanaCliException(Exception): def parse_version(string): - name, version = string.split('@') + name, version = string.split("@") return name.strip(), version.strip() def grafana_cli_bin(params): - ''' + """ Get the grafana-cli binary path with global options. Raise a GrafanaCliException if the grafana-cli is not present or not in PATH :param params: ansible module params. Used to fill grafana-cli global params. - ''' - program = 'grafana-cli' + """ + program = "grafana-cli" grafana_cli = None def is_exe(fpath): @@ -112,50 +112,57 @@ def is_exe(fpath): break if grafana_cli is None: - raise GrafanaCliException('grafana-cli binary is not present or not in PATH') + raise GrafanaCliException("grafana-cli binary is not present or not in PATH") else: - if 'grafana_plugin_url' in params and params['grafana_plugin_url']: - grafana_cli = '{0} {1} {2}'.format(grafana_cli, '--pluginUrl', params['grafana_plugin_url']) - if 'grafana_plugins_dir' in params and params['grafana_plugins_dir']: - grafana_cli = '{0} {1} {2}'.format(grafana_cli, '--pluginsDir', params['grafana_plugins_dir']) - if 'grafana_repo' in params and params['grafana_repo']: - grafana_cli = '{0} {1} {2}'.format(grafana_cli, '--repo', params['grafana_repo']) - if 'validate_certs' in params and params['validate_certs'] is False: - grafana_cli = '{0} {1}'.format(grafana_cli, '--insecure') - - return '{0} {1}'.format(grafana_cli, 'plugins') + if "grafana_plugin_url" in params and params["grafana_plugin_url"]: + grafana_cli = "{0} {1} {2}".format( + grafana_cli, "--pluginUrl", params["grafana_plugin_url"] + ) + if "grafana_plugins_dir" in params and params["grafana_plugins_dir"]: + grafana_cli = "{0} {1} {2}".format( + grafana_cli, "--pluginsDir", params["grafana_plugins_dir"] + ) + if "grafana_repo" in params and params["grafana_repo"]: + grafana_cli = "{0} {1} {2}".format( + grafana_cli, "--repo", params["grafana_repo"] + ) + if "validate_certs" in params and params["validate_certs"] is False: + grafana_cli = "{0} {1}".format(grafana_cli, "--insecure") + + return "{0} {1}".format(grafana_cli, "plugins") def get_grafana_plugin_version(module, params): - ''' + """ Fetch grafana installed plugin version. Return None if plugin is not installed. :param module: ansible module object. used to run system commands. :param params: ansible module params. - ''' + """ grafana_cli = grafana_cli_bin(params) - rc, stdout, stderr = module.run_command('{0} ls'.format(grafana_cli)) + rc, stdout, stderr = module.run_command("{0} ls".format(grafana_cli)) stdout_lines = stdout.split("\n") for line in stdout_lines: - if line.find(' @ ') != -1: + if line.find(" @ ") != -1: line = line.rstrip() plugin_name, plugin_version = parse_version(line) - if plugin_name == params['name']: + if plugin_name == params["name"]: return plugin_version return None def get_grafana_plugin_version_latest(module, params): - ''' + """ Fetch the latest version available from grafana-cli. Return the newest version number or None not found. :param module: ansible module object. used to run system commands. :param params: ansible module params. - ''' + """ grafana_cli = grafana_cli_bin(params) - rc, stdout, stderr = module.run_command('{0} list-versions {1}'.format(grafana_cli, - params['name'])) + rc, stdout, stderr = module.run_command( + "{0} list-versions {1}".format(grafana_cli, params["name"]) + ) stdout_lines = stdout.split("\n") if stdout_lines[0]: return stdout_lines[0].rstrip() @@ -163,108 +170,126 @@ def get_grafana_plugin_version_latest(module, params): def grafana_plugin(module, params): - ''' + """ Install update or remove grafana plugin :param module: ansible module object. used to run system commands. :param params: ansible module params. - ''' + """ grafana_cli = grafana_cli_bin(params) - if params['state'] == 'present': + if params["state"] == "present": grafana_plugin_version = get_grafana_plugin_version(module, params) if grafana_plugin_version is not None: - if 'version' in params and params['version']: - if params['version'] == grafana_plugin_version: - return {'msg': 'Grafana plugin already installed', - 'changed': False, - 'version': grafana_plugin_version} + if "version" in params and params["version"]: + if params["version"] == grafana_plugin_version: + return { + "msg": "Grafana plugin already installed", + "changed": False, + "version": grafana_plugin_version, + } else: - if params['version'] == 'latest' or params['version'] is None: - latest_version = get_grafana_plugin_version_latest(module, params) + if params["version"] == "latest" or params["version"] is None: + latest_version = get_grafana_plugin_version_latest( + module, params + ) if latest_version == grafana_plugin_version: - return {'msg': 'Grafana plugin already installed', - 'changed': False, - 'version': grafana_plugin_version} - cmd = '{0} update {1}'.format(grafana_cli, params['name']) + return { + "msg": "Grafana plugin already installed", + "changed": False, + "version": grafana_plugin_version, + } + cmd = "{0} update {1}".format(grafana_cli, params["name"]) else: - cmd = '{0} install {1} {2}'.format(grafana_cli, params['name'], params['version']) + cmd = "{0} install {1} {2}".format( + grafana_cli, params["name"], params["version"] + ) else: - return {'msg': 'Grafana plugin already installed', - 'changed': False, - 'version': grafana_plugin_version} + return { + "msg": "Grafana plugin already installed", + "changed": False, + "version": grafana_plugin_version, + } else: - if 'version' in params: - if params['version'] == 'latest' or params['version'] is None: - cmd = '{0} install {1}'.format(grafana_cli, params['name']) + if "version" in params: + if params["version"] == "latest" or params["version"] is None: + cmd = "{0} install {1}".format(grafana_cli, params["name"]) else: - cmd = '{0} install {1} {2}'.format(grafana_cli, params['name'], params['version']) + cmd = "{0} install {1} {2}".format( + grafana_cli, params["name"], params["version"] + ) else: - cmd = '{0} install {1}'.format(grafana_cli, params['name']) + cmd = "{0} install {1}".format(grafana_cli, params["name"]) else: - cmd = '{0} uninstall {1}'.format(grafana_cli, params['name']) + cmd = "{0} uninstall {1}".format(grafana_cli, params["name"]) rc, stdout, stderr = module.run_command(cmd) if rc == 0: stdout_lines = stdout.split("\n") for line in stdout_lines: - if line.find(params['name']): - if line.find(' @ ') != -1: + if line.find(params["name"]): + if line.find(" @ ") != -1: line = line.rstrip() plugin_name, plugin_version = parse_version(line) else: plugin_version = None - if params['state'] == 'present': - return {'msg': 'Grafana plugin {0} installed : {1}'.format(params['name'], cmd), - 'changed': True, - 'version': plugin_version} + if params["state"] == "present": + return { + "msg": "Grafana plugin {0} installed : {1}".format( + params["name"], cmd + ), + "changed": True, + "version": plugin_version, + } else: - return {'msg': 'Grafana plugin {0} uninstalled : {1}'.format(params['name'], cmd), - 'changed': True} + return { + "msg": "Grafana plugin {0} uninstalled : {1}".format( + params["name"], cmd + ), + "changed": True, + } else: - if params['state'] == 'absent' and stdout.find("plugin does not exist"): - return {'msg': 'Grafana plugin {0} already uninstalled : {1}'.format(params['name'], cmd), 'changed': False} - raise GrafanaCliException("'{0}' execution returned an error : [{1}] {2} {3}".format(cmd, rc, stdout, stderr)) + if params["state"] == "absent" and stdout.find("plugin does not exist"): + return { + "msg": "Grafana plugin {0} already uninstalled : {1}".format( + params["name"], cmd + ), + "changed": False, + } + raise GrafanaCliException( + "'{0}' execution returned an error : [{1}] {2} {3}".format( + cmd, rc, stdout, stderr + ) + ) def main(): module = AnsibleModule( argument_spec=dict( - name=dict(required=True, - type='str'), - version=dict(type='str'), - grafana_plugins_dir=dict(type='str'), - grafana_repo=dict(type='str'), - grafana_plugin_url=dict(type='str'), - validate_certs=dict(type='bool', default=False), - state=dict(choices=['present', 'absent'], - default='present') + name=dict(required=True, type="str"), + version=dict(type="str"), + grafana_plugins_dir=dict(type="str"), + grafana_repo=dict(type="str"), + grafana_plugin_url=dict(type="str"), + validate_certs=dict(type="bool", default=False), + state=dict(choices=["present", "absent"], default="present"), ), - supports_check_mode=False + supports_check_mode=False, ) try: result = grafana_plugin(module, module.params) except GrafanaCliException as e: - module.fail_json( - failed=True, - msg="{0}".format(e) - ) + module.fail_json(failed=True, msg="{0}".format(e)) return except Exception as e: - module.fail_json( - failed=True, - msg="{0} : {1} ".format(type(e), e) - ) + module.fail_json(failed=True, msg="{0} : {1} ".format(type(e), e)) return - module.exit_json( - failed=False, - **result - ) + module.exit_json(failed=False, **result) return -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_team.py b/plugins/modules/grafana_team.py index b7b2318d..787b4345 100644 --- a/plugins/modules/grafana_team.py +++ b/plugins/modules/grafana_team.py @@ -19,7 +19,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_team author: @@ -72,9 +72,9 @@ extends_documentation_fragment: - community.grafana.basic_auth - community.grafana.api_key -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Create a team community.grafana.grafana_team: @@ -114,9 +114,9 @@ name: "grafana_working_group" email: "foo.bar@example.com" state: absent -''' +""" -RETURN = ''' +RETURN = """ --- team: description: Information about the Team @@ -165,7 +165,7 @@ type: int sample: - 1 -''' +""" import json @@ -183,15 +183,18 @@ class GrafanaError(Exception): class GrafanaTeamInterface(object): - 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'] + 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.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: @@ -200,7 +203,9 @@ def __init__(self, module): 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") + self._module.fail_json( + failed=True, msg="Teams API is available starting Grafana v5" + ) def _send_request(self, url, data=None, headers=None, method="GET"): if data is not None: @@ -209,23 +214,32 @@ def _send_request(self, url, data=None, headers=None, method="GET"): headers = [] full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url) - resp, info = fetch_url(self._module, full_url, data=data, headers=headers, method=method) + resp, info = fetch_url( + self._module, full_url, data=data, headers=headers, method=method + ) status_code = info["status"] if status_code == 404: return None elif status_code == 401: - self._module.fail_json(failed=True, msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url)) + self._module.fail_json( + failed=True, + msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url), + ) elif status_code == 403: self._module.fail_json(failed=True, msg="Permission Denied") elif status_code == 409: self._module.fail_json(failed=True, msg="Team name is taken") elif status_code == 200: return self._module.from_json(resp.read()) - self._module.fail_json(failed=True, msg="Grafana Teams API answered with HTTP %d" % status_code) + self._module.fail_json( + failed=True, msg="Grafana Teams API answered with HTTP %d" % status_code + ) def get_version(self): url = "/api/health" - response = self._send_request(url, data=None, headers=self.headers, method="GET") + response = self._send_request( + url, data=None, headers=self.headers, method="GET" + ) version = response.get("version") if version is not None: major, minor, rev = version.split(".") @@ -235,7 +249,9 @@ def get_version(self): def create_team(self, name, email): url = "/api/teams" team = dict(email=email, name=name) - response = self._send_request(url, data=team, headers=self.headers, method="POST") + response = self._send_request( + url, data=team, headers=self.headers, method="POST" + ) return response def get_team(self, name): @@ -251,7 +267,9 @@ def get_team(self, name): def update_team(self, team_id, name, email): url = "/api/teams/{team_id}".format(team_id=team_id) team = dict(email=email, name=name) - response = self._send_request(url, data=team, headers=self.headers, method="PUT") + response = self._send_request( + url, data=team, headers=self.headers, method="PUT" + ) return response def delete_team(self, team_id): @@ -272,7 +290,9 @@ def add_team_member(self, team_id, email): def delete_team_member(self, team_id, email): user_id = self.get_user_id_from_mail(email) - url = "/api/teams/{team_id}/members/{user_id}".format(team_id=team_id, user_id=user_id) + url = "/api/teams/{team_id}/members/{user_id}".format( + team_id=team_id, user_id=user_id + ) self._send_request(url, headers=self.headers, method="DELETE") def get_user_id_from_mail(self, email): @@ -295,27 +315,27 @@ def setup_module_object(): argument_spec = base.grafana_argument_spec() argument_spec.update( - name=dict(type='str', required=True), - email=dict(type='str', required=True), - members=dict(type='list', elements='str', required=False), - enforce_members=dict(type='bool', default=False), - skip_version_check=dict(type='bool', default=False), + name=dict(type="str", required=True), + email=dict(type="str", required=True), + members=dict(type="list", elements="str", required=False), + enforce_members=dict(type="bool", default=False), + skip_version_check=dict(type="bool", default=False), ) def main(): module = setup_module_object() - state = module.params['state'] - name = module.params['name'] - email = module.params['email'] - members = module.params['members'] - enforce_members = module.params['enforce_members'] + state = module.params["state"] + name = module.params["name"] + email = module.params["email"] + members = module.params["members"] + enforce_members = module.params["enforce_members"] grafana_iface = GrafanaTeamInterface(module) changed = False - if state == 'present': + if state == "present": team = grafana_iface.get_team(name) if team is None: grafana_iface.create_team(name, email) @@ -332,9 +352,9 @@ def main(): grafana_iface.delete_team_member(team.get("id"), member) changed = True team = grafana_iface.get_team(name) - team['members'] = grafana_iface.get_team_members(team.get("id")) + team["members"] = grafana_iface.get_team_members(team.get("id")) module.exit_json(failed=False, changed=changed, team=team) - elif state == 'absent': + elif state == "absent": team = grafana_iface.get_team(name) if team is None: module.exit_json(failed=False, changed=False, message="No team found") @@ -353,5 +373,5 @@ def diff_members(target, current): return diff -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/plugins/modules/grafana_user.py b/plugins/modules/grafana_user.py index 3247b534..7db3e335 100644 --- a/plugins/modules/grafana_user.py +++ b/plugins/modules/grafana_user.py @@ -19,7 +19,7 @@ from __future__ import absolute_import, division, print_function -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: grafana_user author: @@ -72,9 +72,9 @@ requires basic auth and admin privileges. extends_documentation_fragment: - community.grafana.basic_auth -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- - name: Create or update a Grafana user community.grafana.grafana_user: @@ -95,9 +95,9 @@ url_password: changeme login: batman state: absent -''' +""" -RETURN = ''' +RETURN = """ --- user: description: Information about the User @@ -152,7 +152,7 @@ type: bool sample: - false -''' +""" import json @@ -165,12 +165,13 @@ class GrafanaUserInterface(object): - 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.headers["Authorization"] = basic_auth_header( + module.params["url_username"], module.params["url_password"] + ) # }}} self.grafana_url = base.clean_url(module.params.get("url")) @@ -181,22 +182,34 @@ def _send_request(self, url, data=None, headers=None, method="GET"): headers = [] full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url) - resp, info = fetch_url(self._module, full_url, data=data, headers=headers, method=method) + resp, info = fetch_url( + self._module, full_url, data=data, headers=headers, method=method + ) status_code = info["status"] if status_code == 404: return None elif status_code == 401: - self._module.fail_json(failed=True, msg="Unauthorized to perform action '%s' on '%s' header: %s" % (method, full_url, self.headers)) + self._module.fail_json( + failed=True, + msg="Unauthorized to perform action '%s' on '%s' header: %s" + % (method, full_url, self.headers), + ) elif status_code == 403: self._module.fail_json(failed=True, msg="Permission Denied") elif status_code == 200: return self._module.from_json(resp.read()) - self._module.fail_json(failed=True, msg="Grafana Users API answered with HTTP %d" % status_code, body=self._module.from_json(resp.read())) + self._module.fail_json( + failed=True, + msg="Grafana Users API answered with HTTP %d" % status_code, + body=self._module.from_json(resp.read()), + ) def create_user(self, name, email, login, password): # https://grafana.com/docs/http_api/admin/#global-users if not password: - self._module.fail_json(failed=True, msg="missing required arguments: password") + self._module.fail_json( + failed=True, msg="missing required arguments: password" + ) url = "/api/admin/users" user = dict(name=name, email=email, login=login, password=password) self._send_request(url, data=user, headers=self.headers, method="POST") @@ -218,7 +231,9 @@ def update_user_permissions(self, user_id, is_admin): # https://grafana.com/docs/http_api/admin/#permissions url = "/api/admin/users/{user_id}/permissions".format(user_id=user_id) permissions = dict(isGrafanaAdmin=is_admin) - return self._send_request(url, data=permissions, headers=self.headers, method="PUT") + return self._send_request( + url, data=permissions, headers=self.headers, method="PUT" + ) def delete_user(self, user_id): # https://grafana.com/docs/http_api/admin/#delete-global-user @@ -232,7 +247,7 @@ def is_user_update_required(target_user, email, name, login, is_admin): email=target_user.get("email"), name=target_user.get("name"), login=target_user.get("login"), - is_admin=target_user.get("isGrafanaAdmin") + is_admin=target_user.get("isGrafanaAdmin"), ) param_dict = dict(email=email, name=name, login=login, is_admin=is_admin) return target_user_dict != param_dict @@ -243,44 +258,46 @@ def setup_module_object(): argument_spec=argument_spec, supports_check_mode=False, required_if=[ - ['state', 'present', ['name', 'email']], + ["state", "present", ["name", "email"]], ], - required_together=base.grafana_required_together() + required_together=base.grafana_required_together(), ) return module argument_spec = base.grafana_argument_spec() argument_spec.update( - state=dict(choices=['present', 'absent'], default='present'), - name=dict(type='str', required=False), - email=dict(type='str', required=False), - login=dict(type='str', required=True), - password=dict(type='str', required=False, no_log=True), - is_admin=dict(type='bool', default=False), + state=dict(choices=["present", "absent"], default="present"), + name=dict(type="str", required=False), + email=dict(type="str", required=False), + login=dict(type="str", required=True), + password=dict(type="str", required=False, no_log=True), + is_admin=dict(type="bool", default=False), ) -argument_spec.pop('grafana_api_key') +argument_spec.pop("grafana_api_key") def main(): module = setup_module_object() - state = module.params['state'] - name = module.params['name'] - email = module.params['email'] - login = module.params['login'] - password = module.params['password'] - is_admin = module.params['is_admin'] + state = module.params["state"] + name = module.params["name"] + email = module.params["email"] + login = module.params["login"] + password = module.params["password"] + is_admin = module.params["is_admin"] grafana_iface = GrafanaUserInterface(module) # search user by login actual_grafana_user = grafana_iface.get_user_from_login(login) - if state == 'present': + if state == "present": has_changed = False if actual_grafana_user is None: # create new user - actual_grafana_user = grafana_iface.create_user(name, email, login, password) + actual_grafana_user = grafana_iface.create_user( + name, email, login, password + ) has_changed = True if is_user_update_required(actual_grafana_user, email, name, login, is_admin): @@ -288,17 +305,19 @@ def main(): actual_grafana_user_id = actual_grafana_user.get("id") if is_admin != actual_grafana_user.get("isGrafanaAdmin"): grafana_iface.update_user_permissions(actual_grafana_user_id, is_admin) - actual_grafana_user = grafana_iface.update_user(actual_grafana_user_id, email, name, login) + actual_grafana_user = grafana_iface.update_user( + actual_grafana_user_id, email, name, login + ) has_changed = True module.exit_json(changed=has_changed, user=actual_grafana_user) - elif state == 'absent': + elif state == "absent": if actual_grafana_user is None: module.exit_json(message="No user found, nothing to do") result = grafana_iface.delete_user(actual_grafana_user.get("id")) module.exit_json(changed=True, message=result.get("message")) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/tests/requirements.yml b/tests/requirements.yml new file mode 100644 index 00000000..b9d14e2c --- /dev/null +++ b/tests/requirements.yml @@ -0,0 +1,3 @@ +collections: + - name: community.grafana + version: 1.5.3 diff --git a/tests/unit/modules/grafana/grafana_datasource/test_grafana_datasource.py b/tests/unit/modules/grafana/grafana_datasource/test_grafana_datasource.py index 0a68fda7..ff8e4f24 100644 --- a/tests/unit/modules/grafana/grafana_datasource/test_grafana_datasource.py +++ b/tests/unit/modules/grafana/grafana_datasource/test_grafana_datasource.py @@ -1,4 +1,4 @@ -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function from unittest import TestCase from unittest.mock import patch @@ -13,200 +13,207 @@ def set_module_args(args): """prepare arguments so that they will be picked up during module creation""" - args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) + args = json.dumps({"ANSIBLE_MODULE_ARGS": args}) basic._ANSIBLE_ARGS = to_bytes(args) def exit_json(*args, **kwargs): """function to patch over exit_json; package return data into an exception""" - if 'changed' not in kwargs: - kwargs['changed'] = False + if "changed" not in kwargs: + kwargs["changed"] = False raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): """function to patch over fail_json; package return data into an exception""" - kwargs['failed'] = True + kwargs["failed"] = True raise AnsibleFailJson(kwargs) class AnsibleExitJson(Exception): """Exception class to be raised by module.exit_json and caught by the test case""" + pass class AnsibleFailJson(Exception): """Exception class to be raised by module.fail_json and caught by the test case""" + pass class GrafanaDatasource(TestCase): - def setUp(self): self.authorization = basic_auth_header("admin", "admin") - self.mock_module_helper = patch.multiple(basic.AnsibleModule, - exit_json=exit_json, - fail_json=fail_json) + 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) def test_payload_prometheus(self): expected_payload = { - 'access': 'proxy', - 'basicAuth': False, - 'database': '', - 'isDefault': False, - 'jsonData': { - 'tlsAuth': False, - 'tlsAuthWithCACert': False, - 'tlsSkipVerify': True + "access": "proxy", + "basicAuth": False, + "database": "", + "isDefault": False, + "jsonData": { + "tlsAuth": False, + "tlsAuthWithCACert": False, + "tlsSkipVerify": True, }, - 'name': 'openshift_prometheus', - 'uid': 'xyz123', - 'orgId': 1, - 'secureJsonData': {}, - 'type': 'prometheus', - 'url': 'https://openshift-monitoring.company.com', - 'user': '', - 'withCredentials': False + "name": "openshift_prometheus", + "uid": "xyz123", + "orgId": 1, + "secureJsonData": {}, + "type": "prometheus", + "url": "https://openshift-monitoring.company.com", + "user": "", + "withCredentials": False, } - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'admin', - 'name': 'openshift_prometheus', - 'uid': 'xyz123', - 'ds_type': 'prometheus', - 'ds_url': 'https://openshift-monitoring.company.com', - 'access': 'proxy', - 'tls_skip_verify': 'true', - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "admin", + "name": "openshift_prometheus", + "uid": "xyz123", + "ds_type": "prometheus", + "ds_url": "https://openshift-monitoring.company.com", + "access": "proxy", + "tls_skip_verify": "true", + } + ) module = grafana_datasource.setup_module_object() payload = grafana_datasource.get_datasource_payload(module.params) self.assertEqual(payload, expected_payload) def test_payload_prometheus_with_basic_auth(self): expected_payload = { - 'access': 'proxy', - 'basicAuth': True, - 'basicAuthUser': 'admin', - 'database': '', - 'isDefault': False, - 'jsonData': { - 'tlsAuth': False, - 'tlsAuthWithCACert': False, - 'tlsSkipVerify': True + "access": "proxy", + "basicAuth": True, + "basicAuthUser": "admin", + "database": "", + "isDefault": False, + "jsonData": { + "tlsAuth": False, + "tlsAuthWithCACert": False, + "tlsSkipVerify": True, }, - 'name': 'openshift_prometheus', - 'uid': 'xyz123', - 'orgId': 1, - 'secureJsonData': {'basicAuthPassword': 'admin'}, - 'type': 'prometheus', - 'url': 'https://openshift-monitoring.company.com', - 'user': '', - 'withCredentials': False + "name": "openshift_prometheus", + "uid": "xyz123", + "orgId": 1, + "secureJsonData": {"basicAuthPassword": "admin"}, + "type": "prometheus", + "url": "https://openshift-monitoring.company.com", + "user": "", + "withCredentials": False, } - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'admin', - 'name': 'openshift_prometheus', - 'uid': 'xyz123', - 'ds_type': 'prometheus', - 'ds_url': 'https://openshift-monitoring.company.com', - 'access': 'proxy', - 'basic_auth_user': 'admin', - 'basic_auth_password': 'admin', - 'tls_skip_verify': 'true', - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "admin", + "name": "openshift_prometheus", + "uid": "xyz123", + "ds_type": "prometheus", + "ds_url": "https://openshift-monitoring.company.com", + "access": "proxy", + "basic_auth_user": "admin", + "basic_auth_password": "admin", + "tls_skip_verify": "true", + } + ) module = grafana_datasource.setup_module_object() payload = grafana_datasource.get_datasource_payload(module.params) self.assertEqual(payload, expected_payload) def test_payload_influxdb(self): expected_payload = { - 'access': 'proxy', - 'basicAuth': False, - 'database': 'telegraf', - 'isDefault': False, - 'jsonData': { - 'timeInterval': '>10s', - 'tlsAuth': False, - 'tlsAuthWithCACert': True - }, - 'name': 'datasource-influxdb', - 'uid': 'xyz123', - 'orgId': 1, - 'secureJsonData': { - 'tlsCACert': '/etc/ssl/certs/ca.pem' + "access": "proxy", + "basicAuth": False, + "database": "telegraf", + "isDefault": False, + "jsonData": { + "timeInterval": ">10s", + "tlsAuth": False, + "tlsAuthWithCACert": True, }, - 'type': 'influxdb', - 'url': 'https://influx.company.com:8086', - 'user': '', - 'withCredentials': False + "name": "datasource-influxdb", + "uid": "xyz123", + "orgId": 1, + "secureJsonData": {"tlsCACert": "/etc/ssl/certs/ca.pem"}, + "type": "influxdb", + "url": "https://influx.company.com:8086", + "user": "", + "withCredentials": False, } - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'admin', - 'name': 'datasource-influxdb', - 'uid': 'xyz123', - 'ds_type': 'influxdb', - 'ds_url': 'https://influx.company.com:8086', - 'database': 'telegraf', - 'time_interval': '>10s', - 'tls_ca_cert': '/etc/ssl/certs/ca.pem' - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "admin", + "name": "datasource-influxdb", + "uid": "xyz123", + "ds_type": "influxdb", + "ds_url": "https://influx.company.com:8086", + "database": "telegraf", + "time_interval": ">10s", + "tls_ca_cert": "/etc/ssl/certs/ca.pem", + } + ) module = grafana_datasource.setup_module_object() payload = grafana_datasource.get_datasource_payload(module.params) self.assertEqual(payload, expected_payload) def test_payload_elastic(self): expected_payload = { - 'access': 'proxy', - 'basicAuth': True, - 'basicAuthUser': 'grafana', - 'database': '[logstash_]YYYY.MM.DD', - 'isDefault': False, - 'jsonData': { - 'esVersion': 56, - 'interval': 'Daily', - 'maxConcurrentShardRequests': 42, - 'timeField': '@timestamp', - 'timeInterval': '1m', - 'tlsAuth': False, - 'tlsAuthWithCACert': True + "access": "proxy", + "basicAuth": True, + "basicAuthUser": "grafana", + "database": "[logstash_]YYYY.MM.DD", + "isDefault": False, + "jsonData": { + "esVersion": 56, + "interval": "Daily", + "maxConcurrentShardRequests": 42, + "timeField": "@timestamp", + "timeInterval": "1m", + "tlsAuth": False, + "tlsAuthWithCACert": True, }, - 'name': 'datasource-elastic', - 'uid': 'xyz123', - 'orgId': 1, - 'secureJsonData': { - 'basicAuthPassword': 'grafana', - 'tlsCACert': '/etc/ssl/certs/ca.pem' + "name": "datasource-elastic", + "uid": "xyz123", + "orgId": 1, + "secureJsonData": { + "basicAuthPassword": "grafana", + "tlsCACert": "/etc/ssl/certs/ca.pem", }, - 'type': 'elasticsearch', - 'url': 'https://elastic.company.com:9200', - 'user': '', - 'withCredentials': False + "type": "elasticsearch", + "url": "https://elastic.company.com:9200", + "user": "", + "withCredentials": False, } - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'admin', - 'name': 'datasource-elastic', - 'uid': 'xyz123', - 'ds_type': 'elasticsearch', - 'ds_url': 'https://elastic.company.com:9200', - 'database': '[logstash_]YYYY.MM.DD', - 'basic_auth_user': 'grafana', - 'basic_auth_password': 'grafana', - 'time_field': '@timestamp', - 'time_interval': '1m', - 'interval': 'Daily', - 'es_version': 56, - 'max_concurrent_shard_requests': 42, - 'tls_ca_cert': '/etc/ssl/certs/ca.pem' - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "admin", + "name": "datasource-elastic", + "uid": "xyz123", + "ds_type": "elasticsearch", + "ds_url": "https://elastic.company.com:9200", + "database": "[logstash_]YYYY.MM.DD", + "basic_auth_user": "grafana", + "basic_auth_password": "grafana", + "time_field": "@timestamp", + "time_interval": "1m", + "interval": "Daily", + "es_version": 56, + "max_concurrent_shard_requests": 42, + "tls_ca_cert": "/etc/ssl/certs/ca.pem", + } + ) module = grafana_datasource.setup_module_object() payload = grafana_datasource.get_datasource_payload(module.params) self.assertEqual(payload, expected_payload) diff --git a/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py b/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py index b3b025c4..ec691a46 100644 --- a/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py +++ b/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py @@ -1,4 +1,4 @@ -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function from unittest import TestCase from unittest.mock import patch, MagicMock @@ -53,14 +53,13 @@ def run_command_uninstall_again(): class GrafanaPlugin(TestCase): - - @patch('ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin" + ) def test_plugin_install_zip(self, mock_grafana_cli_bin): mock_grafana_cli_bin.return_value = "grafana-cli plugins" - params = { - "name": "alexanderzobnin-zabbix-app" - } + params = {"name": "alexanderzobnin-zabbix-app"} module = MagicMock() module.run_command.return_value = run_command_install_zip() @@ -68,13 +67,13 @@ def test_plugin_install_zip(self, mock_grafana_cli_bin): result = grafana_plugin.get_grafana_plugin_version(module, params) self.assertEqual(result, None) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin" + ) def test_plugin_ls(self, mock_grafana_cli_bin): mock_grafana_cli_bin.return_value = "grafana-cli plugins" - params = { - "name": "alexanderzobnin-zabbix-app" - } + params = {"name": "alexanderzobnin-zabbix-app"} module = MagicMock() module.run_command.return_value = run_command_ls() @@ -82,13 +81,13 @@ def test_plugin_ls(self, mock_grafana_cli_bin): result = grafana_plugin.get_grafana_plugin_version(module, params) self.assertEqual(result, "3.10.5") - @patch('ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin" + ) def test_plugin_uninstall(self, mock_grafana_cli_bin): mock_grafana_cli_bin.return_value = "grafana-cli plugins" - params = { - "name": "alexanderzobnin-zabbix-app" - } + params = {"name": "alexanderzobnin-zabbix-app"} module = MagicMock() module.run_command.return_value = run_command_uninstall() @@ -96,13 +95,13 @@ def test_plugin_uninstall(self, mock_grafana_cli_bin): result = grafana_plugin.get_grafana_plugin_version(module, params) self.assertEqual(result, None) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_plugin.grafana_cli_bin" + ) def test_plugin_uninstall_again(self, mock_grafana_cli_bin): mock_grafana_cli_bin.return_value = "grafana-cli plugins" - params = { - "name": "alexanderzobnin-zabbix-app" - } + params = {"name": "alexanderzobnin-zabbix-app"} module = MagicMock() module.run_command.return_value = run_command_uninstall_again() diff --git a/tests/unit/modules/grafana/grafana_team/test_grafana_team.py b/tests/unit/modules/grafana/grafana_team/test_grafana_team.py index 491b863d..523bdaef 100644 --- a/tests/unit/modules/grafana/grafana_team/test_grafana_team.py +++ b/tests/unit/modules/grafana/grafana_team/test_grafana_team.py @@ -1,4 +1,4 @@ -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function from unittest import TestCase from unittest.mock import patch @@ -21,30 +21,32 @@ def read(self): def exit_json(*args, **kwargs): """function to patch over exit_json; package return data into an exception""" - if 'changed' not in kwargs: - kwargs['changed'] = False + if "changed" not in kwargs: + kwargs["changed"] = False raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): """function to patch over fail_json; package return data into an exception""" - kwargs['failed'] = True + kwargs["failed"] = True raise AnsibleFailJson(kwargs) class AnsibleExitJson(Exception): """Exception class to be raised by module.exit_json and caught by the test case""" + pass class AnsibleFailJson(Exception): """Exception class to be raised by module.fail_json and caught by the test case""" + pass def set_module_args(args): """prepare arguments so that they will be picked up during module creation""" - args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) + args = json.dumps({"ANSIBLE_MODULE_ARGS": args}) basic._ANSIBLE_ARGS = to_bytes(args) @@ -65,7 +67,10 @@ def get_low_version_resp(): def team_exists_resp(): - server_response = json.dumps({"totalCount": 1, "teams": [{"name": "MyTestTeam", "email": "email@test.com"}]}, sort_keys=True) + server_response = json.dumps( + {"totalCount": 1, "teams": [{"name": "MyTestTeam", "email": "email@test.com"}]}, + sort_keys=True, + ) return (MockedReponse(server_response), {"status": 200}) @@ -90,21 +95,26 @@ def team_deleted_resp(): def team_members_resp(): - server_response = json.dumps([{ - "orgId": 1, - "teamId": 2, - "userId": 3, - "email": "user1@email.com", - "login": "user1", - "avatarUrl": r"\/avatar\/1b3c32f6386b0185c40d359cdc733a79" - }, { - "orgId": 1, - "teamId": 2, - "userId": 2, - "email": "user2@email.com", - "login": "user2", - "avatarUrl": r"\/avatar\/cad3c68da76e45d10269e8ef02f8e73e" - }]) + server_response = json.dumps( + [ + { + "orgId": 1, + "teamId": 2, + "userId": 3, + "email": "user1@email.com", + "login": "user1", + "avatarUrl": r"\/avatar\/1b3c32f6386b0185c40d359cdc733a79", + }, + { + "orgId": 1, + "teamId": 2, + "userId": 2, + "email": "user2@email.com", + "login": "user2", + "avatarUrl": r"\/avatar\/cad3c68da76e45d10269e8ef02f8e73e", + }, + ] + ) return (MockedReponse(server_response), {"status": 200}) @@ -124,12 +134,11 @@ def delete_team_member_resp(): class GrafanaTeamsTest(TestCase): - def setUp(self): self.authorization = basic_auth_header("admin", "admin") - self.mock_module_helper = patch.multiple(basic.AnsibleModule, - exit_json=exit_json, - fail_json=fail_json) + 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) @@ -139,112 +148,152 @@ def test_module_setup_fails_without_params(self): with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - err, arg_list = result.exception.args[0]['msg'].split(':') - missing_args = [item.strip() for item in arg_list.split(',')] - self.assertEqual(err, 'missing required arguments') + err, arg_list = result.exception.args[0]["msg"].split(":") + missing_args = [item.strip() for item in arg_list.split(",")] + self.assertEqual(err, "missing required arguments") self.assertEqual(arg_list, ["name", "email", "url"]) def test_module_setup_fails_without_name(self): - set_module_args({ - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + {"email": "email@test.com", "url": "http://grafana.example.com"} + ) with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertEqual(result.exception.args[0]['msg'], 'missing required arguments: name') + self.assertEqual( + result.exception.args[0]["msg"], "missing required arguments: name" + ) def test_module_setup_fails_without_email(self): - set_module_args({ - 'name': 'MyTestTeam', - 'url': 'http://grafana.example.com' - }) + set_module_args({"name": "MyTestTeam", "url": "http://grafana.example.com"}) with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertEqual(result.exception.args[0]['msg'], 'missing required arguments: email') + self.assertEqual( + result.exception.args[0]["msg"], "missing required arguments: email" + ) def test_module_setup_fails_without_url(self): - set_module_args({ - 'name': 'MyTestTeam', - 'email': 'email@test.com', - }) + set_module_args( + { + "name": "MyTestTeam", + "email": "email@test.com", + } + ) with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertEqual(result.exception.args[0]['msg'], 'missing required arguments: url') + self.assertEqual( + result.exception.args[0]["msg"], "missing required arguments: url" + ) def test_module_setup_fails_with_mutually_exclusive_auth_methods(self): - set_module_args({ - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com', - 'grafana_user': 'admin', - 'grafana_api_key': 'random_api_key', - }) + set_module_args( + { + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + "grafana_user": "admin", + "grafana_api_key": "random_api_key", + } + ) with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertEqual(result.exception.args[0]['msg'], 'parameters are mutually exclusive: url_username|grafana_api_key') - - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') + self.assertEqual( + result.exception.args[0]["msg"], + "parameters are mutually exclusive: url_username|grafana_api_key", + ) + + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) def test_module_fails_with_low_grafana_version(self, mock_get_version): - set_module_args({ - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com', - 'grafana_user': 'admin', - 'grafana_password': 'admin', - }) + set_module_args( + { + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + "grafana_user": "admin", + "grafana_password": "admin", + } + ) module = grafana_team.setup_module_object() mock_get_version.return_value = get_low_version_resp() with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertEqual(result.exception.args[0]['msg'], 'Teams API is available starting Grafana v5') - - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') - def test_module_failure_with_unauthorized_resp(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com', - }) + self.assertEqual( + result.exception.args[0]["msg"], + "Teams API is available starting Grafana v5", + ) + + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) + def test_module_failure_with_unauthorized_resp( + self, mock_fetch_url, mock_get_version + ): + set_module_args( + { + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = unauthorized_resp() mock_get_version.return_value = get_version_resp() with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertTrue(result.exception.args[0]['msg'].startswith('Unauthorized to perform action')) - - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') - def test_module_failure_with_permission_denied_resp(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com', - }) + self.assertTrue( + result.exception.args[0]["msg"].startswith("Unauthorized to perform action") + ) + + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) + def test_module_failure_with_permission_denied_resp( + self, mock_fetch_url, mock_get_version + ): + set_module_args( + { + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = permission_denied_resp() mock_get_version.return_value = get_version_resp() with self.assertRaises(AnsibleFailJson) as result: grafana_team.main() - self.assertTrue(result.exception.args[0]['msg'].startswith('Permission Denied')) - - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + self.assertTrue(result.exception.args[0]["msg"].startswith("Permission Denied")) + + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_get_team_method_with_existing_team(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_exists_resp() mock_get_version.return_value = get_version_resp() @@ -252,21 +301,34 @@ def test_get_team_method_with_existing_team(self, mock_fetch_url, mock_get_versi grafana_iface = grafana_team.GrafanaTeamInterface(module) res = grafana_iface.get_team("MyTestTeam") mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/search?name=MyTestTeam', + module, + "http://grafana.example.com/api/teams/search?name=MyTestTeam", data=None, - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='GET') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="GET", + ) self.assertEquals(res, {"email": "email@test.com", "name": "MyTestTeam"}) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') - def test_get_team_method_with_non_existing_team(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) + def test_get_team_method_with_non_existing_team( + self, mock_fetch_url, mock_get_version + ): + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_not_found_resp() mock_get_version.return_value = get_version_resp() @@ -274,21 +336,32 @@ def test_get_team_method_with_non_existing_team(self, mock_fetch_url, mock_get_v grafana_iface = grafana_team.GrafanaTeamInterface(module) res = grafana_iface.get_team("MyTestTeam") mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/search?name=MyTestTeam', + module, + "http://grafana.example.com/api/teams/search?name=MyTestTeam", data=None, - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='GET') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="GET", + ) self.assertEquals(res, None) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_create_team_method(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_created_resp() mock_get_version.return_value = get_version_resp() @@ -297,21 +370,34 @@ def test_create_team_method(self, mock_fetch_url, mock_get_version): res = grafana_iface.create_team("MyTestTeam", "email@test.com") mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams', - data=json.dumps({"email": "email@test.com", "name": "MyTestTeam"}, sort_keys=True), - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='POST') + module, + "http://grafana.example.com/api/teams", + data=json.dumps( + {"email": "email@test.com", "name": "MyTestTeam"}, sort_keys=True + ), + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="POST", + ) self.assertEquals(res, {"message": "Team created", "teamId": 2}) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_update_team_method(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_updated_resp() mock_get_version.return_value = get_version_resp() @@ -319,21 +405,34 @@ def test_update_team_method(self, mock_fetch_url, mock_get_version): grafana_iface = grafana_team.GrafanaTeamInterface(module) res = grafana_iface.update_team(2, "MyTestTeam", "email@test.com") mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/2', - data=json.dumps({"email": "email@test.com", "name": "MyTestTeam"}, sort_keys=True), - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='PUT') + module, + "http://grafana.example.com/api/teams/2", + data=json.dumps( + {"email": "email@test.com", "name": "MyTestTeam"}, sort_keys=True + ), + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="PUT", + ) self.assertEquals(res, {"message": "Team updated"}) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_delete_team_method(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'absent', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "absent", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_deleted_resp() mock_get_version.return_value = get_version_resp() @@ -341,21 +440,32 @@ def test_delete_team_method(self, mock_fetch_url, mock_get_version): grafana_iface = grafana_team.GrafanaTeamInterface(module) res = grafana_iface.delete_team(2) mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/2', + module, + "http://grafana.example.com/api/teams/2", data=None, - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='DELETE') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="DELETE", + ) self.assertEquals(res, {"message": "Team deleted"}) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_get_team_members_method(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_members_resp() mock_get_version.return_value = get_version_resp() @@ -363,21 +473,34 @@ def test_get_team_members_method(self, mock_fetch_url, mock_get_version): grafana_iface = grafana_team.GrafanaTeamInterface(module) res = grafana_iface.get_team_members(2) mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/2/members', + module, + "http://grafana.example.com/api/teams/2/members", data=None, - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='GET') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="GET", + ) self.assertEquals(res, ["user1@email.com", "user2@email.com"]) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') - def test_get_team_members_method_no_members_returned(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) + def test_get_team_members_method_no_members_returned( + self, mock_fetch_url, mock_get_version + ): + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = team_members_no_members_resp() mock_get_version.return_value = get_version_resp() @@ -385,58 +508,89 @@ def test_get_team_members_method_no_members_returned(self, mock_fetch_url, mock_ grafana_iface = grafana_team.GrafanaTeamInterface(module) res = grafana_iface.get_team_members(2) mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/2/members', + module, + "http://grafana.example.com/api/teams/2/members", data=None, - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='GET') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="GET", + ) self.assertEquals(res, []) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_add_team_member_method(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = add_team_member_resp() mock_get_version.return_value = get_version_resp() grafana_iface = grafana_team.GrafanaTeamInterface(module) - with patch.object(grafana_team.GrafanaTeamInterface, 'get_user_id_from_mail') as mock_get_user_id_from_mail: + with patch.object( + grafana_team.GrafanaTeamInterface, "get_user_id_from_mail" + ) as mock_get_user_id_from_mail: mock_get_user_id_from_mail.return_value = 42 res = grafana_iface.add_team_member(2, "another@test.com") mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/2/members', - data=json.dumps({'userId': 42}), - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='POST') + module, + "http://grafana.example.com/api/teams/2/members", + data=json.dumps({"userId": 42}), + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="POST", + ) self.assertEquals(res, None) - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version') - @patch('ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.GrafanaTeamInterface.get_version" + ) + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_team.fetch_url" + ) def test_delete_team_member_method(self, mock_fetch_url, mock_get_version): - set_module_args({ - 'state': 'present', - 'name': 'MyTestTeam', - 'email': 'email@test.com', - 'url': 'http://grafana.example.com' - }) + set_module_args( + { + "state": "present", + "name": "MyTestTeam", + "email": "email@test.com", + "url": "http://grafana.example.com", + } + ) module = grafana_team.setup_module_object() mock_fetch_url.return_value = delete_team_member_resp() mock_get_version.return_value = get_version_resp() grafana_iface = grafana_team.GrafanaTeamInterface(module) - with patch.object(grafana_team.GrafanaTeamInterface, 'get_user_id_from_mail') as mock_get_user_id_from_mail: + with patch.object( + grafana_team.GrafanaTeamInterface, "get_user_id_from_mail" + ) as mock_get_user_id_from_mail: mock_get_user_id_from_mail.return_value = 42 res = grafana_iface.delete_team_member(2, "another@test.com") mock_fetch_url.assert_called_once_with( - module, 'http://grafana.example.com/api/teams/2/members/42', + module, + "http://grafana.example.com/api/teams/2/members/42", data=None, - headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, - method='DELETE') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="DELETE", + ) self.assertEquals(res, None) def test_diff_members_function(self): @@ -444,4 +598,6 @@ def test_diff_members_function(self): list2 = ["bar@example.com", "random@example.com"] res = grafana_team.diff_members(list1, list2) - self.assertEquals(res, {"to_del": ["random@example.com"], "to_add": ["foo@example.com"]}) + self.assertEquals( + res, {"to_del": ["random@example.com"], "to_add": ["foo@example.com"]} + ) diff --git a/tests/unit/modules/grafana/grafana_user/test_grafana_user.py b/tests/unit/modules/grafana/grafana_user/test_grafana_user.py index 80c51409..7468fa42 100644 --- a/tests/unit/modules/grafana/grafana_user/test_grafana_user.py +++ b/tests/unit/modules/grafana/grafana_user/test_grafana_user.py @@ -1,4 +1,4 @@ -from __future__ import (absolute_import, division, print_function) +from __future__ import absolute_import, division, print_function from unittest import TestCase from unittest.mock import call, patch @@ -21,30 +21,32 @@ def read(self): def exit_json(*args, **kwargs): """function to patch over exit_json; package return data into an exception""" - if 'changed' not in kwargs: - kwargs['changed'] = False + if "changed" not in kwargs: + kwargs["changed"] = False raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): """function to patch over fail_json; package return data into an exception""" - kwargs['failed'] = True + kwargs["failed"] = True raise AnsibleFailJson(kwargs) class AnsibleExitJson(Exception): """Exception class to be raised by module.exit_json and caught by the test case""" + pass class AnsibleFailJson(Exception): """Exception class to be raised by module.fail_json and caught by the test case""" + pass def set_module_args(args): """prepare arguments so that they will be picked up during module creation""" - args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) + args = json.dumps({"ANSIBLE_MODULE_ARGS": args}) basic._ANSIBLE_ARGS = to_bytes(args) @@ -59,75 +61,94 @@ def user_already_exists_resp(): def user_created_resp(): - server_response = json.dumps({ - "id": 2, - "email": "robin@gotham.com", - "name": "Robin", - "login": "adrobinmin", - "theme": "light", - "orgId": 1, - "isGrafanaAdmin": False, - "isDisabled": False, - "isExternal": False, - "authLabels": None, - "updatedAt": "2019-09-25T14:44:37+01:00", - "createdAt": "2019-09-25T14:44:37+01:00" - }, sort_keys=True) + server_response = json.dumps( + { + "id": 2, + "email": "robin@gotham.com", + "name": "Robin", + "login": "adrobinmin", + "theme": "light", + "orgId": 1, + "isGrafanaAdmin": False, + "isDisabled": False, + "isExternal": False, + "authLabels": None, + "updatedAt": "2019-09-25T14:44:37+01:00", + "createdAt": "2019-09-25T14:44:37+01:00", + }, + sort_keys=True, + ) return (MockedReponse(server_response), {"status": 200}) class GrafanaUserTest(TestCase): - 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 = patch.multiple( + basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json + ) self.mock_module_helper.start() self.addCleanup(self.mock_module_helper.stop) # create an already existing user - @patch('ansible_collections.community.grafana.plugins.modules.grafana_user.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_user.fetch_url" + ) def test_create_user_existing_user(self, mock_fetch_url): - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'changeme', - 'name': 'Joker', - 'email': 'joker@gotham.com', - 'login': 'joker', - 'password': 'oups', - 'state': 'present' - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "changeme", + "name": "Joker", + "email": "joker@gotham.com", + "login": "joker", + "password": "oups", + "state": "present", + } + ) module = grafana_user.setup_module_object() mock_fetch_url.return_value = user_already_exists_resp() grafana_iface = grafana_user.GrafanaUserInterface(module) with self.assertRaises(AnsibleFailJson): - grafana_iface.create_user( - 'Joker', 'joker@gotham.com', 'joker', 'oups') + grafana_iface.create_user("Joker", "joker@gotham.com", "joker", "oups") mock_fetch_url.assert_called_once_with( module, - 'https://grafana.example.com/api/admin/users', - data=json.dumps({'name': 'Joker', 'email': 'joker@gotham.com', - 'login': 'joker', 'password': 'oups'}, sort_keys=True), - headers={'Content-Type': 'application/json', - 'Authorization': self.authorization}, - method='POST') + "https://grafana.example.com/api/admin/users", + data=json.dumps( + { + "name": "Joker", + "email": "joker@gotham.com", + "login": "joker", + "password": "oups", + }, + sort_keys=True, + ), + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="POST", + ) # create a new user - @patch('ansible_collections.community.grafana.plugins.modules.grafana_user.fetch_url') + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_user.fetch_url" + ) def test_create_user_new_user(self, mock_fetch_url): - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'changeme', - 'name': 'Robin', - 'email': 'robin@gotham.com', - 'login': 'robin', - 'password': 'oups', - 'state': 'present' - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "changeme", + "name": "Robin", + "email": "robin@gotham.com", + "login": "robin", + "password": "oups", + "state": "present", + } + ) module = grafana_user.setup_module_object() mock_fetch_url.return_value = user_created_resp() @@ -136,54 +157,71 @@ def test_create_user_new_user(self, mock_fetch_url): # first call to create user call( module, - 'https://grafana.example.com/api/admin/users', - data=json.dumps({'name': 'Robin', 'email': 'robin@gotham.com', - 'login': 'robin', 'password': 'oups'}, sort_keys=True), - headers={'Content-Type': 'application/json', - 'Authorization': self.authorization}, - method='POST'), - + "https://grafana.example.com/api/admin/users", + data=json.dumps( + { + "name": "Robin", + "email": "robin@gotham.com", + "login": "robin", + "password": "oups", + }, + sort_keys=True, + ), + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="POST", + ), # second call to return created user call( module, - 'https://grafana.example.com/api/users/lookup?loginOrEmail=robin', + "https://grafana.example.com/api/users/lookup?loginOrEmail=robin", data=None, - headers={'Content-Type': 'application/json', - 'Authorization': self.authorization}, - method='GET'), + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="GET", + ), ] grafana_iface = grafana_user.GrafanaUserInterface(module) - result = grafana_iface.create_user( - 'Robin', 'robin@gotham.com', 'robin', 'oups') - - mock_fetch_url.assert_has_calls( - expected_fetch_url_calls, any_order=False) - - self.assertEquals(result, { - "id": 2, - "email": "robin@gotham.com", - "name": "Robin", - "login": "adrobinmin", - "theme": "light", - "orgId": 1, - "isGrafanaAdmin": False, - "isDisabled": False, - "isExternal": False, - "authLabels": None, - "updatedAt": "2019-09-25T14:44:37+01:00", - "createdAt": "2019-09-25T14:44:37+01:00" - }) - - @patch('ansible_collections.community.grafana.plugins.modules.grafana_user.fetch_url') + result = grafana_iface.create_user("Robin", "robin@gotham.com", "robin", "oups") + + mock_fetch_url.assert_has_calls(expected_fetch_url_calls, any_order=False) + + self.assertEquals( + result, + { + "id": 2, + "email": "robin@gotham.com", + "name": "Robin", + "login": "adrobinmin", + "theme": "light", + "orgId": 1, + "isGrafanaAdmin": False, + "isDisabled": False, + "isExternal": False, + "authLabels": None, + "updatedAt": "2019-09-25T14:44:37+01:00", + "createdAt": "2019-09-25T14:44:37+01:00", + }, + ) + + @patch( + "ansible_collections.community.grafana.plugins.modules.grafana_user.fetch_url" + ) def test_delete_user(self, mock_fetch_url): - set_module_args({ - 'url': 'https://grafana.example.com', - 'url_username': 'admin', - 'url_password': 'changeme', - 'login': 'batman', - 'state': 'absent' - }) + set_module_args( + { + "url": "https://grafana.example.com", + "url_username": "admin", + "url_password": "changeme", + "login": "batman", + "state": "absent", + } + ) module = grafana_user.setup_module_object() mock_fetch_url.return_value = user_deleted_resp() @@ -192,9 +230,12 @@ def test_delete_user(self, mock_fetch_url): result = grafana_iface.delete_user(user_id) mock_fetch_url.assert_called_once_with( module, - 'https://grafana.example.com/api/admin/users/42', + "https://grafana.example.com/api/admin/users/42", data=None, - headers={'Content-Type': 'application/json', - 'Authorization': self.authorization}, - method='DELETE') + headers={ + "Content-Type": "application/json", + "Authorization": self.authorization, + }, + method="DELETE", + ) self.assertEquals(result, {"message": "User deleted"}) From 338d3c20e3dba9e23874ffb7b385a0fb082b7128 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:04:22 +0100 Subject: [PATCH 27/40] feat: added org_name param and orga by name function --- plugins/modules/grafana_datasource.py | 202 +++++++++++--------------- 1 file changed, 81 insertions(+), 121 deletions(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 468313cb..11c15a5d 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -128,9 +128,9 @@ default: false org_id: description: - - Grafana Organisation ID in which the datasource should be created. + - Grafana organization ID in which the datasource should be created. - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only - belong to one organisation. + belong to one organization. default: 1 type: int state: @@ -687,10 +687,10 @@ def __init__(self, module): "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"]) + self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) + if module.params['org_name']: + module.params['org_id'] = organization_by_name(module.params['org_name']) + self.switch_organization(module.params['org_id']) # }}} def _send_request(self, url, data=None, headers=None, method="GET"): @@ -721,10 +721,19 @@ def _send_request(self, url, data=None, headers=None, method="GET"): % (status_code, url, data), ) - def switch_organisation(self, org_id): + def switch_organization(self, org_id): url = "/api/user/using/%d" % org_id response = self._send_request(url, headers=self.headers, method="POST") + def organization_by_name(self, org_name): + url = "/api/user/orgs" + organizations = self._send_request(url, headers=self.headers, method='GET') + for org in organizations: + if org['name'] == org_name: + return org['orgId'] + + return self._module.fail_json(failed=True, msg="Current user isn't member of organization: %s" % org_name) + def datasource_by_name(self, name): datasource_exists = False ds = {} @@ -748,125 +757,76 @@ def setup_module_object(): argument_spec = base.grafana_argument_spec() argument_spec.update( - name=dict(required=True, type="str"), - uid=dict(type="str"), - ds_type=dict( - choices=[ - "graphite", - "prometheus", - "elasticsearch", - "influxdb", - "opentsdb", - "mysql", - "postgres", - "cloudwatch", - "alexanderzobnin-zabbix-datasource", - "grafana-azure-monitor-datasource", - "camptocamp-prometheus-alertmanager-datasource", - "sni-thruk-datasource", - "redis-datasource", - "loki", - "tempo", - ] - ), - ds_url=dict(type="str"), - access=dict(default="proxy", choices=["proxy", "direct"]), - database=dict(type="str", default=""), - user=dict(default="", type="str"), - password=dict(default="", no_log=True, type="str"), - basic_auth_user=dict(type="str"), - basic_auth_password=dict(type="str", no_log=True), - with_credentials=dict(default=False, type="bool"), - tls_client_cert=dict(type="str", no_log=True), - tls_client_key=dict(type="str", no_log=True), - tls_ca_cert=dict(type="str", no_log=True), - tls_skip_verify=dict(type="bool", default=False), - is_default=dict(default=False, type="bool"), - org_id=dict(default=1, type="int"), - es_version=dict( - type="str", - default="7.10+", - choices=["2", "5", "56", "60", "70", "7.7+", "7.10+", "8.0+"], - ), - max_concurrent_shard_requests=dict(type="int", default=256), - time_field=dict(default="@timestamp", type="str"), - time_interval=dict(type="str"), - interval=dict( - type="str", - choices=["", "Hourly", "Daily", "Weekly", "Monthly", "Yearly"], - default="", - ), - tsdb_version=dict(type="int", default=1, choices=[1, 2, 3]), - tsdb_resolution=dict( - type="str", default="second", choices=["second", "millisecond"] - ), - sslmode=dict( - default="disable", - choices=["disable", "require", "verify-ca", "verify-full"], - ), - trends=dict(default=False, type="bool"), - aws_auth_type=dict( - default="keys", choices=["keys", "credentials", "arn", "default"] - ), - aws_default_region=dict( - default="us-east-1", - choices=[ - "ap-northeast-1", - "ap-northeast-2", - "ap-southeast-1", - "ap-southeast-2", - "ap-south-1", - "ca-central-1", - "cn-north-1", - "cn-northwest-1", - "eu-central-1", - "eu-west-1", - "eu-west-2", - "eu-west-3", - "sa-east-1", - "us-east-1", - "us-east-2", - "us-gov-west-1", - "us-west-1", - "us-west-2", - ], - ), - aws_access_key=dict(default="", no_log=True, type="str"), - aws_secret_key=dict(default="", no_log=True, type="str"), - aws_credentials_profile=dict(default="", type="str"), - aws_assume_role_arn=dict(default="", type="str"), - aws_custom_metrics_namespaces=dict(type="str"), - azure_cloud=dict( - type="str", - default="azuremonitor", - choices=[ - "azuremonitor", - "chinaazuremonitor", - "govazuremonitor", - "germanyazuremonitor", - ], - ), - azure_tenant=dict(type="str"), - azure_client=dict(type="str"), - azure_secret=dict(type="str", no_log=True), - zabbix_user=dict(type="str"), - zabbix_password=dict(type="str", no_log=True), - additional_json_data=dict(type="dict", default={}, required=False), - additional_secure_json_data=dict(type="dict", default={}, required=False), - enforce_secure_data=dict(type="bool", default=False, required=False), + name=dict(required=True, type='str'), + uid=dict(type='str'), + ds_type=dict(choices=['graphite', + 'prometheus', + 'elasticsearch', + 'influxdb', + 'opentsdb', + 'mysql', + 'postgres', + 'cloudwatch', + 'alexanderzobnin-zabbix-datasource', + 'grafana-azure-monitor-datasource', + 'camptocamp-prometheus-alertmanager-datasource', + 'sni-thruk-datasource', + 'redis-datasource', + 'loki']), + ds_url=dict(type='str'), + access=dict(default='proxy', choices=['proxy', 'direct']), + database=dict(type='str', default=""), + user=dict(default='', type='str'), + password=dict(default='', no_log=True, type='str'), + basic_auth_user=dict(type='str'), + basic_auth_password=dict(type='str', no_log=True), + with_credentials=dict(default=False, type='bool'), + tls_client_cert=dict(type='str', no_log=True), + tls_client_key=dict(type='str', no_log=True), + tls_ca_cert=dict(type='str', no_log=True), + tls_skip_verify=dict(type='bool', default=False), + is_default=dict(default=False, type='bool'), + org_id=dict(default=1, type='int'), + org_name=dict(type='str'), + es_version=dict(type='str', default="7.10+", choices=["2", "5", "56", "60", + "70", "7.7+", "7.10+", + "8.0+"]), + max_concurrent_shard_requests=dict(type='int', default=256), + time_field=dict(default='@timestamp', type='str'), + time_interval=dict(type='str'), + interval=dict(type='str', choices=['', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'], default=''), + tsdb_version=dict(type='int', default=1, choices=[1, 2, 3]), + tsdb_resolution=dict(type='str', default='second', choices=['second', 'millisecond']), + sslmode=dict(default='disable', choices=['disable', 'require', 'verify-ca', 'verify-full']), + trends=dict(default=False, type='bool'), + aws_auth_type=dict(default='keys', choices=['keys', 'credentials', 'arn', 'default']), + aws_default_region=dict(default='us-east-1', choices=['ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1', + 'ca-central-1', + 'cn-north-1', 'cn-northwest-1', + 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', + 'sa-east-1', + 'us-east-1', 'us-east-2', 'us-gov-west-1', 'us-west-1', 'us-west-2']), + aws_access_key=dict(default='', no_log=True, type='str'), + aws_secret_key=dict(default='', no_log=True, type='str'), + aws_credentials_profile=dict(default='', type='str'), + aws_assume_role_arn=dict(default='', type='str'), + aws_custom_metrics_namespaces=dict(type='str'), + azure_cloud=dict(type='str', default='azuremonitor', choices=['azuremonitor', 'chinaazuremonitor', 'govazuremonitor', 'germanyazuremonitor']), + azure_tenant=dict(type='str'), + azure_client=dict(type='str'), + azure_secret=dict(type='str', no_log=True), + zabbix_user=dict(type='str'), + zabbix_password=dict(type='str', no_log=True), + additional_json_data=dict(type='dict', default={}, required=False), + additional_secure_json_data=dict(type='dict', default={}, required=False), + enforce_secure_data=dict(type='bool', default=False, required=False) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, - required_together=[ - ["url_username", "url_password", "org_id"], - ["tls_client_cert", "tls_client_key"], - ], - mutually_exclusive=[ - ["url_username", "grafana_api_key"], - ["tls_ca_cert", "tls_skip_verify"], - ], + required_together=[['url_username', 'url_password', 'org_id'], ['tls_client_cert', 'tls_client_key']], + mutually_exclusive=[['url_username', 'grafana_api_key'], ['tls_ca_cert', 'tls_skip_verify'], ['org_id', 'org_name']], required_if=[ ["state", "present", ["ds_type", "ds_url"]], ["ds_type", "opentsdb", ["tsdb_version", "tsdb_resolution"]], From 352f5075de57fb2061aa4684c4394a962caaed8f Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:28:06 +0100 Subject: [PATCH 28/40] fix: func call --- plugins/modules/grafana_datasource.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 11c15a5d..6606c493 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -689,7 +689,7 @@ def __init__(self, module): else: self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) if module.params['org_name']: - module.params['org_id'] = organization_by_name(module.params['org_name']) + module.params['org_id'] = self.organization_by_name(module.params['org_name']) self.switch_organization(module.params['org_id']) # }}} From f23efc2e07e290421ebc17dcf86eaa0fb3c810ed Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:33:07 +0100 Subject: [PATCH 29/40] docs: add org_name --- plugins/modules/grafana_datasource.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 6606c493..c3cdbc35 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -131,8 +131,16 @@ - Grafana organization ID in which the datasource should be created. - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only belong to one organization. + - Mutually exclusive with `org_name`. default: 1 type: int + org_name: + description: + - Grafana organization name in which the datasource should be created. + - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only + belong to one organization. + - Mutually exclusive with `org_id`. + type: str state: description: - Status of the datasource From 6c67d44b9b1cb3a97c5af59f8b57987235df38b3 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:34:28 +0100 Subject: [PATCH 30/40] docs: add changelog fragment --- changelogs/fragments/332-datasource-by-org-name.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelogs/fragments/332-datasource-by-org-name.yml diff --git a/changelogs/fragments/332-datasource-by-org-name.yml b/changelogs/fragments/332-datasource-by-org-name.yml new file mode 100644 index 00000000..0c8e265d --- /dev/null +++ b/changelogs/fragments/332-datasource-by-org-name.yml @@ -0,0 +1,4 @@ +--- + +minor_changes: + - Add parameter `org_name` to `grafana_datasource` From beb50b32fa9a3ded32226770b508f52931b175cc Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:36:03 +0100 Subject: [PATCH 31/40] chore: indention --- plugins/modules/grafana_datasource.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index c3cdbc35..24899f21 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -738,7 +738,7 @@ def organization_by_name(self, org_name): organizations = self._send_request(url, headers=self.headers, method='GET') for org in organizations: if org['name'] == org_name: - return org['orgId'] + return org['orgId'] return self._module.fail_json(failed=True, msg="Current user isn't member of organization: %s" % org_name) From 27361ca8df24739e22bf74f41d16e54995577a8d Mon Sep 17 00:00:00 2001 From: Moritz <15136847+Nemental@users.noreply.github.com> Date: Wed, 3 Jan 2024 16:36:31 +0100 Subject: [PATCH 32/40] typo Co-authored-by: Sebastian Gumprich --- plugins/modules/grafana_datasource.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 24899f21..5638db6b 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -138,7 +138,7 @@ description: - Grafana organization name in which the datasource should be created. - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only - belong to one organization. + belongs to one organization. - Mutually exclusive with `org_id`. type: str state: From 84051a49b4bf8501d865a3ce04f141596b007d7e Mon Sep 17 00:00:00 2001 From: Moritz <15136847+Nemental@users.noreply.github.com> Date: Wed, 3 Jan 2024 16:36:40 +0100 Subject: [PATCH 33/40] typo Co-authored-by: Sebastian Gumprich --- plugins/modules/grafana_datasource.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 5638db6b..920a4542 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -130,7 +130,7 @@ description: - Grafana organization ID in which the datasource should be created. - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only - belong to one organization. + belongs to one organization. - Mutually exclusive with `org_name`. default: 1 type: int From a4af2449157cba2653649681922d9e4bbfeaa581 Mon Sep 17 00:00:00 2001 From: Moritz <15136847+Nemental@users.noreply.github.com> Date: Wed, 3 Jan 2024 16:43:07 +0100 Subject: [PATCH 34/40] new var org_id for org switch Co-authored-by: Sebastian Gumprich --- plugins/modules/grafana_datasource.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 920a4542..68e4920c 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -696,9 +696,8 @@ def __init__(self, module): ) else: self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) - if module.params['org_name']: - module.params['org_id'] = self.organization_by_name(module.params['org_name']) - self.switch_organization(module.params['org_id']) + org_id = self.organization_by_name(module.params['org_name']) if module.params['org_name'] else module.params['org_id'] + self.switch_organization(org_id) # }}} def _send_request(self, url, data=None, headers=None, method="GET"): From 8d1edb27abab244eea7bcd79e9fd418c14cff8d9 Mon Sep 17 00:00:00 2001 From: Moritz <15136847+Nemental@users.noreply.github.com> Date: Wed, 3 Jan 2024 16:54:36 +0100 Subject: [PATCH 35/40] improve user org list check list comprehension Co-authored-by: Sebastian Gumprich --- plugins/modules/grafana_datasource.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 68e4920c..ff193e95 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -735,9 +735,9 @@ def switch_organization(self, org_id): def organization_by_name(self, org_name): url = "/api/user/orgs" organizations = self._send_request(url, headers=self.headers, method='GET') - for org in organizations: - if org['name'] == org_name: - return org['orgId'] + orga = next((org for org in organizations if org['name'] == org_name)) + if orga: + return orga['orgId'] return self._module.fail_json(failed=True, msg="Current user isn't member of organization: %s" % org_name) From ca5eea437b6a87a7719e18d47cfcc56fa3b8ef26 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Thu, 4 Jan 2024 09:07:20 +0100 Subject: [PATCH 36/40] chore: indent lines --- plugins/modules/grafana_datasource.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index ff193e95..9458c9b9 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -735,9 +735,9 @@ def switch_organization(self, org_id): def organization_by_name(self, org_name): url = "/api/user/orgs" organizations = self._send_request(url, headers=self.headers, method='GET') - orga = next((org for org in organizations if org['name'] == org_name)) - if orga: - return orga['orgId'] + orga = next((org for org in organizations if org['name'] == org_name)) + if orga: + return orga['orgId'] return self._module.fail_json(failed=True, msg="Current user isn't member of organization: %s" % org_name) From 2907e937a3f5ad8103e9b8492e174b26a4a09746 Mon Sep 17 00:00:00 2001 From: Nemental <15136847+Nemental@users.noreply.github.com> Date: Thu, 4 Jan 2024 10:37:24 +0100 Subject: [PATCH 37/40] style: formatting black --- plugins/modules/grafana_datasource.py | 202 +++++++++++++++++--------- 1 file changed, 130 insertions(+), 72 deletions(-) diff --git a/plugins/modules/grafana_datasource.py b/plugins/modules/grafana_datasource.py index 9458c9b9..1c0253b9 100644 --- a/plugins/modules/grafana_datasource.py +++ b/plugins/modules/grafana_datasource.py @@ -617,7 +617,6 @@ def get_datasource_payload(data): # datasource type related parameters if data["ds_type"] == "elasticsearch": - json_data["maxConcurrentShardRequests"] = data["max_concurrent_shard_requests"] json_data["timeField"] = data["time_field"] if data.get("interval"): @@ -695,8 +694,14 @@ def __init__(self, module): "Bearer %s" % module.params["grafana_api_key"] ) else: - self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) - org_id = self.organization_by_name(module.params['org_name']) if module.params['org_name'] else module.params['org_id'] + self.headers["Authorization"] = basic_auth_header( + module.params["url_username"], module.params["url_password"] + ) + org_id = ( + self.organization_by_name(module.params["org_name"]) + if module.params["org_name"] + else module.params["org_id"] + ) self.switch_organization(org_id) # }}} @@ -734,12 +739,14 @@ def switch_organization(self, org_id): def organization_by_name(self, org_name): url = "/api/user/orgs" - organizations = self._send_request(url, headers=self.headers, method='GET') - orga = next((org for org in organizations if org['name'] == org_name)) + organizations = self._send_request(url, headers=self.headers, method="GET") + orga = next((org for org in organizations if org["name"] == org_name)) if orga: - return orga['orgId'] + return orga["orgId"] - return self._module.fail_json(failed=True, msg="Current user isn't member of organization: %s" % org_name) + return self._module.fail_json( + failed=True, msg="Current user isn't member of organization: %s" % org_name + ) def datasource_by_name(self, name): datasource_exists = False @@ -764,76 +771,127 @@ def setup_module_object(): argument_spec = base.grafana_argument_spec() argument_spec.update( - name=dict(required=True, type='str'), - uid=dict(type='str'), - ds_type=dict(choices=['graphite', - 'prometheus', - 'elasticsearch', - 'influxdb', - 'opentsdb', - 'mysql', - 'postgres', - 'cloudwatch', - 'alexanderzobnin-zabbix-datasource', - 'grafana-azure-monitor-datasource', - 'camptocamp-prometheus-alertmanager-datasource', - 'sni-thruk-datasource', - 'redis-datasource', - 'loki']), - ds_url=dict(type='str'), - access=dict(default='proxy', choices=['proxy', 'direct']), - database=dict(type='str', default=""), - user=dict(default='', type='str'), - password=dict(default='', no_log=True, type='str'), - basic_auth_user=dict(type='str'), - basic_auth_password=dict(type='str', no_log=True), - with_credentials=dict(default=False, type='bool'), - tls_client_cert=dict(type='str', no_log=True), - tls_client_key=dict(type='str', no_log=True), - tls_ca_cert=dict(type='str', no_log=True), - tls_skip_verify=dict(type='bool', default=False), - is_default=dict(default=False, type='bool'), - org_id=dict(default=1, type='int'), - org_name=dict(type='str'), - es_version=dict(type='str', default="7.10+", choices=["2", "5", "56", "60", - "70", "7.7+", "7.10+", - "8.0+"]), - max_concurrent_shard_requests=dict(type='int', default=256), - time_field=dict(default='@timestamp', type='str'), - time_interval=dict(type='str'), - interval=dict(type='str', choices=['', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'], default=''), - tsdb_version=dict(type='int', default=1, choices=[1, 2, 3]), - tsdb_resolution=dict(type='str', default='second', choices=['second', 'millisecond']), - sslmode=dict(default='disable', choices=['disable', 'require', 'verify-ca', 'verify-full']), - trends=dict(default=False, type='bool'), - aws_auth_type=dict(default='keys', choices=['keys', 'credentials', 'arn', 'default']), - aws_default_region=dict(default='us-east-1', choices=['ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1', - 'ca-central-1', - 'cn-north-1', 'cn-northwest-1', - 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', - 'sa-east-1', - 'us-east-1', 'us-east-2', 'us-gov-west-1', 'us-west-1', 'us-west-2']), - aws_access_key=dict(default='', no_log=True, type='str'), - aws_secret_key=dict(default='', no_log=True, type='str'), - aws_credentials_profile=dict(default='', type='str'), - aws_assume_role_arn=dict(default='', type='str'), - aws_custom_metrics_namespaces=dict(type='str'), - azure_cloud=dict(type='str', default='azuremonitor', choices=['azuremonitor', 'chinaazuremonitor', 'govazuremonitor', 'germanyazuremonitor']), - azure_tenant=dict(type='str'), - azure_client=dict(type='str'), - azure_secret=dict(type='str', no_log=True), - zabbix_user=dict(type='str'), - zabbix_password=dict(type='str', no_log=True), - additional_json_data=dict(type='dict', default={}, required=False), - additional_secure_json_data=dict(type='dict', default={}, required=False), - enforce_secure_data=dict(type='bool', default=False, required=False) + name=dict(required=True, type="str"), + uid=dict(type="str"), + ds_type=dict( + choices=[ + "graphite", + "prometheus", + "elasticsearch", + "influxdb", + "opentsdb", + "mysql", + "postgres", + "cloudwatch", + "alexanderzobnin-zabbix-datasource", + "grafana-azure-monitor-datasource", + "camptocamp-prometheus-alertmanager-datasource", + "sni-thruk-datasource", + "redis-datasource", + "loki", + "tempo", + ] + ), + ds_url=dict(type="str"), + access=dict(default="proxy", choices=["proxy", "direct"]), + database=dict(type="str", default=""), + user=dict(default="", type="str"), + password=dict(default="", no_log=True, type="str"), + basic_auth_user=dict(type="str"), + basic_auth_password=dict(type="str", no_log=True), + with_credentials=dict(default=False, type="bool"), + tls_client_cert=dict(type="str", no_log=True), + tls_client_key=dict(type="str", no_log=True), + tls_ca_cert=dict(type="str", no_log=True), + tls_skip_verify=dict(type="bool", default=False), + is_default=dict(default=False, type="bool"), + org_id=dict(default=1, type="int"), + org_name=dict(type="str"), + es_version=dict( + type="str", + default="7.10+", + choices=["2", "5", "56", "60", "70", "7.7+", "7.10+", "8.0+"], + ), + max_concurrent_shard_requests=dict(type="int", default=256), + time_field=dict(default="@timestamp", type="str"), + time_interval=dict(type="str"), + interval=dict( + type="str", + choices=["", "Hourly", "Daily", "Weekly", "Monthly", "Yearly"], + default="", + ), + tsdb_version=dict(type="int", default=1, choices=[1, 2, 3]), + tsdb_resolution=dict( + type="str", default="second", choices=["second", "millisecond"] + ), + sslmode=dict( + default="disable", + choices=["disable", "require", "verify-ca", "verify-full"], + ), + trends=dict(default=False, type="bool"), + aws_auth_type=dict( + default="keys", choices=["keys", "credentials", "arn", "default"] + ), + aws_default_region=dict( + default="us-east-1", + choices=[ + "ap-northeast-1", + "ap-northeast-2", + "ap-southeast-1", + "ap-southeast-2", + "ap-south-1", + "ca-central-1", + "cn-north-1", + "cn-northwest-1", + "eu-central-1", + "eu-west-1", + "eu-west-2", + "eu-west-3", + "sa-east-1", + "us-east-1", + "us-east-2", + "us-gov-west-1", + "us-west-1", + "us-west-2", + ], + ), + aws_access_key=dict(default="", no_log=True, type="str"), + aws_secret_key=dict(default="", no_log=True, type="str"), + aws_credentials_profile=dict(default="", type="str"), + aws_assume_role_arn=dict(default="", type="str"), + aws_custom_metrics_namespaces=dict(type="str"), + azure_cloud=dict( + type="str", + default="azuremonitor", + choices=[ + "azuremonitor", + "chinaazuremonitor", + "govazuremonitor", + "germanyazuremonitor", + ], + ), + azure_tenant=dict(type="str"), + azure_client=dict(type="str"), + azure_secret=dict(type="str", no_log=True), + zabbix_user=dict(type="str"), + zabbix_password=dict(type="str", no_log=True), + additional_json_data=dict(type="dict", default={}, required=False), + additional_secure_json_data=dict(type="dict", default={}, required=False), + enforce_secure_data=dict(type="bool", default=False, required=False), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, - required_together=[['url_username', 'url_password', 'org_id'], ['tls_client_cert', 'tls_client_key']], - mutually_exclusive=[['url_username', 'grafana_api_key'], ['tls_ca_cert', 'tls_skip_verify'], ['org_id', 'org_name']], + required_together=[ + ["url_username", "url_password", "org_id"], + ["tls_client_cert", "tls_client_key"], + ], + mutually_exclusive=[ + ["url_username", "grafana_api_key"], + ["tls_ca_cert", "tls_skip_verify"], + ["org_id", "org_name"], + ], required_if=[ ["state", "present", ["ds_type", "ds_url"]], ["ds_type", "opentsdb", ["tsdb_version", "tsdb_resolution"]], From 89e42a1dc25da182c76083b9b1114ab1cfb98f00 Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Thu, 4 Jan 2024 10:18:51 +0100 Subject: [PATCH 38/40] fixup! fix linting with ansible-lint write --- galaxy.yml | 1 + meta/runtime.yml | 2 +- .../grafana_dashboard/defaults/main.yml | 6 +- .../tasks/dashboard-by-org-name.yml | 15 +- .../tasks/dashboard-export.yml | 12 +- .../tasks/dashboard-folder-destination.yml | 4 +- .../tasks/dashboard-from-file-export.yml | 22 +- .../tasks/dashboard-from-id.yml | 17 +- .../tasks/dashboard-from-url.yml | 17 +- .../tasks/delete-dashboard.yml | 6 +- .../targets/grafana_dashboard/tasks/main.yml | 15 +- .../grafana_datasource/defaults/main.yml | 8 +- .../grafana_datasource/tasks/azure.yml | 117 +++--- .../grafana_datasource/tasks/cloudwatch.yml | 111 ++--- .../grafana_datasource/tasks/elastic.yml | 378 +++++++++--------- .../grafana_datasource/tasks/errors.yml | 12 +- .../grafana_datasource/tasks/influx.yml | 71 ++-- .../grafana_datasource/tasks/issues.yml | 59 ++- .../targets/grafana_datasource/tasks/loki.yml | 73 ++-- .../targets/grafana_datasource/tasks/main.yml | 36 +- .../grafana_datasource/tasks/postgres.yml | 65 +-- .../grafana_datasource/tasks/redis.yml | 85 ++-- .../grafana_datasource/tasks/tempo.yml | 59 +-- .../grafana_datasource/tasks/thruk.yml | 69 ++-- .../targets/grafana_datasource/tasks/uid.yml | 255 ++++++------ .../grafana_datasource/tasks/zabbix.yml | 107 ++--- .../targets/grafana_folder/defaults/main.yml | 8 +- .../targets/grafana_folder/tasks/main.yml | 61 ++- .../defaults/main.yml | 8 +- .../tasks/dingding.yml | 32 +- .../tasks/discord.yml | 32 +- .../tasks/email.yml | 42 +- .../tasks/googlechat.yml | 40 +- .../tasks/hipchat.yml | 40 +- .../tasks/kafka.yml | 40 +- .../tasks/line.yml | 40 +- .../tasks/main.yml | 50 ++- .../tasks/opsgenie.yml | 42 +- .../tasks/pagerduty.yml | 40 +- .../tasks/prometheus.yml | 40 +- .../tasks/pushover.yml | 40 +- .../tasks/sensu.yml | 40 +- .../tasks/slack-and-beyond.yml | 60 +-- .../tasks/teams.yml | 40 +- .../tasks/telegram.yml | 40 +- .../tasks/threema.yml | 40 +- .../tasks/victorops.yml | 40 +- .../tasks/webhook.yml | 40 +- .../grafana_organization/defaults/main.yml | 6 +- .../grafana_organization/tasks/main.yml | 37 +- .../defaults/main.yml | 6 +- .../grafana_organization_user/tasks/main.yml | 72 ++-- .../targets/grafana_team/defaults/main.yml | 8 +- .../grafana_team/tasks/create_user.yml | 25 +- .../targets/grafana_team/tasks/main.yml | 263 ++++++------ .../targets/grafana_user/defaults/main.yml | 6 +- .../targets/grafana_user/tasks/main.yml | 172 ++++---- 57 files changed, 1552 insertions(+), 1520 deletions(-) diff --git a/galaxy.yml b/galaxy.yml index 739c4c33..dbfb2d93 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -1,3 +1,4 @@ +--- namespace: community name: grafana version: 1.6.1 diff --git a/meta/runtime.yml b/meta/runtime.yml index ed9ac426..06ab11f5 100644 --- a/meta/runtime.yml +++ b/meta/runtime.yml @@ -1,5 +1,5 @@ --- -requires_ansible: '>=2.9.0' +requires_ansible: ">=2.9.0" action_groups: grafana: - grafana_dashboard diff --git a/tests/integration/targets/grafana_dashboard/defaults/main.yml b/tests/integration/targets/grafana_dashboard/defaults/main.yml index 7bb77ea3..3edac859 100644 --- a/tests/integration/targets/grafana_dashboard/defaults/main.yml +++ b/tests/integration/targets/grafana_dashboard/defaults/main.yml @@ -1,4 +1,4 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml index 538e7c26..6247f0ea 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-by-org-name.yml @@ -15,9 +15,9 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.msg == 'Dashboard test created'" + - result.failed == false + - result.changed == true + - result.msg == 'Dashboard test created' - name: Check import grafana dashboard from file idempotency community.grafana.grafana_dashboard: @@ -31,8 +31,9 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == false" - - "result.msg == 'Dashboard test unchanged.'" + - result.failed == false + - result.changed == false + - result.msg == 'Dashboard test unchanged.' - - ansible.builtin.include_tasks: delete-dashboard.yml + - ansible.builtin.include_tasks: + file: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml index 7a2354ea..05ec652c 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-export.yml @@ -11,9 +11,9 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.msg == 'Dashboard ' ~ result.uid ~ ' exported to /tmp/dashboard_export.json'" + - result.failed == false + - result.changed == true + - result.msg == 'Dashboard ' ~ result.uid ~ ' exported to /tmp/dashboard_export.json' - name: Load /tmp/dashboard_export.json or fail if missing ansible.builtin.set_fact: @@ -22,6 +22,6 @@ - name: Assert that exported dashboard contains formatted JSON ansible.builtin.assert: that: - - "exported_dashboard_lines | length >= 2" - - "exported_dashboard_lines[0] == '{'" - - "exported_dashboard_lines[-1] == '}'" + - exported_dashboard_lines | length >= 2 + - exported_dashboard_lines[0] == '{' + - exported_dashboard_lines[-1] == '}' diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml index 4faf28bd..6c652b53 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-folder-destination.yml @@ -13,6 +13,6 @@ ignore_errors: true - ansible.builtin.assert: that: - - "result.failed == true" - - "result.changed == false" + - result.failed == true + - result.changed == false - "result.msg == 'error : Dashboard folder \\'inexistent\\' does not exist.'" diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml index 2e54d110..04a35ba2 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file-export.yml @@ -1,8 +1,8 @@ --- - name: Copy dashboard file ansible.builtin.copy: - src: "files/dashboard.json" - dest: "/tmp/dashboard.json" + src: files/dashboard.json + dest: /tmp/dashboard.json - name: Check import grafana dashboard from file community.grafana.grafana_dashboard: @@ -16,9 +16,9 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.msg == 'Dashboard test created'" + - result.failed == false + - result.changed == true + - result.msg == 'Dashboard test created' - name: Check import grafana dashboard from file idempotency community.grafana.grafana_dashboard: @@ -32,10 +32,12 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == false" - - "result.msg == 'Dashboard test unchanged.'" + - result.failed == false + - result.changed == false + - result.msg == 'Dashboard test unchanged.' -- ansible.builtin.include_tasks: dashboard-export.yml +- ansible.builtin.include_tasks: + file: dashboard-export.yml -- ansible.builtin.include_tasks: delete-dashboard.yml +- ansible.builtin.include_tasks: + file: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml index d2d248de..8fd1f78a 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml @@ -10,11 +10,11 @@ dashboard_revision: "1" overwrite: true register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.msg == 'Dashboard Zabbix Host Status created'" + - result.failed == false + - result.changed == true + - result.msg == 'Dashboard Zabbix Host Status created' - name: Check import grafana dashboard from id idempotency community.grafana.grafana_dashboard: @@ -29,8 +29,9 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == false" - - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" + - result.failed == false + - result.changed == false + - result.msg == 'Dashboard Zabbix Host Status unchanged.' -- ansible.builtin.include_tasks: delete-dashboard.yml +- ansible.builtin.include_tasks: + file: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml index 13c6555c..9cf8ce97 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml @@ -9,11 +9,11 @@ dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download overwrite: true register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.msg == 'Dashboard Zabbix Host Status created'" + - result.failed == false + - result.changed == true + - result.msg == 'Dashboard Zabbix Host Status created' - name: Check import grafana dashboard from url idempotency community.grafana.grafana_dashboard: @@ -27,8 +27,9 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == false" - - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" + - result.failed == false + - result.changed == false + - result.msg == 'Dashboard Zabbix Host Status unchanged.' -- ansible.builtin.include_tasks: delete-dashboard.yml +- ansible.builtin.include_tasks: + file: delete-dashboard.yml diff --git a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml index c9f04898..bea769b9 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml @@ -9,6 +9,6 @@ register: result - ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.msg == 'Dashboard ' ~ result.uid ~ ' deleted'" + - result.failed == false + - result.changed == true + - result.msg == 'Dashboard ' ~ result.uid ~ ' deleted' diff --git a/tests/integration/targets/grafana_dashboard/tasks/main.yml b/tests/integration/targets/grafana_dashboard/tasks/main.yml index 0a082d43..9c9c3f13 100644 --- a/tests/integration/targets/grafana_dashboard/tasks/main.yml +++ b/tests/integration/targets/grafana_dashboard/tasks/main.yml @@ -1,15 +1,20 @@ --- - name: Create dashboard from url - ansible.builtin.include_tasks: dashboard-from-url.yml + ansible.builtin.include_tasks: + file: dashboard-from-url.yml - name: Create dashboard from id - ansible.builtin.include_tasks: dashboard-from-id.yml + ansible.builtin.include_tasks: + file: dashboard-from-id.yml - name: Create dashboard from file and export - ansible.builtin.include_tasks: dashboard-from-file-export.yml + ansible.builtin.include_tasks: + file: dashboard-from-file-export.yml - name: Create dashboard from file by org_name - ansible.builtin.include_tasks: dashboard-by-org-name.yml + ansible.builtin.include_tasks: + file: dashboard-by-org-name.yml - name: Create dashboard in non existing folder - ansible.builtin.include_tasks: dashboard-folder-destination.yml + ansible.builtin.include_tasks: + file: dashboard-folder-destination.yml diff --git a/tests/integration/targets/grafana_datasource/defaults/main.yml b/tests/integration/targets/grafana_datasource/defaults/main.yml index 8b9c9348..4abf9bb4 100644 --- a/tests/integration/targets/grafana_datasource/defaults/main.yml +++ b/tests/integration/targets/grafana_datasource/defaults/main.yml @@ -1,7 +1,5 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" - -... +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_datasource/tasks/azure.yml b/tests/integration/targets/grafana_datasource/tasks/azure.yml index a9669189..0dbd9496 100644 --- a/tests/integration/targets/grafana_datasource/tasks/azure.yml +++ b/tests/integration/targets/grafana_datasource/tasks/azure.yml @@ -1,11 +1,12 @@ +--- - name: Create azure datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-azure grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" - org_id: '1' + grafana_password: "{{ grafana_password }}" + org_id: "1" ds_type: grafana-azure-monitor-datasource ds_url: http://example.com azure_client: client1 @@ -13,38 +14,38 @@ azure_secret: secret1 azure_cloud: azuremonitor -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-azure created'" - - result.datasource.access == 'proxy' - - result.datasource.basicAuth == false - - result.datasource.database == '' - - result.datasource.isDefault == false - - result.datasource.jsonData.clientId == 'client1' - - result.datasource.jsonData.cloudName == 'azuremonitor' - - result.datasource.jsonData.tenantId == 'tenant1' - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.name == 'datasource-azure' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'grafana-azure-monitor-datasource' - - result.datasource.url == 'http://example.com' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - result.changed + - result.msg == 'Datasource datasource-azure created' + - result.datasource.access == 'proxy' + - result.datasource.basicAuth == false + - result.datasource.database == '' + - result.datasource.isDefault == false + - result.datasource.jsonData.clientId == 'client1' + - result.datasource.jsonData.cloudName == 'azuremonitor' + - result.datasource.jsonData.tenantId == 'tenant1' + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.name == 'datasource-azure' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'grafana-azure-monitor-datasource' + - result.datasource.url == 'http://example.com' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Check azure datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-azure grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" - org_id: '1' + grafana_password: "{{ grafana_password }}" + org_id: "1" ds_type: grafana-azure-monitor-datasource ds_url: http://example.com azure_client: client1 @@ -52,37 +53,37 @@ azure_secret: secret1 azure_cloud: azuremonitor -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.access == 'proxy' - - result.datasource.basicAuth == false - - result.datasource.database == '' - - result.datasource.isDefault == false - - result.datasource.jsonData.clientId == 'client1' - - result.datasource.jsonData.cloudName == 'azuremonitor' - - result.datasource.jsonData.tenantId == 'tenant1' - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.name == 'datasource-azure' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'grafana-azure-monitor-datasource' - - result.datasource.url == 'http://example.com' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.access == 'proxy' + - result.datasource.basicAuth == false + - result.datasource.database == '' + - result.datasource.isDefault == false + - result.datasource.jsonData.clientId == 'client1' + - result.datasource.jsonData.cloudName == 'azuremonitor' + - result.datasource.jsonData.tenantId == 'tenant1' + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.name == 'datasource-azure' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'grafana-azure-monitor-datasource' + - result.datasource.url == 'http://example.com' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Delete azure datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-azure grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" - org_id: '1' + grafana_password: "{{ grafana_password }}" + org_id: "1" ds_type: grafana-azure-monitor-datasource ds_url: http://example.com azure_client: client1 @@ -91,22 +92,22 @@ azure_cloud: azuremonitor state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-azure deleted.'" + - result.changed + - result.msg == 'Datasource datasource-azure deleted.' - name: Delete azure datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-azure grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" - org_id: '1' + grafana_password: "{{ grafana_password }}" + org_id: "1" ds_type: grafana-azure-monitor-datasource ds_url: http://example.com azure_client: client1 @@ -115,9 +116,9 @@ azure_cloud: azuremonitor state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml b/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml index 50268ea8..79408b68 100644 --- a/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml +++ b/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml @@ -1,11 +1,12 @@ +--- - name: Create cloudwatch datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-cloudwatch grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" - org_id: '1' + grafana_password: "{{ grafana_password }}" + org_id: "1" ds_type: cloudwatch ds_url: http://monitoring.us-west-1.amazonaws.com aws_auth_type: keys @@ -14,38 +15,38 @@ aws_secret_key: mel10n aws_custom_metrics_namespaces: n1,n2 -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-cloudwatch created'" - - result.datasource.access == 'proxy' - - result.datasource.basicAuth == false - - result.datasource.database == '' - - result.datasource.isDefault == false - - result.datasource.jsonData.authType == 'keys' - - result.datasource.jsonData.customMetricsNamespaces == 'n1,n2' - - result.datasource.jsonData.defaultRegion == 'us-west-1' - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.name == 'datasource-cloudwatch' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'cloudwatch' - - result.datasource.url == 'http://monitoring.us-west-1.amazonaws.com' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - result.changed + - result.msg == 'Datasource datasource-cloudwatch created' + - result.datasource.access == 'proxy' + - result.datasource.basicAuth == false + - result.datasource.database == '' + - result.datasource.isDefault == false + - result.datasource.jsonData.authType == 'keys' + - result.datasource.jsonData.customMetricsNamespaces == 'n1,n2' + - result.datasource.jsonData.defaultRegion == 'us-west-1' + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.name == 'datasource-cloudwatch' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'cloudwatch' + - result.datasource.url == 'http://monitoring.us-west-1.amazonaws.com' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Check cloudwatch datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-cloudwatch grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: cloudwatch ds_url: http://monitoring.us-west-1.amazonaws.com aws_auth_type: keys @@ -54,58 +55,58 @@ aws_secret_key: mel10n aws_custom_metrics_namespaces: n1,n2 -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.access == 'proxy' - - result.datasource.basicAuth == false - - result.datasource.database == '' - - result.datasource.isDefault == false - - result.datasource.jsonData.authType == 'keys' - - result.datasource.jsonData.customMetricsNamespaces == 'n1,n2' - - result.datasource.jsonData.defaultRegion == 'us-west-1' - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.name == 'datasource-cloudwatch' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'cloudwatch' - - result.datasource.url == 'http://monitoring.us-west-1.amazonaws.com' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.access == 'proxy' + - result.datasource.basicAuth == false + - result.datasource.database == '' + - result.datasource.isDefault == false + - result.datasource.jsonData.authType == 'keys' + - result.datasource.jsonData.customMetricsNamespaces == 'n1,n2' + - result.datasource.jsonData.defaultRegion == 'us-west-1' + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.name == 'datasource-cloudwatch' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'cloudwatch' + - result.datasource.url == 'http://monitoring.us-west-1.amazonaws.com' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Delete cloudwatch datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-cloudwatch grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-cloudwatch deleted.'" + - result.changed + - result.msg == 'Datasource datasource-cloudwatch deleted.' - name: Delete cloudwatch datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-cloudwatch grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/elastic.yml b/tests/integration/targets/grafana_datasource/tasks/elastic.yml index 73b25842..ff05b93f 100644 --- a/tests/integration/targets/grafana_datasource/tasks/elastic.yml +++ b/tests/integration/targets/grafana_datasource/tasks/elastic.yml @@ -1,313 +1,313 @@ --- - name: Create elasticsearch datasource with legacy elasticsearch format register: result - grafana_datasource: - name: "datasource/elasticLegacy" - uid: "myuid" + community.grafana.grafana_datasource: + name: datasource/elasticLegacy + uid: myuid grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.company.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily es_version: 56 max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == 56 - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elasticLegacy' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.company.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials - - "result.msg == 'Datasource datasource/elasticLegacy created'" + - result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == 56 + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elasticLegacy' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.company.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.msg == 'Datasource datasource/elasticLegacy created' - name: Create elasticsearch datasource with new elsaticsearch version format register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.company.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily - es_version: "7.10+" + es_version: 7.10+ max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == "7.10.0" - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elastic' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.company.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials - - "result.msg == 'Datasource datasource/elastic created'" + - result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == "7.10.0" + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elastic' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.company.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.msg == 'Datasource datasource/elastic created' - name: Check elasticsearch datasource creation idempotency register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.company.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily - es_version: "7.10+" + es_version: 7.10+ max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == '7.10.0' - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elastic' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.company.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials + - not result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == '7.10.0' + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elastic' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.company.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials -- name: update elasticsearch datasource creation +- name: Update elasticsearch datasource creation register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.example.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily - es_version: "7.10+" + es_version: 7.10+ max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == '7.10.0' - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elastic' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.example.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials + - result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == '7.10.0' + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elastic' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.example.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials -- name: update elasticsearch datasource (ignoring secureJsonData) +- name: Update elasticsearch datasource (ignoring secureJsonData) register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.example.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily - es_version: "7.10+" + es_version: 7.10+ max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem enforce_secure_data: false additional_json_data: - nonSecureTest: "nonsecure" + nonSecureTest: nonsecure additional_secure_json_data: - secureTest: "secure" + secureTest: secure -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == '7.10.0' - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elastic' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.example.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials - - result.datasource.jsonData.nonSecureTest == 'nonsecure' + - result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == '7.10.0' + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elastic' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.example.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.datasource.jsonData.nonSecureTest == 'nonsecure' -- name: update elasticsearch datasource (including secureJsonData) +- name: Update elasticsearch datasource (including secureJsonData) register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.example.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily - es_version: "7.10+" + es_version: 7.10+ max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem enforce_secure_data: true additional_json_data: - nonSecureTest: "nonsecure" + nonSecureTest: nonsecure additional_secure_json_data: - secureTest: "secure" + secureTest: secure -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == '7.10.0' - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elastic' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.example.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials - - result.datasource.jsonData.nonSecureTest == 'nonsecure' - - result.datasource.secureJsonFields.secureTest == true - - result.diff.after.secureJsonData is defined + - result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == '7.10.0' + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elastic' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.example.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.datasource.jsonData.nonSecureTest == 'nonsecure' + - result.datasource.secureJsonFields.secureTest == true + - result.diff.after.secureJsonData is defined - name: Delete elasticsearch datasource register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete elasticsearch datasource (idempotency) register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/errors.yml b/tests/integration/targets/grafana_datasource/tasks/errors.yml index 731a19d8..779b4724 100644 --- a/tests/integration/targets/grafana_datasource/tasks/errors.yml +++ b/tests/integration/targets/grafana_datasource/tasks/errors.yml @@ -1,18 +1,18 @@ --- - name: Create datasource without `ds_type` and `ds_url` (expect failure) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-postgres grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" ignore_errors: true -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.failed - - "result.msg == 'state is present but all of the following are missing: ds_type, ds_url'" + - not result.changed + - result.failed + - "result.msg == 'state is present but all of the following are missing: ds_type, ds_url'" diff --git a/tests/integration/targets/grafana_datasource/tasks/influx.yml b/tests/integration/targets/grafana_datasource/tasks/influx.yml index da61833f..7952bec6 100644 --- a/tests/integration/targets/grafana_datasource/tasks/influx.yml +++ b/tests/integration/targets/grafana_datasource/tasks/influx.yml @@ -1,88 +1,89 @@ +--- - name: Create influxdb datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-influxdb grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: influxdb ds_url: https://influx.company.com:8086 database: telegraf - time_interval: '>10s' + time_interval: ">10s" tls_ca_cert: /etc/ssl/certs/ca.pem -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-influxdb created'" + - result.changed + - result.msg == 'Datasource datasource-influxdb created' - name: Check influxdb datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-influxdb grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: influxdb ds_url: https://influx.company.com:8086 database: telegraf - time_interval: '>10s' + time_interval: ">10s" tls_ca_cert: /etc/ssl/certs/ca.pem -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.basicAuth == false - - result.datasource.access == 'proxy' - - result.datasource.database == 'telegraf' - - result.datasource.isDefault == false - - result.datasource.jsonData.timeInterval == '>10s' - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource-influxdb' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'influxdb' - - result.datasource.url == 'https://influx.company.com:8086' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.basicAuth == false + - result.datasource.access == 'proxy' + - result.datasource.database == 'telegraf' + - result.datasource.isDefault == false + - result.datasource.jsonData.timeInterval == '>10s' + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource-influxdb' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'influxdb' + - result.datasource.url == 'https://influx.company.com:8086' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Delete influxdb datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-influxdb grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete influxdb datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-influxdb grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/issues.yml b/tests/integration/targets/grafana_datasource/tasks/issues.yml index f80677d8..3b4df5a7 100644 --- a/tests/integration/targets/grafana_datasource/tasks/issues.yml +++ b/tests/integration/targets/grafana_datasource/tasks/issues.yml @@ -1,46 +1,43 @@ --- - -- name: test datasource name with slash +- name: Test datasource name with slash register: result - grafana_datasource: - name: "datasource/elastic" + community.grafana.grafana_datasource: + name: datasource/elastic grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: elasticsearch ds_url: https://elastic.company.com:9200 - database: '[logstash_]YYYY.MM.DD' + database: "[logstash_]YYYY.MM.DD" basic_auth_user: grafana - basic_auth_password: '******' - time_field: '@timestamp' + basic_auth_password: "******" + time_field: "@timestamp" time_interval: 1m interval: Daily es_version: 56 max_concurrent_shard_requests: 42 tls_ca_cert: /etc/ssl/certs/ca.pem -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.basicAuth - - result.datasource.basicAuthUser == 'grafana' - - result.datasource.access == 'proxy' - - result.datasource.database == '[logstash_]YYYY.MM.DD' - - not result.datasource.isDefault - - result.datasource.jsonData.esVersion == 56 - - result.datasource.jsonData.interval == 'Daily' - - result.datasource.jsonData.maxConcurrentShardRequests == 42 - - result.datasource.jsonData.timeField == '@timestamp' - - not result.datasource.jsonData.tlsAuth - - not result.datasource.jsonData.tlsAuthWithCACert - - result.datasource.name == 'datasource/elastic' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'elasticsearch' - - result.datasource.url == 'https://elastic.company.com:9200' - - result.datasource.user == '' - - not result.datasource.withCredentials - - "result.msg == 'Datasource datasource/elastic created'" - -... + - result.changed + - result.datasource.basicAuth + - result.datasource.basicAuthUser == 'grafana' + - result.datasource.access == 'proxy' + - result.datasource.database == '[logstash_]YYYY.MM.DD' + - not result.datasource.isDefault + - result.datasource.jsonData.esVersion == 56 + - result.datasource.jsonData.interval == 'Daily' + - result.datasource.jsonData.maxConcurrentShardRequests == 42 + - result.datasource.jsonData.timeField == '@timestamp' + - not result.datasource.jsonData.tlsAuth + - not result.datasource.jsonData.tlsAuthWithCACert + - result.datasource.name == 'datasource/elastic' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'elasticsearch' + - result.datasource.url == 'https://elastic.company.com:9200' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.msg == 'Datasource datasource/elastic created' diff --git a/tests/integration/targets/grafana_datasource/tasks/loki.yml b/tests/integration/targets/grafana_datasource/tasks/loki.yml index 68eca980..a501b99d 100644 --- a/tests/integration/targets/grafana_datasource/tasks/loki.yml +++ b/tests/integration/targets/grafana_datasource/tasks/loki.yml @@ -1,82 +1,83 @@ +--- - name: Create loki datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-loki grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" - org_id: '1' + grafana_password: "{{ grafana_password }}" + org_id: "1" ds_type: loki ds_url: https://loki.company.com:3100 -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-loki created'" + - result.changed + - result.msg == 'Datasource datasource-loki created' - name: Check loki datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-loki grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: loki ds_url: https://loki.company.com:3100 -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.basicAuth == false - - result.datasource.access == 'proxy' - - result.datasource.database == '' - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.name == 'datasource-loki' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'loki' - - result.datasource.url == 'https://loki.company.com:3100' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.basicAuth == false + - result.datasource.access == 'proxy' + - result.datasource.database == '' + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.name == 'datasource-loki' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'loki' + - result.datasource.url == 'https://loki.company.com:3100' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Delete loki datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-loki grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-loki deleted.'" + - result.changed + - result.msg == 'Datasource datasource-loki deleted.' - name: Delete loki datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-loki grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/main.yml b/tests/integration/targets/grafana_datasource/tasks/main.yml index 312ad347..0b3ea4cd 100644 --- a/tests/integration/targets/grafana_datasource/tasks/main.yml +++ b/tests/integration/targets/grafana_datasource/tasks/main.yml @@ -1,16 +1,24 @@ --- - - block: - - include_tasks: errors.yml - - include_tasks: elastic.yml - - include_tasks: influx.yml - - include_tasks: postgres.yml - - include_tasks: cloudwatch.yml - - include_tasks: thruk.yml - - include_tasks: loki.yml - - include_tasks: zabbix.yml - - include_tasks: redis.yml - - include_tasks: azure.yml - - include_tasks: uid.yml - -... + - ansible.builtin.include_tasks: + file: errors.yml + - ansible.builtin.include_tasks: + file: elastic.yml + - ansible.builtin.include_tasks: + file: influx.yml + - ansible.builtin.include_tasks: + file: postgres.yml + - ansible.builtin.include_tasks: + file: cloudwatch.yml + - ansible.builtin.include_tasks: + file: thruk.yml + - ansible.builtin.include_tasks: + file: loki.yml + - ansible.builtin.include_tasks: + file: zabbix.yml + - ansible.builtin.include_tasks: + file: redis.yml + - ansible.builtin.include_tasks: + file: azure.yml + - ansible.builtin.include_tasks: + file: uid.yml diff --git a/tests/integration/targets/grafana_datasource/tasks/postgres.yml b/tests/integration/targets/grafana_datasource/tasks/postgres.yml index 80221f01..b07bc752 100644 --- a/tests/integration/targets/grafana_datasource/tasks/postgres.yml +++ b/tests/integration/targets/grafana_datasource/tasks/postgres.yml @@ -1,11 +1,12 @@ +--- - name: Create postgres datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-postgres grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: postgres ds_url: postgres.company.com:5432 database: db @@ -15,22 +16,22 @@ additional_json_data: timescaledb: true -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-postgres created'" + - result.changed + - result.msg == 'Datasource datasource-postgres created' - name: Check postgres datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-postgres grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: postgres ds_url: postgres.company.com:5432 database: db @@ -40,54 +41,54 @@ additional_json_data: timescaledb: true -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.basicAuth == false - - result.datasource.database == 'db' - - result.datasource.isDefault == false - - result.datasource.jsonData.sslmode == 'verify-full' - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.jsonData.timescaledb == true - - result.datasource.name == 'datasource-postgres' - - result.datasource.orgId == 1 - - result.datasource.type == 'postgres' - - result.datasource.url == 'postgres.company.com:5432' - - result.datasource.user == 'postgres' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.basicAuth == false + - result.datasource.database == 'db' + - result.datasource.isDefault == false + - result.datasource.jsonData.sslmode == 'verify-full' + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.jsonData.timescaledb == true + - result.datasource.name == 'datasource-postgres' + - result.datasource.orgId == 1 + - result.datasource.type == 'postgres' + - result.datasource.url == 'postgres.company.com:5432' + - result.datasource.user == 'postgres' + - result.datasource.withCredentials == false - name: Delete postgres datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-postgres grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete postgres datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-postgres grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/redis.yml b/tests/integration/targets/grafana_datasource/tasks/redis.yml index 93369535..dc39be64 100644 --- a/tests/integration/targets/grafana_datasource/tasks/redis.yml +++ b/tests/integration/targets/grafana_datasource/tasks/redis.yml @@ -1,101 +1,102 @@ +--- - name: Create redis datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-redis grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: redis-datasource ds_url: https://redis.company.com:6379 time_interval: 1m -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.access == 'proxy' - - not result.datasource.isDefault - - result.datasource.name == 'datasource-redis' - - result.datasource.orgId == 1 - - result.datasource.type == 'redis-datasource' - - result.datasource.url == 'https://redis.company.com:6379' - - "result.msg == 'Datasource datasource-redis created'" + - result.changed + - result.datasource.access == 'proxy' + - not result.datasource.isDefault + - result.datasource.name == 'datasource-redis' + - result.datasource.orgId == 1 + - result.datasource.type == 'redis-datasource' + - result.datasource.url == 'https://redis.company.com:6379' + - result.msg == 'Datasource datasource-redis created' - name: Check redis-datasource datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-redis grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: redis-datasource ds_url: https://redis.company.com:6379 time_interval: 1m -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.access == 'proxy' - - not result.datasource.isDefault - - result.datasource.name == 'datasource-redis' - - result.datasource.orgId == 1 - - result.datasource.type == 'redis-datasource' - - result.datasource.url == 'https://redis.company.com:6379' + - not result.changed + - result.datasource.access == 'proxy' + - not result.datasource.isDefault + - result.datasource.name == 'datasource-redis' + - result.datasource.orgId == 1 + - result.datasource.type == 'redis-datasource' + - result.datasource.url == 'https://redis.company.com:6379' -- name: update redis-datasource datasource creation +- name: Update redis-datasource datasource creation register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-redis grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: redis-datasource ds_url: https://redisnew.company.com:6379 time_interval: 1m -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.access == 'proxy' - - not result.datasource.isDefault - - result.datasource.name == 'datasource-redis' - - result.datasource.orgId == 1 - - result.datasource.type == 'redis-datasource' - - result.datasource.url == 'https://redisnew.company.com:6379' + - result.changed + - result.datasource.access == 'proxy' + - not result.datasource.isDefault + - result.datasource.name == 'datasource-redis' + - result.datasource.orgId == 1 + - result.datasource.type == 'redis-datasource' + - result.datasource.url == 'https://redisnew.company.com:6379' -- name: Delete redis-datasource datasource +- name: Delete redis-datasource datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-redis grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete redis-datasource datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-redis grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/tempo.yml b/tests/integration/targets/grafana_datasource/tasks/tempo.yml index 5065a6ce..51ab5251 100644 --- a/tests/integration/targets/grafana_datasource/tasks/tempo.yml +++ b/tests/integration/targets/grafana_datasource/tasks/tempo.yml @@ -1,78 +1,79 @@ +--- - name: Create tempo datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-tempo grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: tempo ds_url: tempo.company.com:3100 -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-tempo created'" + - result.changed + - result.msg == 'Datasource datasource-tempo created' - name: Check tempo datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-tempo grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: tempo ds_url: tempo.company.com:3100 -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.basicAuth == false - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.secureJsonFields.httpHeaderValue1 == true - - result.datasource.name == 'datasource-tempo' - - result.datasource.orgId == 1 - - result.datasource.type == 'tempo' - - result.datasource.url == 'tempo.company.com:3100' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.basicAuth == false + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.secureJsonFields.httpHeaderValue1 == true + - result.datasource.name == 'datasource-tempo' + - result.datasource.orgId == 1 + - result.datasource.type == 'tempo' + - result.datasource.url == 'tempo.company.com:3100' + - result.datasource.withCredentials == false - name: Delete tempo datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-tempo grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete tempo datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-tempo grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/thruk.yml b/tests/integration/targets/grafana_datasource/tasks/thruk.yml index 3ecc92d9..74f7c4df 100644 --- a/tests/integration/targets/grafana_datasource/tasks/thruk.yml +++ b/tests/integration/targets/grafana_datasource/tasks/thruk.yml @@ -1,78 +1,79 @@ +--- - name: Create thruk datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-thruk grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" org_id: "1" ds_type: sni-thruk-datasource - ds_url: "https://thruk.company.com/sitename/thruk" - tls_skip_verify: yes - validate_certs: no + ds_url: https://thruk.company.com/sitename/thruk + tls_skip_verify: true + validate_certs: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-thruk created'" + - result.changed + - result.msg == 'Datasource datasource-thruk created' - name: Check thruk datasource creation idempotency register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-thruk grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: sni-thruk-datasource - ds_url: "https://thruk.company.com/sitename/thruk" - tls_skip_verify: yes - validate_certs: no + ds_url: https://thruk.company.com/sitename/thruk + tls_skip_verify: true + validate_certs: false -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.basicAuth == false - - result.datasource.access == 'proxy' - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.jsonData.tlsAuthWithCACert == false - - result.datasource.name == 'datasource-thruk' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'sni-thruk-datasource' - - result.datasource.url == 'https://thruk.company.com/sitename/thruk' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.basicAuth == false + - result.datasource.access == 'proxy' + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.jsonData.tlsAuthWithCACert == false + - result.datasource.name == 'datasource-thruk' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'sni-thruk-datasource' + - result.datasource.url == 'https://thruk.company.com/sitename/thruk' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Delete thruk datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-thruk grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete thruk datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-thruk grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/uid.yml b/tests/integration/targets/grafana_datasource/tasks/uid.yml index 71102a07..7a472b42 100644 --- a/tests/integration/targets/grafana_datasource/tasks/uid.yml +++ b/tests/integration/targets/grafana_datasource/tasks/uid.yml @@ -1,253 +1,254 @@ +--- - name: Create datasource with uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-with-uid uid: uid1 grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-with-uid created'" + - result.changed + - result.msg == 'Datasource datasource-with-uid created' - name: Create datasource without uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-without-uid grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - "result.msg == 'Datasource datasource-without-uid created'" + - result.changed + - result.msg == 'Datasource datasource-without-uid created' - name: Check datasource creation idempotency with uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-with-uid uid: uid1 grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.access == 'proxy' - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.name == 'datasource-with-uid' - - result.datasource.uid == 'uid1' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'prometheus' - - result.datasource.url == 'https://prometheus.company.com:8086' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.access == 'proxy' + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.name == 'datasource-with-uid' + - result.datasource.uid == 'uid1' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'prometheus' + - result.datasource.url == 'https://prometheus.company.com:8086' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Check datasource creation idempotency without uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-without-uid grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - result.datasource.access == 'proxy' - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.name == 'datasource-without-uid' - - result.datasource.uid - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'prometheus' - - result.datasource.url == 'https://prometheus.company.com:8086' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - not result.changed + - result.datasource.access == 'proxy' + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.name == 'datasource-without-uid' + - result.datasource.uid + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'prometheus' + - result.datasource.url == 'https://prometheus.company.com:8086' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Set uid for datasource with random uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-without-uid uid: uid3 grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.access == 'proxy' - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.name == 'datasource-without-uid' - - result.datasource.uid == 'uid3' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'prometheus' - - result.datasource.url == 'https://prometheus.company.com:8086' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - result.changed + - result.datasource.access == 'proxy' + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.name == 'datasource-without-uid' + - result.datasource.uid == 'uid3' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'prometheus' + - result.datasource.url == 'https://prometheus.company.com:8086' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Change uid for datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-with-uid uid: uid2 grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - result.datasource.access == 'proxy' - - result.datasource.isDefault == false - - result.datasource.jsonData.tlsAuth == false - - result.datasource.name == 'datasource-with-uid' - - result.datasource.uid == 'uid2' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'prometheus' - - result.datasource.url == 'https://prometheus.company.com:8086' - - result.datasource.user == '' - - result.datasource.withCredentials == false + - result.changed + - result.datasource.access == 'proxy' + - result.datasource.isDefault == false + - result.datasource.jsonData.tlsAuth == false + - result.datasource.name == 'datasource-with-uid' + - result.datasource.uid == 'uid2' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'prometheus' + - result.datasource.url == 'https://prometheus.company.com:8086' + - result.datasource.user == '' + - result.datasource.withCredentials == false - name: Delete datasource-with-uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-with-uid uid: uid1 grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete datasource-without-uid register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-without-uid grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete datasource-with-uid (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-with-uid uid: uid1 grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: prometheus ds_url: https://prometheus.company.com:8086 - basic_auth_user: "admin" - basic_auth_password: "admin" - validate_certs: False - is_default: no + basic_auth_user: admin + basic_auth_password: admin + validate_certs: false + is_default: false state: absent -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_datasource/tasks/zabbix.yml b/tests/integration/targets/grafana_datasource/tasks/zabbix.yml index c8a8236b..d238efb3 100644 --- a/tests/integration/targets/grafana_datasource/tasks/zabbix.yml +++ b/tests/integration/targets/grafana_datasource/tasks/zabbix.yml @@ -1,114 +1,115 @@ +--- - name: Create zabbix datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-zabbix grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: alexanderzobnin-zabbix-datasource ds_url: https://zabbix.company.com zabbix_user: grafana - zabbix_password: '******' + zabbix_password: "******" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - not result.datasource.isDefault - - result.datasource.jsonData.username == 'grafana' - - result.datasource.name == 'datasource-zabbix' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'alexanderzobnin-zabbix-datasource' - - result.datasource.url == 'https://zabbix.company.com' - - result.datasource.user == '' - - not result.datasource.withCredentials - - "result.msg == 'Datasource datasource-zabbix created'" + - result.changed + - not result.datasource.isDefault + - result.datasource.jsonData.username == 'grafana' + - result.datasource.name == 'datasource-zabbix' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'alexanderzobnin-zabbix-datasource' + - result.datasource.url == 'https://zabbix.company.com' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.msg == 'Datasource datasource-zabbix created' - name: Create zabbix datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-zabbix grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: alexanderzobnin-zabbix-datasource ds_url: https://zabbix.company.com zabbix_user: grafana - zabbix_password: '******' + zabbix_password: "******" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - not result.changed - - not result.datasource.isDefault - - result.datasource.jsonData.username == 'grafana' - - result.datasource.name == 'datasource-zabbix' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'alexanderzobnin-zabbix-datasource' - - result.datasource.url == 'https://zabbix.company.com' - - result.datasource.user == '' - - not result.datasource.withCredentials + - not result.changed + - not result.datasource.isDefault + - result.datasource.jsonData.username == 'grafana' + - result.datasource.name == 'datasource-zabbix' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'alexanderzobnin-zabbix-datasource' + - result.datasource.url == 'https://zabbix.company.com' + - result.datasource.user == '' + - not result.datasource.withCredentials - name: Update zabbix datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-zabbix grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" - org_id: '1' + org_id: "1" ds_type: alexanderzobnin-zabbix-datasource ds_url: https://zabbix.example.com zabbix_user: grafana - zabbix_password: '******' + zabbix_password: "******" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - result.changed - - not result.datasource.isDefault - - result.datasource.jsonData.username == 'grafana' - - result.datasource.name == 'datasource-zabbix' - - result.datasource.orgId == 1 - - ('password' not in result.datasource) or (result.datasource.password == '') - - result.datasource.type == 'alexanderzobnin-zabbix-datasource' - - result.datasource.url == 'https://zabbix.example.com' - - result.datasource.user == '' - - not result.datasource.withCredentials - - "result.msg == 'Datasource datasource-zabbix updated'" + - result.changed + - not result.datasource.isDefault + - result.datasource.jsonData.username == 'grafana' + - result.datasource.name == 'datasource-zabbix' + - result.datasource.orgId == 1 + - ('password' not in result.datasource) or (result.datasource.password == '') + - result.datasource.type == 'alexanderzobnin-zabbix-datasource' + - result.datasource.url == 'https://zabbix.example.com' + - result.datasource.user == '' + - not result.datasource.withCredentials + - result.msg == 'Datasource datasource-zabbix updated' - name: Delete zabbix datasource register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-zabbix grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - result.changed + - result.changed - name: Delete zabbix datasource (idempotency) register: result - grafana_datasource: + community.grafana.grafana_datasource: name: datasource-zabbix grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" grafana_password: "{{ grafana_password }}" state: absent -- assert: +- ansible.builtin.assert: that: - - not result.changed + - not result.changed diff --git a/tests/integration/targets/grafana_folder/defaults/main.yml b/tests/integration/targets/grafana_folder/defaults/main.yml index 8b9c9348..4abf9bb4 100644 --- a/tests/integration/targets/grafana_folder/defaults/main.yml +++ b/tests/integration/targets/grafana_folder/defaults/main.yml @@ -1,7 +1,5 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" - -... +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_folder/tasks/main.yml b/tests/integration/targets/grafana_folder/tasks/main.yml index c6a52056..cada94ab 100644 --- a/tests/integration/targets/grafana_folder/tasks/main.yml +++ b/tests/integration/targets/grafana_folder/tasks/main.yml @@ -1,55 +1,54 @@ --- - - name: Create a Folder grafana_folder: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - title: "grafana_working_group" - state: present + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + title: grafana_working_group + state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.folder.title == 'grafana_working_group'" + - result.changed == true + - result.folder.title == 'grafana_working_group' - name: Test folder creation idempotency grafana_folder: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - title: "grafana_working_group" - state: present + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + title: grafana_working_group + state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.folder.title == 'grafana_working_group'" + - result.changed == false + - result.folder.title == 'grafana_working_group' - name: Delete a Folder grafana_folder: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - title: "grafana_working_group" - state: absent + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + title: grafana_working_group + state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" + - result.changed == true - name: Test folder deletion idempotency grafana_folder: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - title: "grafana_working_group" - state: absent + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + title: grafana_working_group + state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" + - result.changed == false diff --git a/tests/integration/targets/grafana_notification_channel/defaults/main.yml b/tests/integration/targets/grafana_notification_channel/defaults/main.yml index 8b9c9348..4abf9bb4 100644 --- a/tests/integration/targets/grafana_notification_channel/defaults/main.yml +++ b/tests/integration/targets/grafana_notification_channel/defaults/main.yml @@ -1,7 +1,5 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" - -... +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml b/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml index 7279e313..75967099 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml @@ -1,19 +1,19 @@ --- - name: Create dingding notification channel register: result - grafana_notification_channel: + community.grafana.community.grafana.grafana_notification_channel: uid: dingding name: dingding type: dingding dingding_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == True - result.channel.name == "dingding" @@ -22,19 +22,19 @@ - name: Create dingding notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.community.grafana.grafana_notification_channel: uid: dingding name: dingding type: dingding dingding_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == False - result.channel.name == "dingding" @@ -43,32 +43,32 @@ - name: Delete dingding notification channel register: result - grafana_notification_channel: + community.grafana.community.grafana.grafana_notification_channel: uid: dingding state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == True - name: Delete dingding notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.community.grafana.grafana_notification_channel: uid: dingding state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/discord.yml b/tests/integration/targets/grafana_notification_channel/tasks/discord.yml index 29cfece7..30c70d63 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/discord.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/discord.yml @@ -1,19 +1,19 @@ --- - name: Create discord notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: discord name: discord type: discord discord_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == True - result.channel.name == "discord" @@ -22,19 +22,19 @@ - name: Create discord notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: discord name: discord type: discord discord_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == False - result.channel.name == "discord" @@ -43,32 +43,32 @@ - name: Delete discord notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: discord state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == True - name: Delete discord notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: discord state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/email.yml b/tests/integration/targets/grafana_notification_channel/tasks/email.yml index 85a236c9..29e18875 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/email.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/email.yml @@ -1,7 +1,7 @@ --- - name: Create email notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: email name: email type: email @@ -10,21 +10,21 @@ - bar@example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "email" - result.channel.type == "email" - result.channel.uid == "email" - name: Create email notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: email name: email type: email @@ -33,47 +33,47 @@ - bar@example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "email" - result.channel.type == "email" - result.channel.uid == "email" - name: Delete discord notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: email state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" - - "result.state == 'absent'" + - result.changed == True + - result.state == 'absent' - name: Delete discord notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: email state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml b/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml index abc7db64..8acdf0a6 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml @@ -1,74 +1,74 @@ --- - name: Create googlechat notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: googlechat name: googlechat type: googlechat googlechat_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "googlechat" - result.channel.uid == "googlechat" - result.channel.type == "googlechat" - name: Create googlechat notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: googlechat name: googlechat type: googlechat googlechat_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "googlechat" - result.channel.uid == "googlechat" - result.channel.type == "googlechat" - name: Delete googlechat notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: googlechat state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete googlechat notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: googlechat state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml b/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml index 4a9ec170..6423cafc 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml @@ -1,74 +1,74 @@ --- - name: Create hipchat notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: hipchat name: hipchat type: hipchat hipchat_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "hipchat" - result.channel.type == "hipchat" - result.channel.uid == "hipchat" - name: Create hipchat notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: hipchat name: hipchat type: hipchat hipchat_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "hipchat" - result.channel.type == "hipchat" - result.channel.uid == "hipchat" - name: Delete hipchat notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: hipchat state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete hipchat notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: hipchat state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml b/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml index ffc208ac..d8ec9cad 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml @@ -1,7 +1,7 @@ --- - name: Create kafka notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: kafka name: kafka type: kafka @@ -9,21 +9,21 @@ kafka_topic: test grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "kafka" - result.channel.uid == "kafka" - result.channel.type == "kafka" - name: Create kafka notification channel (idempotentcy) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: kafka name: kafka type: kafka @@ -31,46 +31,46 @@ kafka_topic: test grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "kafka" - result.channel.uid == "kafka" - result.channel.type == "kafka" - name: Delete kafka notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: kafka state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete kafka notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: kafka state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/line.yml b/tests/integration/targets/grafana_notification_channel/tasks/line.yml index 83a1863b..dde928c3 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/line.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/line.yml @@ -1,74 +1,74 @@ --- - name: Create line notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: line name: line type: line line_token: xxx grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.uid == "line" - result.channel.name == "line" - result.channel.type == "line" - name: Create line notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: line name: line type: line line_token: xxx grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.uid == "line" - result.channel.name == "line" - result.channel.type == "line" - name: Delete line notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: line state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete line notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: line state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/main.yml b/tests/integration/targets/grafana_notification_channel/tasks/main.yml index ceaf72ad..af0b2f86 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/main.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/main.yml @@ -1,20 +1,34 @@ --- - block: - - include_tasks: dingding.yml - - include_tasks: discord.yml - - include_tasks: email.yml - - include_tasks: googlechat.yml - - include_tasks: hipchat.yml - - include_tasks: kafka.yml -# - include_tasks: line.yml - - include_tasks: teams.yml - - include_tasks: opsgenie.yml - - include_tasks: pagerduty.yml - - include_tasks: prometheus.yml - - include_tasks: pushover.yml - - include_tasks: sensu.yml - - include_tasks: slack-and-beyond.yml - - include_tasks: telegram.yml -# - include_tasks: threema.yml - - include_tasks: victorops.yml - - include_tasks: webhook.yml + - ansible.builtin.include_tasks: + file: dingding.yml + - ansible.builtin.include_tasks: + file: discord.yml + - ansible.builtin.include_tasks: + file: email.yml + - ansible.builtin.include_tasks: + file: googlechat.yml + - ansible.builtin.include_tasks: + file: hipchat.yml + - ansible.builtin.include_tasks: + file: kafka.yml + - ansible.builtin.include_tasks: + file: teams.yml + - ansible.builtin.include_tasks: + file: opsgenie.yml + - ansible.builtin.include_tasks: + file: pagerduty.yml + - ansible.builtin.include_tasks: + file: prometheus.yml + - ansible.builtin.include_tasks: + file: pushover.yml + - ansible.builtin.include_tasks: + file: sensu.yml + - ansible.builtin.include_tasks: + file: slack-and-beyond.yml + - ansible.builtin.include_tasks: + file: telegram.yml + - ansible.builtin.include_tasks: + file: victorops.yml + - ansible.builtin.include_tasks: + file: webhook.yml diff --git a/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml b/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml index f871fe71..cd1048b8 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml @@ -1,7 +1,7 @@ --- - name: Create opsgenie notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: opsgenie name: opsgenie type: opsgenie @@ -9,21 +9,21 @@ opsgenie_api_key: xxx grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "opsgenie" - result.channel.type == "opsgenie" - result.channel.uid == "opsgenie" - name: Create opsgenie notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: opsgenie name: opsgenie type: opsgenie @@ -31,47 +31,47 @@ opsgenie_api_key: xxx grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "opsgenie" - result.channel.type == "opsgenie" - result.channel.uid == "opsgenie" - name: Delete opsgenie notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: opsgenie state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" - - "result.state == 'absent'" + - result.changed == True + - result.state == 'absent' - name: Delete opsgenie notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: opsgenie state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml b/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml index a8fa940b..40fd0046 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml @@ -1,74 +1,74 @@ --- - name: Create pagerduty notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pagerduty name: pagerduty type: pagerduty pagerduty_integration_key: xxx grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "pagerduty" - result.channel.type == "pagerduty" - result.channel.uid == "pagerduty" - name: Create pagerduty notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pagerduty name: pagerduty type: pagerduty pagerduty_integration_key: xxx grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "pagerduty" - result.channel.type == "pagerduty" - result.channel.uid == "pagerduty" - name: Delete pagerduty notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pagerduty state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete pagerduty notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pagerduty state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml b/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml index 40810eaf..c85d26f2 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml @@ -1,74 +1,74 @@ --- - name: Create prometheus notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: prometheus name: prometheus type: prometheus prometheus_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "prometheus" - result.channel.uid == "prometheus" - result.channel.type == "prometheus-alertmanager" - name: Create prometheus notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: prometheus name: prometheus type: prometheus prometheus_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "prometheus" - result.channel.uid == "prometheus" - result.channel.type == "prometheus-alertmanager" - name: Delete prometheus notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: prometheus state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete prometheus notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: prometheus state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml b/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml index 894bd71e..ee7b9bea 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml @@ -1,7 +1,7 @@ --- - name: Create pushover notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pushover name: pushover type: pushover @@ -9,21 +9,21 @@ pushover_user_key: yyy grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "pushover" - result.channel.uid == "pushover" - result.channel.type == "pushover" - name: Create pushover notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pushover name: pushover type: pushover @@ -31,46 +31,46 @@ pushover_user_key: yyy grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "pushover" - result.channel.uid == "pushover" - result.channel.type == "pushover" - name: Delete pushover notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pushover state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete pushover notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: pushover state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml b/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml index 01619b71..a46ef1d0 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml @@ -1,74 +1,74 @@ --- - name: Create sensu notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: sensu name: sensu type: sensu sensu_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "sensu" - result.channel.type == "sensu" - result.channel.uid == "sensu" - name: Create sensu notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: sensu name: sensu type: sensu sensu_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "sensu" - result.channel.type == "sensu" - result.channel.uid == "sensu" - name: Delete sensu notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: sensu state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete sensu notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: sensu state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml b/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml index 0748c8bd..1cbab6d5 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml @@ -1,110 +1,110 @@ --- - name: Create slack notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: slack name: slack type: slack slack_url: https://hooks.slack.com/services/xxx/yyy/zzz grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "slack" - result.channel.type == "slack" - result.channel.uid == "slack" - name: Create slack notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: slack name: slack type: slack slack_url: https://hooks.slack.com/services/xxx/yyy/zzz grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "slack" - result.channel.type == "slack" - result.channel.uid == "slack" - name: Check slack notification channel idempotency register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: slack name: slack type: slack slack_url: https://hooks.slack.com/services/xxx/yyy/zzz grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - name: Update slack notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: slack name: slack type: slack slack_url: https://hooks.slack.com/services/xxx/yyy/fff grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete slack notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: state: absent uid: slack grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete slack notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: state: absent uid: slack grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/teams.yml b/tests/integration/targets/grafana_notification_channel/tasks/teams.yml index cfc44aef..d9c7471c 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/teams.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/teams.yml @@ -1,74 +1,74 @@ --- - name: Create teams notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: teams name: teams type: teams teams_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "teams" - result.channel.uid == "teams" - result.channel.type == "teams" - name: Create teams notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: teams name: teams type: teams teams_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "teams" - result.channel.uid == "teams" - result.channel.type == "teams" - name: Delete teams notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: teams state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete teams notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: teams state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml b/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml index 98a7a3c6..38e27ef5 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml @@ -1,7 +1,7 @@ --- - name: Create telegram notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: telegram name: telegram type: telegram @@ -9,21 +9,21 @@ telegram_chat_id: yyy grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "telegram" - result.channel.type == "telegram" - result.channel.uid == "telegram" - name: Create telegram notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: telegram name: telegram type: telegram @@ -31,46 +31,46 @@ telegram_chat_id: yyy grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "telegram" - result.channel.type == "telegram" - result.channel.uid == "telegram" - name: Delete telegram notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: telegram state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete telegram notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: telegram state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/threema.yml b/tests/integration/targets/grafana_notification_channel/tasks/threema.yml index 7858b697..c61eae31 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/threema.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/threema.yml @@ -1,7 +1,7 @@ --- - name: Create threema notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: threema name: threema type: threema @@ -10,21 +10,21 @@ threema_api_secret: zzz grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "threema" - result.channel.type == "threema" - result.channel.uid == "threema" - name: Create threema notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: threema name: threema type: threema @@ -33,46 +33,46 @@ threema_api_secret: zzz grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "threema" - result.channel.type == "threema" - result.channel.uid == "threema" - name: Delete threema notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: threema state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete threema notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: threema state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml b/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml index 3779e813..e2167913 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml @@ -1,74 +1,74 @@ --- - name: Create victorops notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: victorops name: victorops type: victorops victorops_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "victorops" - result.channel.type == "victorops" - result.channel.uid == "victorops" - name: Create victorops notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: victorops name: victorops type: victorops victorops_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "victorops" - result.channel.type == "victorops" - result.channel.uid == "victorops" - name: Delete victorops notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: victorops state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete victorops notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: victorops state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml b/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml index c9efd919..5a00878f 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml @@ -1,74 +1,74 @@ --- - name: Create webhook notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: webhook name: webhook type: webhook webhook_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - result.channel.name == "webhook" - result.channel.uid == "webhook" - result.channel.type == "webhook" - name: Create webhook notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: webhook name: webhook type: webhook webhook_url: https://example.org grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False - result.channel.name == "webhook" - result.channel.uid == "webhook" - result.channel.type == "webhook" - name: Delete webhook notification channel register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: webhook state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == True" + - result.changed == True - name: Delete webhook notification channel (idempotency) register: result - grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: webhook state: absent grafana_url: "{{ grafana_url }}" grafana_user: "{{ grafana_username }}" - grafana_password: "{{ grafana_password}}" + grafana_password: "{{ grafana_password }}" -- debug: +- ansible.builtin.debug: var: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == False" + - result.changed == False diff --git a/tests/integration/targets/grafana_organization/defaults/main.yml b/tests/integration/targets/grafana_organization/defaults/main.yml index 7bb77ea3..3edac859 100644 --- a/tests/integration/targets/grafana_organization/defaults/main.yml +++ b/tests/integration/targets/grafana_organization/defaults/main.yml @@ -1,4 +1,4 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_organization/tasks/main.yml b/tests/integration/targets/grafana_organization/tasks/main.yml index f8ccdf3b..156bc940 100644 --- a/tests/integration/targets/grafana_organization/tasks/main.yml +++ b/tests/integration/targets/grafana_organization/tasks/main.yml @@ -1,5 +1,4 @@ --- - - name: Create a Grafana organization community.grafana.grafana_organization: url: "{{ grafana_url }}" @@ -8,13 +7,13 @@ name: orgtest state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.failed == false" - - "result.org.name == 'orgtest'" + - result.changed == true + - result.failed == false + - result.org.name == 'orgtest' -- name: check idempotency Grafana organization +- name: Check idempotency Grafana organization community.grafana.grafana_organization: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" @@ -22,11 +21,11 @@ name: orgtest state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.failed == false" - - "result.org.name == 'orgtest'" + - result.changed == false + - result.failed == false + - result.org.name == 'orgtest' - name: Delete a Grafana organization community.grafana.grafana_organization: @@ -36,13 +35,13 @@ name: orgtest state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.failed == false" - - "result.msg |length > 0" + - result.changed == true + - result.failed == false + - result.msg |length > 0 -- name: check idempotency delete a Grafana organization +- name: Check idempotency delete a Grafana organization community.grafana.grafana_organization: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" @@ -50,8 +49,8 @@ name: orgtest state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.failed == false" - - "result.msg == 'No org found, nothing to do'" + - result.changed == false + - result.failed == false + - result.msg == 'No org found, nothing to do' diff --git a/tests/integration/targets/grafana_organization_user/defaults/main.yml b/tests/integration/targets/grafana_organization_user/defaults/main.yml index 7bb77ea3..3edac859 100644 --- a/tests/integration/targets/grafana_organization_user/defaults/main.yml +++ b/tests/integration/targets/grafana_organization_user/defaults/main.yml @@ -1,4 +1,4 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_organization_user/tasks/main.yml b/tests/integration/targets/grafana_organization_user/tasks/main.yml index 3ede4f7c..6887670c 100644 --- a/tests/integration/targets/grafana_organization_user/tasks/main.yml +++ b/tests/integration/targets/grafana_organization_user/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: Create test user (default org 1) - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" @@ -19,10 +19,10 @@ login: orgtest state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" + - result.failed == false + - result.changed == true - name: Check idempotency on user removal from org community.grafana.grafana_organization_user: @@ -32,10 +32,10 @@ login: orgtest state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == false" + - result.failed == false + - result.changed == false - name: Add user to organization community.grafana.grafana_organization_user: @@ -46,12 +46,12 @@ role: viewer state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.user.orgId == 1" - - "result.user.role == 'Viewer'" + - result.failed == false + - result.changed == true + - result.user.orgId == 1 + - result.user.role == 'Viewer' - name: Update existing user role community.grafana.grafana_organization_user: @@ -62,12 +62,12 @@ role: editor state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.user.orgId == 1" - - "result.user.role == 'Editor'" + - result.failed == false + - result.changed == true + - result.user.orgId == 1 + - result.user.role == 'Editor' - name: Check idempotency on user update community.grafana.grafana_organization_user: @@ -78,10 +78,10 @@ role: editor state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == false" + - result.failed == false + - result.changed == false - name: Create a new organization community.grafana.grafana_organization: @@ -102,12 +102,12 @@ role: admin state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.user.orgId == org.org.id" - - "result.user.role == 'Admin'" + - result.failed == false + - result.changed == true + - result.user.orgId == org.org.id + - result.user.role == 'Admin' - name: Remove user from new organization by org_id community.grafana.grafana_organization_user: @@ -118,10 +118,10 @@ login: orgtest state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" + - result.failed == false + - result.changed == true - name: Add user to the new organization by org_name community.grafana.grafana_organization_user: @@ -133,12 +133,12 @@ role: admin state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" - - "result.user.orgId == org.org.id" - - "result.user.role == 'Admin'" + - result.failed == false + - result.changed == true + - result.user.orgId == org.org.id + - result.user.role == 'Admin' - name: Remove user from new organization by org_name community.grafana.grafana_organization_user: @@ -149,7 +149,7 @@ login: orgtest state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.failed == false" - - "result.changed == true" + - result.failed == false + - result.changed == true diff --git a/tests/integration/targets/grafana_team/defaults/main.yml b/tests/integration/targets/grafana_team/defaults/main.yml index 8b9c9348..4abf9bb4 100644 --- a/tests/integration/targets/grafana_team/defaults/main.yml +++ b/tests/integration/targets/grafana_team/defaults/main.yml @@ -1,7 +1,5 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" - -... +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_team/tasks/create_user.yml b/tests/integration/targets/grafana_team/tasks/create_user.yml index 6971d07b..9641e718 100644 --- a/tests/integration/targets/grafana_team/tasks/create_user.yml +++ b/tests/integration/targets/grafana_team/tasks/create_user.yml @@ -1,29 +1,30 @@ +--- - name: Create John Doe for tests purpose through uri module - uri: + ansible.builtin.uri: url: "{{ grafana_url }}api/admin/users" method: POST user: "{{ grafana_username }}" password: "{{ grafana_password }}" - force_basic_auth: yes + force_basic_auth: true body: - name: "John" - email: "john+doe@example.com" - login: "john" - password: "userpassword" + name: John + email: john+doe@example.com + login: john + password: userpassword body_format: json status_code: 200 - name: Create Jane Doe for tests purpose through uri module - uri: + ansible.builtin.uri: url: "{{ grafana_url }}api/admin/users" method: POST user: "{{ grafana_username }}" password: "{{ grafana_password }}" - force_basic_auth: yes + force_basic_auth: true body: - name: "Jane" - email: "jane.doe@example.com" - login: "jane" - password: "userpassword" + name: Jane + email: jane.doe@example.com + login: jane + password: userpassword body_format: json status_code: 200 diff --git a/tests/integration/targets/grafana_team/tasks/main.yml b/tests/integration/targets/grafana_team/tasks/main.yml index 2d74581b..74fb5c84 100644 --- a/tests/integration/targets/grafana_team/tasks/main.yml +++ b/tests/integration/targets/grafana_team/tasks/main.yml @@ -1,187 +1,188 @@ --- - - name: Create a Team - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + state: present register: result -- set_fact: +- ansible.builtin.set_fact: # From Grafana 9.0.0, the API user automatically becomes a member of the team auto_member: "{{ result.team.memberCount == 1 }}" -- set_fact: +- ansible.builtin.set_fact: expected_members: "{{ auto_member | ternary(['********@localhost'], []) }}" -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == true + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members - name: Check idempotency on team creation - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == false + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members - name: Check a team can be deleted - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - state: absent + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.message == 'Team deleted'" + - result.changed == true + - result.message == 'Team deleted' - name: Check idempotency on team deletion - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - state: absent + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.message == 'No team found'" + - result.changed == false + - result.message == 'No team found' - name: Create users for tests purpose - import_tasks: create_user.yml - + ansible.builtin.import_tasks: + file: create_user.yml - name: Create a Team with members - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - members: - - "john+doe@example.com" - - "jane.doe@example.com" - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + members: + - john+doe@example.com + - jane.doe@example.com + state: present register: result -- set_fact: - expected_members: "{{ auto_member | ternary(['********@localhost', 'jane.doe@example.com', 'john+doe@example.com'], ['jane.doe@example.com', 'john+doe@example.com']) }}" +- ansible.builtin.set_fact: + expected_members: "{{ auto_member | ternary(['********@localhost', 'jane.doe@example.com', 'john+doe@example.com'], ['jane.doe@example.com', 'john+doe@example.com']) + }}" -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == true + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members - name: Ensure a Team exists with member not enforced - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - members: - - "john+doe@example.com" - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + members: + - john+doe@example.com + state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == false + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members -- set_fact: +- ansible.builtin.set_fact: enforced_members: "{{ auto_member | ternary(['admin@localhost', 'john+doe@example.com'], ['john+doe@example.com']) }}" expected_members: "{{ auto_member | ternary(['********@localhost', 'john+doe@example.com'], ['john+doe@example.com']) }}" - name: Ensure a Team exists with member enforced - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - members: "{{ enforced_members }}" - enforce_members: true - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + members: "{{ enforced_members }}" + enforce_members: true + state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == true + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members - name: Ensure a Team exists with members omitted - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == false + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members - name: Add new member to existing Team - grafana_team: - url: "{{ grafana_url }}" - url_username: "{{ grafana_username }}" - url_password: "{{ grafana_password }}" - name: "grafana_working_group" - email: "foo.bar@example.com" - members: - - "john+doe@example.com" - - "jane.doe@example.com" - state: present + community.grafana.grafana_team: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: grafana_working_group + email: foo.bar@example.com + members: + - john+doe@example.com + - jane.doe@example.com + state: present register: result -- set_fact: - expected_members: "{{ auto_member | ternary(['********@localhost', 'jane.doe@example.com', 'john+doe@example.com'], ['jane.doe@example.com', 'john+doe@example.com']) }}" +- ansible.builtin.set_fact: + expected_members: "{{ auto_member | ternary(['********@localhost', 'jane.doe@example.com', 'john+doe@example.com'], ['jane.doe@example.com', 'john+doe@example.com']) + }}" -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.team.name == 'grafana_working_group'" - - "result.team.email == 'foo.bar@example.com'" - - "result.team.memberCount == (expected_members|length)" - - "result.team.members == expected_members" + - result.changed == true + - result.team.name == 'grafana_working_group' + - result.team.email == 'foo.bar@example.com' + - result.team.memberCount == (expected_members|length) + - result.team.members == expected_members diff --git a/tests/integration/targets/grafana_user/defaults/main.yml b/tests/integration/targets/grafana_user/defaults/main.yml index 7bb77ea3..3edac859 100644 --- a/tests/integration/targets/grafana_user/defaults/main.yml +++ b/tests/integration/targets/grafana_user/defaults/main.yml @@ -1,4 +1,4 @@ --- -grafana_url: "http://grafana:3000/" -grafana_username: "admin" -grafana_password: "admin" +grafana_url: http://grafana:3000/ +grafana_username: admin +grafana_password: admin diff --git a/tests/integration/targets/grafana_user/tasks/main.yml b/tests/integration/targets/grafana_user/tasks/main.yml index c6280165..01ded30b 100644 --- a/tests/integration/targets/grafana_user/tasks/main.yml +++ b/tests/integration/targets/grafana_user/tasks/main.yml @@ -1,237 +1,237 @@ --- - name: Create new admin - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Harley Quinn" + name: Harley Quinn email: harley.quinn@gotham.city login: harley password: Wy3ta6ob6M3wHELv58MPfqOe126RTnWpcYfEhyJm is_admin: true state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.failed == false" - - "result.user.name == 'Harley Quinn'" - - "result.user.email == 'harley.quinn@gotham.city'" - - "result.user.isGrafanaAdmin == true" + - result.changed == true + - result.failed == false + - result.user.name == 'Harley Quinn' + - result.user.email == 'harley.quinn@gotham.city' + - result.user.isGrafanaAdmin == true - name: Check idempotency on admin creation - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Harley Quinn" + name: Harley Quinn email: harley.quinn@gotham.city login: harley password: Wy3ta6ob6M3wHELv58MPfqOe126RTnWpcYfEhyJm is_admin: true state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.user.name == 'Harley Quinn'" - - "result.user.email == 'harley.quinn@gotham.city'" - - "result.user.isGrafanaAdmin == true" + - result.changed == false + - result.user.name == 'Harley Quinn' + - result.user.email == 'harley.quinn@gotham.city' + - result.user.isGrafanaAdmin == true - name: Check user creation with Grafana API - uri: + ansible.builtin.uri: url: "{{ grafana_url }}api/users/lookup?loginOrEmail=harley" user: "{{ grafana_username }}" password: "{{ grafana_password }}" - force_basic_auth: yes + force_basic_auth: true status_code: 200 headers: Accept: application/json Content-Type: application/json register: result -- assert: +- ansible.builtin.assert: that: - - "result.json.name == 'Harley Quinn'" - - "result.json.email == 'harley.quinn@gotham.city'" - - "result.json.isGrafanaAdmin == true" + - result.json.name == 'Harley Quinn' + - result.json.email == 'harley.quinn@gotham.city' + - result.json.isGrafanaAdmin == true - name: Create a Grafana user without password (expect failure) - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Bruce Wayne" + name: Bruce Wayne email: batman@gotham.city login: batman state: present register: result - ignore_errors: yes -- assert: + ignore_errors: true +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.failed == true" + - result.changed == false + - result.failed == true - "result.msg == 'missing required arguments: password'" - name: Create a Grafana user - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Bruce Wayne" + name: Bruce Wayne email: batman@gotham.city login: batman password: robin state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.user.name == 'Bruce Wayne'" - - "result.user.email == 'batman@gotham.city'" - - "result.user.isGrafanaAdmin == false" + - result.changed == true + - result.user.name == 'Bruce Wayne' + - result.user.email == 'batman@gotham.city' + - result.user.isGrafanaAdmin == false - name: Check idempotency on user creation (password not requiered) - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Bruce Wayne" + name: Bruce Wayne email: batman@gotham.city login: batman state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.user.name == 'Bruce Wayne'" - - "result.user.email == 'batman@gotham.city'" - - "result.user.isGrafanaAdmin == false" + - result.changed == false + - result.user.name == 'Bruce Wayne' + - result.user.email == 'batman@gotham.city' + - result.user.isGrafanaAdmin == false - name: Check user creation with Grafana API - uri: + ansible.builtin.uri: url: "{{ grafana_url }}api/users/lookup?loginOrEmail=batman" user: "{{ grafana_username }}" password: "{{ grafana_password }}" - force_basic_auth: yes + force_basic_auth: true status_code: 200 headers: Accept: application/json Content-Type: application/json register: result -- assert: +- ansible.builtin.assert: that: - - "result.json.name == 'Bruce Wayne'" - - "result.json.email == 'batman@gotham.city'" - - "result.json.isGrafanaAdmin == false" + - result.json.name == 'Bruce Wayne' + - result.json.email == 'batman@gotham.city' + - result.json.isGrafanaAdmin == false - name: Update Grafana user - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "The Dark Knight" + name: The Dark Knight email: thedarkknight@gotham.city login: batman password: robin is_admin: true state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.user.name == 'The Dark Knight'" - - "result.user.email == 'thedarkknight@gotham.city'" - - "result.user.isGrafanaAdmin == true" + - result.changed == true + - result.user.name == 'The Dark Knight' + - result.user.email == 'thedarkknight@gotham.city' + - result.user.isGrafanaAdmin == true - name: Check user update with Grafana API - uri: + ansible.builtin.uri: url: "{{ grafana_url }}api/users/lookup?loginOrEmail=batman" user: "{{ grafana_username }}" password: "{{ grafana_password }}" - force_basic_auth: yes + force_basic_auth: true status_code: 200 headers: Accept: application/json Content-Type: application/json register: result -- assert: +- ansible.builtin.assert: that: - - "result.json.name == 'The Dark Knight'" - - "result.json.email == 'thedarkknight@gotham.city'" - - "result.json.isGrafanaAdmin == true" + - result.json.name == 'The Dark Knight' + - result.json.email == 'thedarkknight@gotham.city' + - result.json.isGrafanaAdmin == true - name: Delete a Grafana user - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" login: batman state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.message == 'User deleted'" + - result.changed == true + - result.message == 'User deleted' - name: Check idempotency on user deletion - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" login: batman state: absent register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.message == 'No user found, nothing to do'" + - result.changed == false + - result.message == 'No user found, nothing to do' - name: Check user deletion with Grafana API (expect 404 Not Found) - uri: + ansible.builtin.uri: url: "{{ grafana_url }}api/users/lookup?loginOrEmail=batman" user: "{{ grafana_username }}" password: "{{ grafana_password }}" - force_basic_auth: yes + force_basic_auth: true status_code: 404 headers: Accept: application/json Content-Type: application/json register: result -- assert: +- ansible.builtin.assert: that: - - "result.json.message | lower == 'user not found'" + - result.json.message | lower == 'user not found' - name: Create a Grafana user with character encoding - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Bruce Wayne" + name: Bruce Wayne email: bruce+wayne@gotham.city login: bruce+wayne@gotham.city password: robin state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == true" - - "result.user.name == 'Bruce Wayne'" - - "result.user.email == 'bruce+wayne@gotham.city'" - - "result.user.isGrafanaAdmin == false" + - result.changed == true + - result.user.name == 'Bruce Wayne' + - result.user.email == 'bruce+wayne@gotham.city' + - result.user.isGrafanaAdmin == false - name: Check idempotency on user creation (password not requiered) - grafana_user: + community.grafana.grafana_user: url: "{{ grafana_url }}" url_username: "{{ grafana_username }}" url_password: "{{ grafana_password }}" - name: "Bruce Wayne" + name: Bruce Wayne email: bruce+wayne@gotham.city login: bruce+wayne@gotham.city state: present register: result -- assert: +- ansible.builtin.assert: that: - - "result.changed == false" - - "result.user.name == 'Bruce Wayne'" - - "result.user.email == 'bruce+wayne@gotham.city'" - - "result.user.isGrafanaAdmin == false" + - result.changed == false + - result.user.name == 'Bruce Wayne' + - result.user.email == 'bruce+wayne@gotham.city' + - result.user.isGrafanaAdmin == false From 339e2e0d2d52382ad8df25d923bb97095e9fea5f Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Thu, 4 Jan 2024 10:20:57 +0100 Subject: [PATCH 39/40] add changelog fragment! --- changelogs/fragments/325_linting.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 changelogs/fragments/325_linting.yml diff --git a/changelogs/fragments/325_linting.yml b/changelogs/fragments/325_linting.yml new file mode 100644 index 00000000..cfeff8a5 --- /dev/null +++ b/changelogs/fragments/325_linting.yml @@ -0,0 +1,2 @@ +trivial: + - fix linting with ansible-lint write. From 0aedf86f15e4019973c2439ed6be1231af426b6a Mon Sep 17 00:00:00 2001 From: Sebastian Gumprich Date: Thu, 4 Jan 2024 10:33:28 +0100 Subject: [PATCH 40/40] fixup! fixup! fix linting with ansible-lint write --- .../grafana_notification_channel/tasks/dingding.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml b/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml index 75967099..80d2f07d 100644 --- a/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml +++ b/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml @@ -1,7 +1,7 @@ --- - name: Create dingding notification channel register: result - community.grafana.community.grafana.grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: dingding name: dingding type: dingding @@ -22,7 +22,7 @@ - name: Create dingding notification channel (idempotency) register: result - community.grafana.community.grafana.grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: dingding name: dingding type: dingding @@ -43,7 +43,7 @@ - name: Delete dingding notification channel register: result - community.grafana.community.grafana.grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: dingding state: absent grafana_url: "{{ grafana_url }}" @@ -59,7 +59,7 @@ - name: Delete dingding notification channel (idempotency) register: result - community.grafana.community.grafana.grafana_notification_channel: + community.grafana.grafana_notification_channel: uid: dingding state: absent grafana_url: "{{ grafana_url }}"