diff options
Diffstat (limited to '')
88 files changed, 9226 insertions, 0 deletions
diff --git a/collections-debian-merged/ansible_collections/community/grafana/.all-contributorsrc b/collections-debian-merged/ansible_collections/community/grafana/.all-contributorsrc new file mode 100644 index 00000000..1eaec0ff --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/.all-contributorsrc @@ -0,0 +1,141 @@ +{ + "files": [ + "README.md" + ], + "imageSize": 100, + "commit": false, + "contributors": [ + { + "login": "gundalow", + "name": "John R Barker", + "avatar_url": "https://avatars1.githubusercontent.com/u/940557?v=4", + "profile": "https://github.com/gundalow", + "contributions": [ + "infra", + "test", + "code" + ] + }, + { + "login": "rrey", + "name": "Rémi REY", + "avatar_url": "https://avatars1.githubusercontent.com/u/2752379?v=4", + "profile": "https://github.com/rrey", + "contributions": [ + "test", + "doc" + ] + }, + { + "login": "seuf", + "name": "Thierry Sallé", + "avatar_url": "https://avatars1.githubusercontent.com/u/1336359?v=4", + "profile": "https://aperogeek.fr", + "contributions": [ + "code", + "test" + ] + }, + { + "login": "Tailzip", + "name": "Antoine", + "avatar_url": "https://avatars0.githubusercontent.com/u/1068018?v=4", + "profile": "http://antoine.tanzil.li", + "contributions": [ + "code", + "test" + ] + }, + { + "login": "pomverte", + "name": "hvle", + "avatar_url": "https://avatars0.githubusercontent.com/u/695230?v=4", + "profile": "https://github.com/pomverte", + "contributions": [ + "code", + "test" + ] + }, + { + "login": "jual", + "name": "jual", + "avatar_url": "https://avatars2.githubusercontent.com/u/4416541?v=4", + "profile": "https://github.com/jual", + "contributions": [ + "code", + "test" + ] + }, + { + "login": "MCyprien", + "name": "MCyprien", + "avatar_url": "https://avatars2.githubusercontent.com/u/11160859?v=4", + "profile": "https://github.com/MCyprien", + "contributions": [ + "code", + "test" + ] + }, + { + "login": "rockaut", + "name": "Markus Fischbacher", + "avatar_url": "https://avatars0.githubusercontent.com/u/453368?v=4", + "profile": "https://twitter.com/RealRockaut", + "contributions": [ + "code" + ] + }, + { + "login": "rverchere", + "name": "Remi Verchere", + "avatar_url": "https://avatars3.githubusercontent.com/u/232433?v=4", + "profile": "https://github.com/rverchere", + "contributions": [ + "code" + ] + }, + { + "login": "Akasurde", + "name": "Abhijeet Kasurde", + "avatar_url": "https://avatars1.githubusercontent.com/u/633765?v=4", + "profile": "http://akasurde.github.io", + "contributions": [ + "doc", + "test" + ] + }, + { + "login": "martinwangjian", + "name": "martinwangjian", + "avatar_url": "https://avatars2.githubusercontent.com/u/1770277?v=4", + "profile": "https://github.com/martinwangjian", + "contributions": [ + "code" + ] + }, + { + "login": "cwollinger", + "name": "cwollinger", + "avatar_url": "https://avatars2.githubusercontent.com/u/11299733?v=4", + "profile": "https://github.com/CWollinger", + "contributions": [ + "code" + ] + }, + { + "login": "Andersson007", + "name": "Andrew Klychkov", + "avatar_url": "https://avatars3.githubusercontent.com/u/34477873?v=4", + "profile": "https://github.com/Andersson007", + "contributions": [ + "code" + ] + } + ], + "contributorsPerLine": 7, + "projectName": "community.grafana", + "projectOwner": "ansible-collections", + "repoType": "github", + "repoHost": "https://github.com", + "skipCi": true +} diff --git a/collections-debian-merged/ansible_collections/community/grafana/.github/CODEOWNERS b/collections-debian-merged/ansible_collections/community/grafana/.github/CODEOWNERS new file mode 100644 index 00000000..3035cfbb --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/.github/CODEOWNERS @@ -0,0 +1,13 @@ +.github + +# Repo maintainers, and goverance team (like Anisble's @ansible-commit-external) +* @rrey @seuf @gundalow-collections/community-goverance-team + +# or possibly, we may want to define teams at the org level. +# * @gundalow-collections/grafana-maintainers + +# Example of maintainer of just a single plugin +#grafana/plugins/modules/grafana_plugin.py @someone-else + + +.github/ @gundalow diff --git a/collections-debian-merged/ansible_collections/community/grafana/.github/settings.yml b/collections-debian-merged/ansible_collections/community/grafana/.github/settings.yml new file mode 100644 index 00000000..9fde967c --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/.github/settings.yml @@ -0,0 +1,89 @@ +### +# https://probot.github.io/apps/settings/ +# + +# DO NOT MODIFY +# this is a copy of https://github.com/gundalow-collection/.github/blob/master/.github/settings.yml +# Work around till https://github.com/probot/settings/pull/179 is merged + + + +repository: + # See https://developer.github.com/v3/repos/#edit for all available settings. + has_issues: true + has_wiki: false + has_pages: false + default_branch: devel + allow_squash_merge: true + allow_merge_commit: false + allow_rebase_merge: true + +# Labels: define labels for Issues and Pull Requests +labels: + - name: bug + color: fbca04 + description: This issue/PR relates to a bug. + - name: feature + description: This issue/PR relates to a feature request. + color: 006b75 + - name: migrated_from_ansible_ansible + color: 5319e7 + description: This issue/PR was moved from gh/ansible/ansible + +branches: + - name: devel + # https://developer.github.com/v3/repos/branches/#update-branch-protection + # Branch Protection settings. Set to null to disable + protection: + # Required. Require at least one approving review on a pull request, before merging. Set to null to disable. + required_pull_request_reviews: + # The number of approvals required. (1-6) + required_approving_review_count: 1 + # Dismiss approved reviews automatically when a new commit is pushed. + dismiss_stale_reviews: true + # Blocks merge until code owners have reviewed. + require_code_owner_reviews: true + # Specify which users and teams can dismiss pull request reviews. Pass an empty dismissal_restrictions object to disable. User and team dismissal_restrictions are only available for organization-owned repositories. Omit this parameter for personal repositories. + dismissal_restrictions: + users: [] + teams: [] + # Required. Require status checks to pass before merging. Set to null to disable + required_status_checks: + # Required. Require branches to be up to date before merging. + strict: true + # Required. The list of status checks to require in order to merge into this branch + contexts: [] + # Required. Enforce all configured restrictions for administrators. Set to true to enforce required status checks for repository administrators. Set to null to disable. + enforce_admins: true + # Required. Restrict who can push to this branch. Team and user restrictions are only available for organization-owned repositories. Set to null to disable. + #restrictions: + # users: [] + # teams: [] + - name: master + # https://developer.github.com/v3/repos/branches/#update-branch-protection + # Branch Protection settings. Set to null to disable + protection: + # Required. Require at least one approving review on a pull request, before merging. Set to null to disable. + required_pull_request_reviews: + # The number of approvals required. (1-6) + required_approving_review_count: 1 + # Dismiss approved reviews automatically when a new commit is pushed. + dismiss_stale_reviews: true + # Blocks merge until code owners have reviewed. + require_code_owner_reviews: true + # Specify which users and teams can dismiss pull request reviews. Pass an empty dismissal_restrictions object to disable. User and team dismissal_restrictions are only available for organization-owned repositories. Omit this parameter for personal repositories. + dismissal_restrictions: + users: [] + teams: [] + # Required. Require status checks to pass before merging. Set to null to disable + required_status_checks: + # Required. Require branches to be up to date before merging. + strict: true + # Required. The list of status checks to require in order to merge into this branch + contexts: [] + # Required. Enforce all configured restrictions for administrators. Set to true to enforce required status checks for repository administrators. Set to null to disable. + enforce_admins: true + # Required. Restrict who can push to this branch. Team and user restrictions are only available for organization-owned repositories. Set to null to disable. + #restrictions: + # users: [] + # teams: [] diff --git a/collections-debian-merged/ansible_collections/community/grafana/.github/workflows/ansible-test.yml b/collections-debian-merged/ansible_collections/community/grafana/.github/workflows/ansible-test.yml new file mode 100644 index 00000000..7925eebb --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/.github/workflows/ansible-test.yml @@ -0,0 +1,89 @@ +name: CI +on: +- pull_request + +jobs: + sanity: + runs-on: ubuntu-latest + strategy: + matrix: + python_version: ["3.6"] + ansible_version: ["stable-2.9", "stable-2.10", "devel"] + steps: + + - name: Check out code + uses: actions/checkout@v1 + with: + path: ansible_collections/community/grafana + + - name: Set up Python ${{ matrix.python_version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python_version }} + + - name: Install ansible + run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible_version }}.tar.gz --disable-pip-version-check + + - name: Run sanity tests + run: ansible-test sanity --docker -v --color + + units: + runs-on: ubuntu-latest + strategy: + matrix: + python_version: ["3.6"] + ansible_version: ["stable-2.9", "stable-2.10", "devel"] + steps: + - name: Check out code + uses: actions/checkout@v1 + with: + path: ansible_collections/community/grafana + + - name: Set up Python ${{ matrix.python_version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python_version }} + + - name: Install ansible + run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible_version }}.tar.gz --disable-pip-version-check + + - name: Run unit tests + run: ansible-test units --docker -v --color --python ${{ matrix.python_version }} --coverage + + - name: Generate coverage report. + run: ansible-test coverage xml -v --requirements --group-by command --group-by version + + - uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: false + + integration: + runs-on: ubuntu-latest + strategy: + matrix: + grafana_version: ["6.7.4", "7.0.6", "7.1.3"] + ansible_version: ["stable-2.9", "stable-2.10", "devel"] + python_version: ["3.6"] + container: + image: python:${{ matrix.python_version }}-alpine + services: + grafana: + image: grafana/grafana:${{ matrix.grafana_version }} + steps: + + - name: Install requirements on alpine + run: apk add bash git gcc python3-dev libc-dev libffi-dev openssl-dev + + - name: Check out code + uses: actions/checkout@v1 + with: + path: ansible_collections/community/grafana + + - name: Install deps + run: pip install coverage + + - name: Install ansible + run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible_version }}.tar.gz --disable-pip-version-check + + - name: Run integration tests on Python ${{ matrix.python_version }} + run: ansible-test integration -v --color --retry-on-error --python ${{ matrix.python_version }} --continue-on-error --diff diff --git a/collections-debian-merged/ansible_collections/community/grafana/.github/workflows/rebase.yml b/collections-debian-merged/ansible_collections/community/grafana/.github/workflows/rebase.yml new file mode 100644 index 00000000..017a2faa --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/.github/workflows/rebase.yml @@ -0,0 +1,24 @@ +# https://github.com/marketplace/actions/automatic-rebase +# GitHub Actions don't automatically rebase before running, so add support for people to type `/rebase` +on: + issue_comment: + types: [created] +name: Automatic Rebase +jobs: + rebase: + name: Rebase + if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@1.2 + - name: Automatic Rebase + uses: cirrus-actions/rebase@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # https://github.community/t5/GitHub-Actions/Workflow-is-failing-if-no-job-can-be-ran-due-to-condition/m-p/38186#M3250 + always_job: + name: Aways run job + runs-on: ubuntu-latest + steps: + - name: Always run + run: echo "This job is used to prevent the workflow to fail when all other jobs are skipped." diff --git a/collections-debian-merged/ansible_collections/community/grafana/CHANGELOG.rst b/collections-debian-merged/ansible_collections/community/grafana/CHANGELOG.rst new file mode 100644 index 00000000..2d7fa2d5 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/CHANGELOG.rst @@ -0,0 +1,80 @@ +================================ +Grafana Collection Release Notes +================================ + +.. contents:: Topics + + +v1.1.0 +====== + +Minor Changes +------------- + +- Update the version where `message` alias will disappear from `grafana_dashboard`. (Now 2.0.0) + +New Modules +----------- + +- community.grafana.grafana_notification_channel - Manage Grafana Notification Channels + +v1.0.0 +====== + +Release Summary +--------------- + +Stable release for Ansible 2.10 and beyond + +Major Changes +------------- + +- Add changelog management for ansible 2.10 (#112) +- grafana_datasource ; adding additional_json_data param + +Known Issues +------------ + +- grafana_datasource doesn't set password correctly (#113) + +v0.2.2 +====== + +Bugfixes +-------- + +- Fix an issue in `grafana_dashboard` that made dashboard import no more detecting changes and fail. +- Refactor module `grafana_datasource` to ease its support. + +v0.2.1 +====== + +Bugfixes +-------- + +- Fix an issue with `grafana_datasource` idempotency + +v0.2.0 +====== + +Minor Changes +------------- + +- Add Thruk as Grafana Datasource +- Add `grafana_folder` module +- Add `grafana_user` module +- Use `module_utils` to allow code factorization + +Bugfixes +-------- + +- Fix issue `#45` in `grafana_plugin` + +v0.1.0 +====== + +Release Summary +--------------- + +Initial migration of Grafana content from Ansible core (2.9/devel) + diff --git a/collections-debian-merged/ansible_collections/community/grafana/FILES.json b/collections-debian-merged/ansible_collections/community/grafana/FILES.json new file mode 100644 index 00000000..f4a0082b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/FILES.json @@ -0,0 +1,894 @@ +{ + "files": [ + { + "name": ".", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".github", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".github/CODEOWNERS", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "27ba6e53b61251034d894049f866e4e15f9946b605b91756597e2a4727beef98", + "format": 1 + }, + { + "name": ".github/workflows", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".github/workflows/ansible-test.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8f8b291fb839a5dbb0fae766abcedf081de3991e08b0eba7b068dc9238f8fe2a", + "format": 1 + }, + { + "name": ".github/workflows/rebase.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "af21c44f389c778da76ab32ace5d6ea6a48f3407f7bb08ea902a0c593b55b25b", + "format": 1 + }, + { + "name": ".github/settings.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ac7c48229438311bfcb2676f762abadeb754d113288aab1f96389d4ce82de433", + "format": 1 + }, + { + "name": "changelogs", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "changelogs/config.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c60a0101ebb47b3d768f2d8c076a3b2383ce2a692d3795c0dc933669f95c3ecc", + "format": 1 + }, + { + "name": "changelogs/fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "changelogs/fragments/0.2.2.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8e9cce00704fea5f9764611503c1ed3ab12c23e34992ebba0525fd24c1e8dfbd", + "format": 1 + }, + { + "name": "changelogs/fragments/0.2.0.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1fb6466e60e26e40c30488eeaf29f72412ac294e621a851513ef3b989bb53b42", + "format": 1 + }, + { + "name": "changelogs/fragments/0.1.0.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1180e63b9f228a782274f5bea3ca438cc118b16eb78cc427c63ba7a64a77d1c4", + "format": 1 + }, + { + "name": "changelogs/fragments/1.0.0.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "cea50ea6c55adce42f435e1c04e45c8242a0739a21bae9a6e139317b8390e78b", + "format": 1 + }, + { + "name": "changelogs/fragments/update_deprecation.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a30e2092086b6fdfbc420b33cc2cb077eb81491ece7478ab93c9aef233906d60", + "format": 1 + }, + { + "name": "changelogs/fragments/0.2.1.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f7e30d2ec6d5a078fae4abd9544ef5980bfb31f60a7007a89372adf71f851c54", + "format": 1 + }, + { + "name": "changelogs/changelog.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "09850c59b52b01cc6e6fcbbeb0eb2fbf5123b55aa4c19252db9b773f4f5bc5eb", + "format": 1 + }, + { + "name": ".all-contributorsrc", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b8418ed48b5b2b53de790a10c7005e3baa2a8fa1715418ed7444ddfd239f4cb5", + "format": 1 + }, + { + "name": "LICENSE", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "format": 1 + }, + { + "name": "plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/module_utils", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/module_utils/base.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9fc5d3ef1729cba9abae7e320e7e485d34d5a28d48e05188f49f82dd60dbefb4", + "format": 1 + }, + { + "name": "plugins/callback", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/callback/grafana_annotations.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c5e2efa8f72288bdcf5cb3c7d5cd4252180b358e3d8997744aba2f6e689be71b", + "format": 1 + }, + { + "name": "plugins/callback/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules/grafana_folder.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4d3cd61f81c6b2ba0d621fe1973b4b9e585c61f53a6462b5360e396871003c4f", + "format": 1 + }, + { + "name": "plugins/modules/grafana_plugin.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "dad043e80ae3c29f6d3a284e3bee330a09a1eabc62f73de9ed1cfdf846df9d3c", + "format": 1 + }, + { + "name": "plugins/modules/grafana_user.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a1bc42ff52de36105e31b608df6e5d2436fa3254bf56617e990097389f138471", + "format": 1 + }, + { + "name": "plugins/modules/grafana_team.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "818999620f2343afe865236c617b0f85763c91ea9d25accabbc6bd9c05dc5f51", + "format": 1 + }, + { + "name": "plugins/modules/grafana_notification_channel.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6d769a0a22eeb15ebcf2efa86c86316b64ab144e8c1f21c3758767d9d490bc81", + "format": 1 + }, + { + "name": "plugins/modules/grafana_dashboard.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "feea76a4a6158d21e4217ff58f4d1ff9ada33c472d748fed658f24c75a25718e", + "format": 1 + }, + { + "name": "plugins/modules/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "plugins/modules/grafana_datasource.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "62e745e579588543117b9b1fc6506e04d4fce10acbed00aa8e588e22e01bff4d", + "format": 1 + }, + { + "name": "plugins/lookup", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/lookup/grafana_dashboard.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8af0840bb64958e93c66873b5bbd21ff324f4f3a130dcad63e3d112680728f33", + "format": 1 + }, + { + "name": "plugins/lookup/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "plugins/doc_fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/doc_fragments/basic_auth.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "fff91970e34eca089abc8275b82957c07acd78889db684281be97252a5b6d27b", + "format": 1 + }, + { + "name": "plugins/doc_fragments/api_key.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bb4e6492b954294664aa87ac44bd12ffa42e59ddfcedd693e5a486b42c352dc1", + "format": 1 + }, + { + "name": "plugins/doc_fragments/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "meta/runtime.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c03f11d23823bc02cb96a7d367906c9dab8fa9aeba23be4ba0263018359130e5", + "format": 1 + }, + { + "name": "CHANGELOG.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5c42ff439009193de623ced6f7a90abad8f2f64be9a4f39efd1edebf5e48e2ac", + "format": 1 + }, + { + "name": "codecov.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e55a41874408d15b899f7df85fa9f4c6c3c476cf4a9e919b9a396c3f1aa1a1f0", + "format": 1 + }, + { + "name": "README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "04e6b26f44fc448ebb034ceae5f6df9804decef2136268dd73226b836584ae49", + "format": 1 + }, + { + "name": "tests", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_folder", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_folder/defaults", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_folder/defaults/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7c9856c26c7fda2df3157d1a25073f8268f4e0b642f560690f40c9e83ca3b62c", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_folder/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_folder/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "47bc05ebcddd2fe27fa914c732be64a7c2c6378578d5c8cb6429d73f25d355f5", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_user", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_user/defaults", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_user/defaults/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e1fd56ed28989838abaca1d4b86ac2abd1d819607f1556a15347a5f9836781d8", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_user/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_user/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "511dd9c886a1c6553b38daf29bed681e02ba22f42114dbf6232428d0bcf97d53", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/aliases", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "811322fad85866ac31f9501f8da0c7072809065397d53c06712447946b746b6b", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/files", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/files/dashboard.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "81bf045dfa0d6e8262abf423ceb0fc008c8db82ba9616c4ce9a5ac7679bc1fa8", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/defaults", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/defaults/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7c9856c26c7fda2df3157d1a25073f8268f4e0b642f560690f40c9e83ca3b62c", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "468c55bbc58254f1e956f8b6eaf318b863e88270f9741a05fd63643d18ced748", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4987b17b353b126c059e60e83ea081eacd83b149d6aeed0ab9d34c013322d574", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f679381b8db000fb5bf0e1166fd78196a63efc8c0bba4a8917ae02f85e54c295", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "abaf3c4b643d2f893fd05849de8ee8f15ed14ae74a24cb9b252db54c64415478", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_dashboard/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "47ab2644c2627aec121762a9372dd7832e69831f971a6ddf1f8cb14af5099619", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/aliases", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "811322fad85866ac31f9501f8da0c7072809065397d53c06712447946b746b6b", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/defaults", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/defaults/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7c9856c26c7fda2df3157d1a25073f8268f4e0b642f560690f40c9e83ca3b62c", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/postgres.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f294c23faa7ee6f4016fdd933fd9a44bef770b20f66ea043f6b9052a4f74cc4f", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "556537a82506b9f848059c16cf72a60b937fbe199ac5b935ca80cca90a9b13af", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/zabbix.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "948eeec1081dc4b3e88931a969f77a586f0dbac8956460a340a077e20cf246db", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/thruk.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5872025c77594c314e604807c5520fa1b8650a9d13dffdbeea93c4cbd452960e", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/influx.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0c07304999b4a207211ef2ababc3bea780975f10356508e01e8e98866bf5ee86", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/loki.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "21cdeab1a809f8cc1bee5e9479146b8ca336bbcefbc97defc9bd9ff60ebefae0", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/elastic.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "20cb49b7e5ce4155b098aa0f30c1a5eb87de2cb689fffcebc6b23ea46e989b7e", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_datasource/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6a02ed05d418c68feeb0fd6514713a231f87dbc46140e6010d94a0e968c609d8", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/defaults", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/defaults/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7c9856c26c7fda2df3157d1a25073f8268f4e0b642f560690f40c9e83ca3b62c", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/teams.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "731dc10671551b9224fbf451e9cdb8797637a57138e5ddb2084902f5745946d9", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "61d1fbbf982c2f8a42a77ce24a0f4e76a65e4f6aab04f177af2c87df3ebf6a89", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/webhook.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4690809e4c123151a33d2bca9b24fc83e100a30bc0839dbd45987e479fa8774a", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bcd2cf03b12275bfed73d65ce763a44672f6d40d08b475588208775c9c3d0ef2", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/kafka.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "160adbef4ee0530b0451cacc7f260ec737c35390b0d683d614377d91325b10a2", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/victorops.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "35b5a4597766e708a1294c1db0ed5518dbb782eff022c1260e543d2f14250726", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/dingding.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4afd5b1a0726d9c1edf89a35f8c0872ea75a901a0b95d66272bcaea1866bbdad", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/pushover.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "72fc38490afc2de6e5fa53cbba5781cd6c4dda29346598aecd64bd2d6c5acdf5", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1e2650581856bb750388a331573205cd5bc11b3748d913994ae0dced1cc9373f", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/discord.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3dc3a14993292f1e8d6210a71c11a2b295a9c775daba4ecd0ae12c86109ebe3e", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "be4455c6c8fb29ed9564a045164334c49832ffa47e64e3c2ec4d8ea5f1d1c0da", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9a754c4d6c61928d616c60ce8a12e7874308e7738a97e17e82a49aadb0f18e86", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "cec677cc924c033ea9c51d741f1c54020cf9ffc4ff51b1c5b60c7f15f5308b75", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/threema.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8c1ffe9acb5166afaff89c2a5e2f098d2ef5a534b4cbe2ad5f1e3a98f6dc38ce", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/email.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3d392ac07e1c2ef4eda3ce61824b6a358c2189585f2dc34c5863e4bc31a07f65", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/telegram.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a6bc11253ab25301708f8df6e1780e500373c0c1bde1d775b073f0d99f04c80d", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/sensu.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7c00cfdcd5fa64ec902b0797cacf2aaba35367defd1f18e89dbb1787393d7940", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/line.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "29488c65be33dab429c51563a46a116afd589253711711f813dfc8ad3f41cdc4", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_notification_channel/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "65fcde828d6cc9d15b7dc90e19ac15b2e10d4c66607d72c6f2bda447ff939279", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_team", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_team/defaults", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_team/defaults/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7c9856c26c7fda2df3157d1a25073f8268f4e0b642f560690f40c9e83ca3b62c", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_team/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_team/tasks/create_user.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2a057bff7c515928bcbae824311828bdd60c48092805560bc009e3c27c795621", + "format": 1 + }, + { + "name": "tests/integration/targets/grafana_team/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9d1651fdd1cde28a688cc97b7343fd490215db946eacdff0eeef9dff7873b3b5", + "format": 1 + }, + { + "name": "tests/sanity", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.11.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6f30433f464a48b8503f0fbf5e5bc44ca112acc6b75535490493c398cd7c97c9", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.10.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6f30433f464a48b8503f0fbf5e5bc44ca112acc6b75535490493c398cd7c97c9", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.9.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9c94aed17d123ac549159a77f80adcb3a16c714f544fbbe6a092a5dcf0861dc9", + "format": 1 + }, + { + "name": "tests/unit", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/modules/grafana", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/modules/grafana/grafana_plugin", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c7b7015b793f75de5c19cd95772a8aaa170eca6e508a305755f61ae11495e4f1", + "format": 1 + }, + { + "name": "tests/unit/modules/grafana/grafana_user", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/modules/grafana/grafana_user/test_grafana_user.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ebe4eca4179be5a9780ef606dbd01da1e8512df914b9d576a256a9f0b72c66bb", + "format": 1 + }, + { + "name": "tests/unit/modules/grafana/grafana_team", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/modules/grafana/grafana_team/test_grafana_team.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "96116b92002f89708a978cf54ba9209234bc65622b82ea37f67b942a8d19b849", + "format": 1 + }, + { + "name": "tests/.gitignore", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b5726d3ec9335a09c124469eca039523847a6b0f08a083efaefd002b83326600", + "format": 1 + } + ], + "format": 1 +}
\ No newline at end of file diff --git a/collections-debian-merged/ansible_collections/community/grafana/LICENSE b/collections-debian-merged/ansible_collections/community/grafana/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/collections-debian-merged/ansible_collections/community/grafana/MANIFEST.json b/collections-debian-merged/ansible_collections/community/grafana/MANIFEST.json new file mode 100644 index 00000000..2078bb4e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/MANIFEST.json @@ -0,0 +1,32 @@ +{ + "collection_info": { + "namespace": "community", + "name": "grafana", + "version": "1.1.0", + "authors": [ + "R\u00e9mi REY (@rrey)", + "Thierry Sall\u00e9 (@seuf)" + ], + "readme": "README.md", + "tags": [ + "monitoring", + "grafana" + ], + "description": "Collection allowing to interact with Grafana APIs", + "license": [], + "license_file": "LICENSE", + "dependencies": {}, + "repository": "https://github.com/ansible-collections/grafana.git", + "documentation": "https://github.com/ansible-collections/grafana.git", + "homepage": "https://github.com/ansible-collections/grafana", + "issues": "https://github.com/ansible-collections/grafana/issues" + }, + "file_manifest_file": { + "name": "FILES.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "085c537708e753dccbd2467de4a96c9021e7ca7dec5a785758609cea70dddb3e", + "format": 1 + }, + "format": 1 +}
\ No newline at end of file diff --git a/collections-debian-merged/ansible_collections/community/grafana/README.md b/collections-debian-merged/ansible_collections/community/grafana/README.md new file mode 100644 index 00000000..4947b4d7 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/README.md @@ -0,0 +1,176 @@ +# Grafana Collection for Ansible + +![](https://github.com/ansible-collections/grafana/workflows/CI/badge.svg?branch=master) +[![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/grafana)](https://codecov.io/gh/ansible-collections/community.grafana) +<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --> +[![All Contributors](https://img.shields.io/badge/all_contributors-13-orange.svg?style=flat-square)](#contributors-) +<!-- ALL-CONTRIBUTORS-BADGE:END --> + +This repo hosts the `community.grafana` Ansible Collection. + +The collection includes a variety of Ansible content to help automate the management of resources in Grafana. + +## Included content + +Click on the name of a plugin or module to view that content's documentation: + + - **Connection Plugins**: + - **Filter Plugins**: + - **Inventory Source**: + - **Callback Plugins**: + - [grafana_annotations](https://docs.ansible.com/ansible/latest/plugins/callback/grafana_annotations.html) + - **Lookup Plugins**: + - [grafana_dashboard](https://docs.ansible.com/ansible/latest/plugins/lookup/grafana_dashboard.html) + - **Modules**: + - [grafana_dashboard](https://docs.ansible.com/ansible/latest/modules/grafana_dashboard_module.html) + - [grafana_datasource](https://docs.ansible.com/ansible/latest/modules/grafana_datasource_module.html) + - grafana_folder + - [grafana_plugin](https://docs.ansible.com/ansible/latest/modules/grafana_plugin_module.html) + - grafana_team + - grafana_user + +## Supported Grafana versions + +We aim at keeping the last 3 minor versions (at least) of Grafana tested. +This collection is currently testing the modules against Grafana versions `6.7.4`, `7.0.6`, and `7.1.3`. + +## Installation and Usage + +### Installing the Collection from Ansible Galaxy + +Before using the Grafana collection, you need to install it with the Ansible Galaxy CLI: + + ansible-galaxy collection install community.grafana + +You can also include it in a `requirements.yml` file and install it via `ansible-galaxy collection install -r requirements.yml`, using the format: + +```yaml +--- +collections: + - name: community.grafana + version: 1.0.0 +``` + +### Using modules from the Grafana Collection in your playbooks + +You can either call modules by their Fully Qualified Collection Namespace (FQCN), like `community.grafana.grafana_datasource`, or you can call modules by their short name if you list the `community.grafana` collection in the playbook's `collections`, like so: + +```yaml +--- +- hosts: localhost + gather_facts: false + connection: local + + collections: + - community.grafana + + tasks: + - name: Ensure Influxdb datasource exists. + grafana_datasource: + name: "datasource-influxdb" + grafana_url: "https://grafana.company.com" + grafana_user: "admin" + grafana_password: "xxxxxx" + org_id: "1" + ds_type: "influxdb" + ds_url: "https://influx.company.com:8086" + database: "telegraf" + time_interval: ">10s" + tls_ca_cert: "/etc/ssl/certs/ca.pem" +``` + +For documentation on how to use individual modules and other content included in this collection, please see the links in the 'Included content' section earlier in this README. + +## Testing and Development + +If you want to develop new content for this collection or improve what's already here, the easiest way to work on the collection is to clone it into one of the configured [`COLLECTIONS_PATHS`](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#collections-paths), and work on it there. + +### Testing with `ansible-test` + +The `tests` directory contains configuration for running sanity and integration tests using [`ansible-test`](https://docs.ansible.com/ansible/latest/dev_guide/testing_integration.html). + +You can run the collection's test suites with the commands: + + ansible-test sanity --docker -v --color + ansible-test integration --docker -v --color + +## Publishing New Versions + +The current process for publishing new versions of the Grafana Collection is manual, and requires a user who has access to the `community.grafana` namespace on Ansible Galaxy to publish the build artifact. + + 1. Ensure `CHANGELOG.md` contains all the latest changes. + 2. Update `galaxy.yml` and this README's `requirements.yml` example with the new `version` for the collection. + 3. Tag the version in Git and push to GitHub. + 4. Run the following commands to build and release the new version on Galaxy: + + ``` + ansible-galaxy collection build + ansible-galaxy collection publish ./community-grafana-$VERSION_HERE.tar.gz + ``` + +After the version is published, verify it exists on the [Grafana Collection Galaxy page](https://galaxy.ansible.com/community/grafana). + +## Changelogs + +* Every change that does not only affect docs or tests must have a changelog fragment. + * Exception: fixing/extending a feature that already has a changelog fragment and has not yet been released. Such PRs must always link to the original PR(s) they update. + * Use your common sense! + * (This might change later. The trivial category should then be used to document changes which are not important enough to end up in the text version of the changelog.) + * Fragments must not be added for new module PRs and new plugin PRs. The only exception are test and filter plugins: these are not automatically documented yet. +* The (x+1).0.0 changelog continues the x.0.0 changelog. + * A x.y.0 changelog with y > 0 is not part of a changelog of a later X.*.* (with X > x) or x,Y,* (with Y > y) release. + * A x.y.z changelog with z > 0 is not part of a changelog of a later (x+1).*.* or x.Y.z (with Y > y) release. +Since everything adding to the minor/patch changelogs are backports, the same changelog fragments of these minor/patch releases will be in the next major release's changelog. (This is the same behavior as in ansible/ansible.) +* Changelogs do not contain previous major releases, and only use the ancestor feature (in changelogs/changelog.yaml) to point to the previous major release. +* Changelog fragments are removed after a release is made. + +See [antsibull-changelog documentation](https://github.com/ansible-community/antsibull-changelog/blob/main/docs/changelogs.rst#changelog-fragment-categories) + +## More Information + +For more information about Ansible's Grafana integration, join the `#ansible-community` channel on Freenode IRC, and browse the resources in the [Grafana Working Group](https://github.com/ansible/community/wiki/Grafana) Community wiki page. + +## License + +GNU General Public License v3.0 or later + +See LICENCE to see the full text. + +## Contributing + +Any contribution is welcome and we only ask contributors to: +* Provide *at least* integration tests for any contribution. +* Create an issues for any significant contribution that would change a large portion of the code base. + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + +<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> +<!-- prettier-ignore-start --> +<!-- markdownlint-disable --> +<table> + <tr> + <td align="center"><a href="https://github.com/gundalow"><img src="https://avatars1.githubusercontent.com/u/940557?v=4" width="100px;" alt=""/><br /><sub><b>John R Barker</b></sub></a><br /><a href="#infra-gundalow" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=gundalow" title="Tests">⚠️</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=gundalow" title="Code">💻</a></td> + <td align="center"><a href="https://github.com/rrey"><img src="https://avatars1.githubusercontent.com/u/2752379?v=4" width="100px;" alt=""/><br /><sub><b>Rémi REY</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=rrey" title="Tests">⚠️</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=rrey" title="Documentation">📖</a></td> + <td align="center"><a href="https://aperogeek.fr"><img src="https://avatars1.githubusercontent.com/u/1336359?v=4" width="100px;" alt=""/><br /><sub><b>Thierry Sallé</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=seuf" title="Code">💻</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=seuf" title="Tests">⚠️</a></td> + <td align="center"><a href="http://antoine.tanzil.li"><img src="https://avatars0.githubusercontent.com/u/1068018?v=4" width="100px;" alt=""/><br /><sub><b>Antoine</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=Tailzip" title="Code">💻</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=Tailzip" title="Tests">⚠️</a></td> + <td align="center"><a href="https://github.com/pomverte"><img src="https://avatars0.githubusercontent.com/u/695230?v=4" width="100px;" alt=""/><br /><sub><b>hvle</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=pomverte" title="Code">💻</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=pomverte" title="Tests">⚠️</a></td> + <td align="center"><a href="https://github.com/jual"><img src="https://avatars2.githubusercontent.com/u/4416541?v=4" width="100px;" alt=""/><br /><sub><b>jual</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=jual" title="Code">💻</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=jual" title="Tests">⚠️</a></td> + <td align="center"><a href="https://github.com/MCyprien"><img src="https://avatars2.githubusercontent.com/u/11160859?v=4" width="100px;" alt=""/><br /><sub><b>MCyprien</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=MCyprien" title="Code">💻</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=MCyprien" title="Tests">⚠️</a></td> + </tr> + <tr> + <td align="center"><a href="https://twitter.com/RealRockaut"><img src="https://avatars0.githubusercontent.com/u/453368?v=4" width="100px;" alt=""/><br /><sub><b>Markus Fischbacher</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=rockaut" title="Code">💻</a></td> + <td align="center"><a href="https://github.com/rverchere"><img src="https://avatars3.githubusercontent.com/u/232433?v=4" width="100px;" alt=""/><br /><sub><b>Remi Verchere</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=rverchere" title="Code">💻</a></td> + <td align="center"><a href="http://akasurde.github.io"><img src="https://avatars1.githubusercontent.com/u/633765?v=4" width="100px;" alt=""/><br /><sub><b>Abhijeet Kasurde</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=Akasurde" title="Documentation">📖</a> <a href="https://github.com/ansible-collections/community.grafana/commits?author=Akasurde" title="Tests">⚠️</a></td> + <td align="center"><a href="https://github.com/martinwangjian"><img src="https://avatars2.githubusercontent.com/u/1770277?v=4" width="100px;" alt=""/><br /><sub><b>martinwangjian</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=martinwangjian" title="Code">💻</a></td> + <td align="center"><a href="https://github.com/CWollinger"><img src="https://avatars2.githubusercontent.com/u/11299733?v=4" width="100px;" alt=""/><br /><sub><b>cwollinger</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=cwollinger" title="Code">💻</a></td> + <td align="center"><a href="https://github.com/Andersson007"><img src="https://avatars3.githubusercontent.com/u/34477873?v=4" width="100px;" alt=""/><br /><sub><b>Andrew Klychkov</b></sub></a><br /><a href="https://github.com/ansible-collections/community.grafana/commits?author=Andersson007" title="Code">💻</a></td> + </tr> +</table> + +<!-- markdownlint-enable --> +<!-- prettier-ignore-end --> +<!-- ALL-CONTRIBUTORS-LIST:END --> + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/changelog.yaml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/changelog.yaml new file mode 100644 index 00000000..210b0f1d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/changelog.yaml @@ -0,0 +1,61 @@ +ancestor: null +releases: + 0.1.0: + changes: + release_summary: 'Initial migration of Grafana content from Ansible core (2.9/devel) + + ' + fragments: + - 0.1.0.yml + release_date: '2019-12-27' + 0.2.0: + changes: + bugfixes: + - Fix issue `#45` in `grafana_plugin` + minor_changes: + - Add Thruk as Grafana Datasource + - Add `grafana_folder` module + - Add `grafana_user` module + - Use `module_utils` to allow code factorization + fragments: + - 0.2.0.yml + release_date: '2020-02-26' + 0.2.1: + changes: + bugfixes: + - Fix an issue with `grafana_datasource` idempotency + fragments: + - 0.2.1.yml + release_date: '2020-03-18' + 0.2.2: + changes: + bugfixes: + - Fix an issue in `grafana_dashboard` that made dashboard import no more detecting + changes and fail. + - Refactor module `grafana_datasource` to ease its support. + fragments: + - 0.2.2.yml + release_date: '2020-03-30' + 1.0.0: + changes: + known_issues: + - grafana_datasource doesn't set password correctly (#113) + major_changes: + - Add changelog management for ansible 2.10 (#112) + - grafana_datasource ; adding additional_json_data param + release_summary: Stable release for Ansible 2.10 and beyond + fragments: + - 1.0.0.yml + release_date: '2020-08-16' + 1.1.0: + changes: + minor_changes: + - Update the version where `message` alias will disappear from `grafana_dashboard`. + (Now 2.0.0) + fragments: + - update_deprecation.yml + modules: + - description: Manage Grafana Notification Channels + name: grafana_notification_channel + namespace: '' + release_date: '2020-11-16' diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/config.yaml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/config.yaml new file mode 100644 index 00000000..86afd70b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/config.yaml @@ -0,0 +1,31 @@ +changelog_filename_template: ../CHANGELOG.rst +changelog_filename_version_depth: 0 +changes_file: changelog.yaml +changes_format: combined +ignore_other_fragment_extensions: true +keep_fragments: true +mention_ancestor: true +new_plugins_after_name: removed_features +notesdir: fragments +prelude_section_name: release_summary +prelude_section_title: Release Summary +sections: +- - major_changes + - Major Changes +- - minor_changes + - Minor Changes +- - breaking_changes + - Breaking Changes / Porting Guide +- - deprecated_features + - Deprecated Features +- - removed_features + - Removed Features (previously deprecated) +- - security_fixes + - Security Fixes +- - bugfixes + - Bugfixes +- - known_issues + - Known Issues +title: Grafana Collection +trivial_section_name: trivial +use_fqcn: true diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.1.0.yml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.1.0.yml new file mode 100644 index 00000000..f81c41c4 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.1.0.yml @@ -0,0 +1,2 @@ +release_summary: | + Initial migration of Grafana content from Ansible core (2.9/devel) diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.0.yml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.0.yml new file mode 100644 index 00000000..2e7a83ea --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.0.yml @@ -0,0 +1,7 @@ +bugfixes: +- Fix issue `#45` in `grafana_plugin` +minor_changes: +- Add Thruk as Grafana Datasource +- Add `grafana_user` module +- Add `grafana_folder` module +- Use `module_utils` to allow code factorization diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.1.yml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.1.yml new file mode 100644 index 00000000..d4ff484d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.1.yml @@ -0,0 +1,2 @@ +bugfixes: +- Fix an issue with `grafana_datasource` idempotency diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.2.yml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.2.yml new file mode 100644 index 00000000..c74c9769 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/0.2.2.yml @@ -0,0 +1,3 @@ +bugfixes: +- Fix an issue in `grafana_dashboard` that made dashboard import no more detecting changes and fail. +- Refactor module `grafana_datasource` to ease its support. diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/1.0.0.yml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/1.0.0.yml new file mode 100644 index 00000000..d121711b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/1.0.0.yml @@ -0,0 +1,6 @@ +release_summary: Stable release for Ansible 2.10 and beyond +major_changes: +- grafana_datasource ; adding additional_json_data param +- Add changelog management for ansible 2.10 (#112) +known_issues: +- grafana_datasource doesn't set password correctly (#113) diff --git a/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/update_deprecation.yml b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/update_deprecation.yml new file mode 100644 index 00000000..7489327e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/changelogs/fragments/update_deprecation.yml @@ -0,0 +1,2 @@ +minor_changes: +- Update the version where `message` alias will disappear from `grafana_dashboard`. (Now 2.0.0) diff --git a/collections-debian-merged/ansible_collections/community/grafana/codecov.yml b/collections-debian-merged/ansible_collections/community/grafana/codecov.yml new file mode 100644 index 00000000..f0f6358e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/codecov.yml @@ -0,0 +1,4 @@ +coverage: + precision: 2 + round: down + range: "70...100" diff --git a/collections-debian-merged/ansible_collections/community/grafana/meta/runtime.yml b/collections-debian-merged/ansible_collections/community/grafana/meta/runtime.yml new file mode 100644 index 00000000..576832bc --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/meta/runtime.yml @@ -0,0 +1,2 @@ +--- +requires_ansible: '>=2.9.0' diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/callback/__init__.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/callback/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/callback/__init__.py diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/callback/grafana_annotations.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/callback/grafana_annotations.py new file mode 100644 index 00000000..04b61f25 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/callback/grafana_annotations.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +DOCUMENTATION = ''' + name: grafana_annotations + type: notification + short_description: send ansible events as annotations on charts to grafana over http api. + author: "Rémi REY (@rrey)" + description: + - This callback will report start, failed and stats events to Grafana as annotations (https://grafana.com) + requirements: + - whitelisting in configuration + options: + grafana_url: + description: Grafana annotations api URL + required: True + env: + - name: GRAFANA_URL + ini: + - section: callback_grafana_annotations + key: grafana_url + type: string + validate_certs: + description: validate the SSL certificate of the Grafana server. (For HTTPS url) + env: + - name: GRAFANA_VALIDATE_CERT + ini: + - section: callback_grafana_annotations + key: validate_grafana_certs + - section: callback_grafana_annotations + key: validate_certs + default: True + type: bool + aliases: [ validate_grafana_certs ] + http_agent: + description: The HTTP 'User-agent' value to set in HTTP requets. + env: + - name: HTTP_AGENT + ini: + - section: callback_grafana_annotations + key: http_agent + default: 'Ansible (grafana_annotations callback)' + type: string + grafana_api_key: + description: Grafana API key, allowing to authenticate when posting on the HTTP API. + If not provided, grafana_login and grafana_password will + be required. + env: + - name: GRAFANA_API_KEY + ini: + - section: callback_grafana_annotations + key: grafana_api_key + type: string + grafana_user: + description: Grafana user used for authentication. Ignored if grafana_api_key is provided. + env: + - name: GRAFANA_USER + ini: + - section: callback_grafana_annotations + key: grafana_user + default: ansible + type: string + grafana_password: + description: Grafana password used for authentication. Ignored if grafana_api_key is provided. + env: + - name: GRAFANA_PASSWORD + ini: + - section: callback_grafana_annotations + key: grafana_password + default: ansible + type: string + grafana_dashboard_id: + description: The grafana dashboard id where the annotation shall be created. + env: + - name: GRAFANA_DASHBOARD_ID + ini: + - section: callback_grafana_annotations + key: grafana_dashboard_id + type: integer + grafana_panel_ids: + description: The grafana panel ids where the annotation shall be created. + Give a single integer or a comma-separated list of integers. + env: + - name: GRAFANA_PANEL_IDS + ini: + - section: callback_grafana_annotations + key: grafana_panel_ids + default: [] + type: list +''' + +import json +import socket +import getpass +from datetime import datetime + +from ansible.module_utils._text import to_text +from ansible.module_utils.urls import open_url +from ansible.plugins.callback import CallbackBase + + +PLAYBOOK_START_TXT = """\ +Started playbook {playbook} + +From '{hostname}' +By user '{username}' +""" + +PLAYBOOK_ERROR_TXT = """\ +Playbook {playbook} Failure ! + +From '{hostname}' +By user '{username}' + +'{task}' failed on {host} + +debug: {result} +""" + +PLAYBOOK_STATS_TXT = """\ +Playbook {playbook} +Duration: {duration} +Status: {status} + +From '{hostname}' +By user '{username}' + +Result: +{summary} +""" + + +def to_millis(dt): + return int(dt.strftime('%s')) * 1000 + + +class CallbackModule(CallbackBase): + """ + ansible grafana callback plugin + ansible.cfg: + callback_plugins = <path_to_callback_plugins_folder> + callback_whitelist = grafana_annotations + and put the plugin in <path_to_callback_plugins_folder> + """ + + CALLBACK_VERSION = 2.0 + 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.force_basic_auth = False + self.hostname = socket.gethostname() + self.username = getpass.getuser() + self.start_time = datetime.now() + self.errors = 0 + + 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) + + 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 + 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) + + 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) + data = { + 'time': to_millis(self.start_time), + 'text': text, + 'tags': ['ansible', 'ansible_event_start', self.playbook, self.hostname] + } + self._send_annotation(data) + + def v2_playbook_on_stats(self, stats): + end_time = datetime.now() + duration = end_time - self.start_time + summarize_stat = {} + for host in stats.processed.keys(): + summarize_stat[host] = stats.summarize(host) + + status = "FAILED" + 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)) + + data = { + '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)) + if ignore_errors: + return + data = { + 'time': to_millis(datetime.now()), + 'text': text, + 'tags': ['ansible', 'ansible_event_failure', self.playbook, self.hostname] + } + self.errors += 1 + self._send_annotations(data) + + def _send_annotations(self, data): + if self.dashboard_id: + data["dashboardId"] = int(self.dashboard_id) + if self.panel_ids: + for panel_id in self.panel_ids: + data["panelId"] = int(panel_id) + self._send_annotation(data) + else: + self._send_annotation(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) + except Exception as e: + self._display.error(u'Could not submit message to Grafana: %s' % to_text(e)) diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/__init__.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/__init__.py diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/api_key.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/api_key.py new file mode 100644 index 00000000..ffea714e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/api_key.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# 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) + +__metaclass__ = type + + +class ModuleDocFragment(object): + + 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/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/basic_auth.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/basic_auth.py new file mode 100644 index 00000000..8c41acdb --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/doc_fragments/basic_auth.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# 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) + +__metaclass__ = type + + +class ModuleDocFragment(object): + + DOCUMENTATION = r'''options: + url: + description: + - The Grafana URL. + required: true + type: str + aliases: [ grafana_url ] + url_username: + description: + - The Grafana user for API authentication. + default: admin + type: str + aliases: [ grafana_user ] + url_password: + description: + - The Grafana password for API authentication. + default: admin + type: str + 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. + type: bool + default: yes + client_cert: + description: + - PEM formatted certificate chain file to be used for SSL client authentication. + - This file can also include the key as well, and if the key is included, I(client_key) is not required + type: path + client_key: + description: + - PEM formatted file that contains your private key to be used for SSL client authentication. + - If I(client_cert) contains both the certificate and key, this option is not required. + 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. + type: bool + default: yes + ''' diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/lookup/__init__.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/lookup/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/lookup/__init__.py diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/lookup/grafana_dashboard.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/lookup/grafana_dashboard.py new file mode 100644 index 00000000..e0432861 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/lookup/grafana_dashboard.py @@ -0,0 +1,168 @@ +# (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) +__metaclass__ = type + +DOCUMENTATION = ''' +name: grafana_dashboard +author: Thierry Salle (@seuf) +short_description: list or search grafana dashboards +description: + - This lookup returns a list of grafana dashboards with possibility to filter them by query. +options: + grafana_url: + description: url of grafana. + env: + - name: GRAFANA_URL + default: http://127.0.0.1:3000 + grafana_api_key: + description: + - api key of grafana. + - when C(grafana_api_key) is set, the options C(grafan_user), C(grafana_password) and C(grafana_org_id) are ignored. + - Attention, please remove the two == at the end of the grafana_api_key + - because ansible lookup plugins options are split on = (see example). + env: + - name: GRAFANA_API_KEY + grafana_user: + description: grafana authentication user. + env: + - name: GRAFANA_USER + default: admin + grafana_password: + description: grafana authentication password. + env: + - name: GRAFANA_PASSWORD + default: admin + grafana_org_id: + description: grafana organisation id. + env: + - name: GRAFANA_ORG_ID + default: 1 + search: + description: optional filter for dashboard search. + env: + - name: GRAFANA_DASHBOARD_SEARCH +''' + +EXAMPLES = """ +- name: get project foo grafana dashboards + set_fact: + grafana_dashboards: "{{ lookup('grafana_dashboard', 'grafana_url=http://grafana.company.com grafana_user=admin grafana_password=admin search=foo') }}" + +- name: get all grafana dashboards + set_fact: + grafana_dashboards: "{{ lookup('grafana_dashboard', 'grafana_url=http://grafana.company.com grafana_api_key=' ~ grafana_api_key|replace('==', '')) }}" +""" + +import json +import os +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase +from ansible.module_utils.urls import basic_auth_header, open_url +from ansible.module_utils._text import to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError +from ansible.utils.display import Display + +display = Display() + + +ANSIBLE_GRAFANA_URL = 'http://127.0.0.1:3000' +ANSIBLE_GRAFANA_API_KEY = None +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_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_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_DASHBOARD_SEARCH') is not None: + ANSIBLE_GRAFANA_DASHBOARD_SEARCH = os.environ['GRAFANA_DASHBOARD_SEARCH'] + + +class GrafanaAPIException(Exception): + pass + + +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) + + 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') + except HTTPError as 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()))) + + def grafana_headers(self): + headers = {'content-type': 'application/json; charset=utf8'} + if self.grafana_api_key: + headers['Authorization'] = "Bearer %s==" % self.grafana_api_key + else: + headers['Authorization'] = basic_auth_header(self.grafana_user, self.grafana_password) + self.grafana_switch_organisation(headers) + + return headers + + def grafana_list_dashboards(self): + # define http headers + headers = self.grafana_headers() + + dashboard_list = [] + try: + if self.search: + 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') + except HTTPError as 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)) + else: + 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_dict = {} + ret = [] + + for param in grafana_args: + try: + key, value = param.split('=') + except ValueError: + raise AnsibleError("grafana_dashboard lookup plugin needs key=value pairs, but received %s" % terms) + grafana_dict[key] = value + + grafana = GrafanaAPI(**grafana_dict) + + ret = grafana.grafana_list_dashboards() + + return ret diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/module_utils/base.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/module_utils/base.py new file mode 100644 index 00000000..75ec3c08 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/module_utils/base.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. +# +# Copyright: (c) 2019, Rémi REY (@rrey) + +from __future__ import (absolute_import, division, print_function) +from ansible.module_utils.urls import url_argument_spec + +__metaclass__ = type + + +def grafana_argument_spec(): + argument_spec = url_argument_spec() + + del argument_spec['force'] + del argument_spec['force_basic_auth'] + del argument_spec['http_agent'] + + 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), + ) + return argument_spec + + +def grafana_required_together(): + return [['url_username', 'url_password']] + + +def grafana_mutually_exclusive(): + return [['url_username', 'grafana_api_key']] diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/__init__.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/__init__.py diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_dashboard.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_dashboard.py new file mode 100644 index 00000000..0bb53d39 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_dashboard.py @@ -0,0 +1,563 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2017, Thierry Sallé (@seuf) +# 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 + +DOCUMENTATION = ''' +--- +module: grafana_dashboard +author: + - Thierry Sallé (@seuf) +version_added: "1.0.0" +short_description: Manage Grafana dashboards +description: + - Create, update, delete, export Grafana dashboards via API. +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.. + default: 1 + type: int + folder: + description: + - The Grafana folder where this dashboard will be imported to. + default: General + version_added: "1.0.0" + type: str + state: + description: + - State of the dashboard. + choices: [ absent, export, present ] + default: present + type: str + slug: + description: + - Deprecated since Grafana 5. Use grafana dashboard uid instead. + - slug of the dashboard. It's the friendly url name of the dashboard. + - When C(state) is C(present), this parameter can override the slug in the meta section of the json file. + - If you want to import a json dashboard exported directly from the interface (not from the api), + you have to specify the slug parameter because there is no meta section in the exported json. + type: str + uid: + version_added: "1.0.0" + description: + - uid of the dashboard to export when C(state) is C(export) or C(absent). + type: str + path: + description: + - The path to the json file containing the Grafana dashboard to import or export. + - A http URL is also accepted (since 2.10). + - Required if C(state) is C(export) or C(present). + aliases: [ dashboard_url ] + type: str + overwrite: + description: + - Override existing dashboard when state is present. + type: bool + default: 'no' + dashboard_id: + description: + - Public Grafana.com dashboard id to import + version_added: "1.0.0" + type: str + dashboard_revision: + description: + - Revision of the public grafana dashboard to import + default: 1 + version_added: "1.0.0" + type: str + commit_message: + description: + - Set a commit message for the version history. + - Only used when C(state) is C(present). + - C(message) alias is deprecated in Ansible 2.10, since it is used internally by Ansible Core Engine. + aliases: [ 'message' ] + type: str +extends_documentation_fragment: +- community.grafana.basic_auth +- community.grafana.api_key +''' + +EXAMPLES = ''' +- hosts: localhost + connection: local + tasks: + - name: Import Grafana dashboard foo + community.grafana.grafana_dashboard: + grafana_url: http://grafana.company.com + grafana_api_key: "{{ grafana_api_key }}" + state: present + commit_message: Updated by ansible + overwrite: yes + path: /path/to/dashboards/foo.json + + - name: Import Grafana dashboard Zabbix + community.grafana.grafana_dashboard: + grafana_url: http://grafana.company.com + grafana_api_key: "{{ grafana_api_key }}" + folder: zabbix + dashboard_id: 6098 + dashbord_revision: 1 + + - name: Import Grafana dashboard zabbix + community.grafana.grafana_dashboard: + grafana_url: http://grafana.company.com + grafana_api_key: "{{ grafana_api_key }}" + folder: public + dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download + + - name: Export dashboard + community.grafana.grafana_dashboard: + grafana_url: http://grafana.company.com + grafana_user: "admin" + grafana_password: "{{ grafana_password }}" + org_id: 1 + state: export + uid: "000000653" + path: "/path/to/dashboards/000000653.json" +''' + +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 +from ansible.module_utils.urls import fetch_url +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 + +__metaclass__ = type + + +class GrafanaAPIException(Exception): + pass + + +class GrafanaMalformedJson(Exception): + pass + + +class GrafanaExportException(Exception): + pass + + +class GrafanaDeleteException(Exception): + pass + + +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: + 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'] + else: + module.params['force_basic_auth'] = True + grafana_switch_organisation(module, data['grafana_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: + try: + settings = json.loads(to_text(r.read())) + grafana_version = settings['buildInfo']['version'].split('.')[0] + except UnicodeError as e: + 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) + + 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': + return True, 0 + + try: + 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'])) + + folders = json.loads(r.read()) + + for folder in folders: + if folder['title'] == folder_name: + return True, folder['id'] + except Exception as e: + raise GrafanaAPIException(e) + + return False, 0 + + +def grafana_dashboard_exists(module, grafana_url, uid, headers): + dashboard_exists = False + dashboard = {} + + grafana_version = get_grafana_version(module, grafana_url, headers) + if grafana_version >= 5: + uri = '%s/api/dashboards/uid/%s' % (grafana_url, uid) + else: + uri = '%s/api/dashboards/db/%s' % (grafana_url, uid) + + r, info = fetch_url(module, uri, headers=headers, method='GET') + + if info['status'] == 200: + dashboard_exists = True + try: + dashboard = json.loads(r.read()) + except Exception as e: + raise GrafanaAPIException(e) + elif info['status'] == 404: + dashboard_exists = False + else: + raise GrafanaAPIException('Unable to get dashboard %s : %s' % (uid, info)) + + return dashboard_exists, dashboard + + +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: + try: + dashboards = json.loads(r.read()) + for d in dashboards: + 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)) + + return False, None + + +# 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']) + + # remove meta key if exists for compare + 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 + + # 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 payload == dashboard: + return False + return True + + +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)) + payload = json.loads(r.read()) + else: + try: + with open(data['path'], 'r') 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} + + # define http header + headers = grafana_headers(module, data) + + grafana_version = get_grafana_version(module, data['grafana_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'] + else: + 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'] + else: + uid = None + + result = {} + + # test if the folder exists + if grafana_version >= 5: + folder_exists, folder_id = grafana_folder_exists(module, data['grafana_url'], data['folder'], headers) + if folder_exists is False: + result['msg'] = "Dashboard folder '%s' does not exist." % data['folder'] + result['uid'] = uid + result['changed'] = False + return result + + payload['folderId'] = folder_id + + # test if dashboard already exists + if uid: + dashboard_exists, dashboard = grafana_dashboard_exists( + module, data['grafana_url'], uid, headers=headers) + else: + dashboard_exists, dashboard = grafana_dashboard_search( + module, data['grafana_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['grafana_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'] + except Exception as e: + raise GrafanaAPIException(e) + 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['commit_message'], info['status'])) + else: + # unchanged + result['uid'] = uid + result['msg'] = "Dashboard %s unchanged." % payload['dashboard']['title'] + result['changed'] = False + else: + # create + if folder_exists is True: + payload['folderId'] = folder_id + + # 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['grafana_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'] + except Exception as e: + raise GrafanaAPIException(e) + result['uid'] = uid + else: + raise GrafanaAPIException('Unable to create the new dashboard %s : %s - %s. (headers : %s)' % + (payload['dashboard']['title'], info['status'], info, headers)) + + return result + + +def grafana_delete_dashboard(module, data): + + # define http headers + headers = grafana_headers(module, data) + + grafana_version = get_grafana_version(module, data['grafana_url'], headers) + if grafana_version < 5: + if data.get('slug'): + uid = data['slug'] + else: + raise GrafanaMalformedJson('No slug parameter. Needed with grafana < 5') + else: + if data.get('uid'): + uid = data['uid'] + else: + raise GrafanaDeleteException('No uid specified %s') + + # test if dashboard already exists + dashboard_exists, dashboard = grafana_dashboard_exists(module, data['grafana_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['grafana_url'], uid), headers=headers, method='DELETE') + else: + r, info = fetch_url(module, '%s/api/dashboards/uid/%s' % (data['grafana_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)) + else: + # dashboard does not exist, do nothing + result = {'msg': "Dashboard %s does not exist." % uid, + 'changed': False, + 'uid': uid} + + return result + + +def grafana_export_dashboard(module, data): + + # define http headers + headers = grafana_headers(module, data) + + grafana_version = get_grafana_version(module, data['grafana_url'], headers) + if grafana_version < 5: + if data.get('slug'): + uid = data['slug'] + else: + raise GrafanaMalformedJson('No slug parameter. Needed with grafana < 5') + else: + if data.get('uid'): + uid = data['uid'] + else: + raise GrafanaExportException('No uid specified') + + # test if dashboard already exists + dashboard_exists, dashboard = grafana_dashboard_exists(module, data['grafana_url'], uid, headers=headers) + + if dashboard_exists is True: + try: + with open(data['path'], 'w') as f: + f.write(json.dumps(dashboard)) + 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} + else: + result = {'msg': "Dashboard %s does not exist." % uid, + 'uid': uid, + 'changed': False} + + return result + + +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'), + 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']], + ], + required_together=[['url_username', 'url_password', 'org_id']], + mutually_exclusive=[['url_username', 'grafana_api_key'], ['uid', 'slug'], ['path', 'dashboard_id']], + ) + + 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': + result = grafana_create_dashboard(module, module.params) + 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) + ) + return + except GrafanaMalformedJson as 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) + ) + return + except GrafanaExportException as e: + module.fail_json( + failed=True, + msg="error : Can't export dashboard : %s" % to_native(e) + ) + return + + module.exit_json( + failed=False, + **result + ) + return + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_datasource.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_datasource.py new file mode 100644 index 00000000..65276d47 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_datasource.py @@ -0,0 +1,752 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2017, Thierry Sallé (@seuf) +# 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 = ''' +module: grafana_datasource +author: +- Thierry Sallé (@seuf) +- Martin Wang (@martinwangjian) +- Rémi REY (@rrey) +short_description: Manage Grafana datasources +description: +- Create/update/delete Grafana datasources via API. +options: + name: + description: + - The name of the datasource. + required: true + type: str + ds_type: + description: + - The type of the datasource. + required: true + choices: + - graphite + - prometheus + - elasticsearch + - influxdb + - opentsdb + - mysql + - postgres + - cloudwatch + - alexanderzobnin-zabbix-datasource + - sni-thruk-datasource + - camptocamp-prometheus-alertmanager-datasource + - loki + type: str + ds_url: + description: + - The URL of the datasource. + required: true + type: str + access: + description: + - The access mode for this datasource. + choices: + - direct + - proxy + default: proxy + type: str + database: + description: + - Name of the database for the datasource. + - This options is required when the C(ds_type) is C(influxdb), C(elasticsearch) + (index name), C(mysql) or C(postgres). + required: false + type: str + user: + description: + - The datasource login user for influxdb datasources. + type: str + password: + description: + - The datasource password. + - For encrypted password use C(additional_secure_json_data.password). + type: str + basic_auth_user: + description: + - The datasource basic auth user. + - Setting this option with basic_auth_password will enable basic auth. + type: str + basic_auth_password: + description: + - The datasource basic auth password, when C(basic auth) is C(yes). + type: str + with_credentials: + description: + - Whether credentials such as cookies or auth headers should be sent with cross-site + requests. + type: bool + default: 'no' + tls_client_cert: + description: + - The client TLS certificate. + - If C(tls_client_cert) and C(tls_client_key) are set, this will enable TLS authentication. + - Starts with ----- BEGIN CERTIFICATE ----- + - Stored as secure data, see C(enforce_secure_data) and notes! + type: str + tls_client_key: + description: + - The client TLS private key + - Starts with ----- BEGIN RSA PRIVATE KEY ----- + - Stored as secure data, see C(enforce_secure_data) and notes! + type: str + tls_ca_cert: + description: + - The TLS CA certificate for self signed certificates. + - Only used when C(tls_client_cert) and C(tls_client_key) are set. + - Stored as secure data, see C(enforce_secure_data) and notes! + type: str + tls_skip_verify: + description: + - Skip the TLS datasource certificate verification. + type: bool + default: false + is_default: + description: + - Make this datasource the default one. + type: bool + default: 'no' + org_id: + description: + - Grafana Organisation 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. + default: 1 + type: int + state: + description: + - Status of the datasource + choices: + - absent + - present + default: present + type: str + es_version: + description: + - Elasticsearch version (for C(ds_type = elasticsearch) only) + - Version 56 is for elasticsearch 5.6+ where you can specify the C(max_concurrent_shard_requests) + option. + choices: + - 2 + - 5 + - 56 + - 60 + - 70 + default: 5 + type: int + max_concurrent_shard_requests: + description: + - Starting with elasticsearch 5.6, you can specify the max concurrent shard per + requests. + default: 256 + type: int + time_field: + description: + - Name of the time field in elasticsearch ds. + - For example C(@timestamp). + type: str + default: '@timestamp' + time_interval: + description: + - Minimum group by interval for C(influxdb) or C(elasticsearch) datasources. + - for example C(>10s). + type: str + interval: + description: + - For elasticsearch C(ds_type), this is the index pattern used. + choices: + - '' + - Hourly + - Daily + - Weekly + - Monthly + - Yearly + type: str + tsdb_version: + description: + - The opentsdb version. + - Use C(1) for <=2.1, C(2) for ==2.2, C(3) for ==2.3. + choices: + - 1 + - 2 + - 3 + default: 1 + type: int + tsdb_resolution: + description: + - The opentsdb time resolution. + choices: + - millisecond + - second + default: second + type: str + sslmode: + description: + - SSL mode for C(postgres) datasource type. + choices: + - disable + - require + - verify-ca + - verify-full + type: str + default: disable + trends: + required: false + description: + - Use trends or not for zabbix datasource type. + type: bool + aws_auth_type: + description: + - Type for AWS authentication for CloudWatch datasource type (authType of grafana + api) + default: keys + choices: + - keys + - credentials + - arn + type: str + aws_default_region: + description: + - AWS default region for CloudWatch datasource type + default: us-east-1 + type: str + 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_credentials_profile: + description: + - Profile for AWS credentials for CloudWatch datasource type when C(aws_auth_type) + is C(credentials) + default: '' + required: false + type: str + aws_access_key: + description: + - AWS access key for CloudWatch datasource type when C(aws_auth_type) is C(keys) + default: '' + required: false + type: str + aws_secret_key: + description: + - AWS secret key for CloudWatch datasource type when C(aws_auth_type) is C(keys) + default: '' + required: false + type: str + aws_assume_role_arn: + description: + - AWS IAM role arn to assume for CloudWatch datasource type when C(aws_auth_type) + is C(arn) + default: '' + required: false + type: str + aws_custom_metrics_namespaces: + description: + - Namespaces of Custom Metrics for CloudWatch datasource type + default: '' + required: false + type: str + zabbix_user: + description: + - User for Zabbix API + required: false + type: str + zabbix_password: + description: + - Password for Zabbix API + required: false + type: str + additional_json_data: + description: + - Defined data is used for datasource jsonData + - Data may be overridden by specifically defined parameters (like zabbix_user) + required: false + type: dict + default: {} + additional_secure_json_data: + description: + - Defined data is used for datasource secureJsonData + - Data may be overridden by specifically defined parameters (like tls_client_cert) + - Stored as secure data, see C(enforce_secure_data) and notes! + required: false + type: dict + default: {} + enforce_secure_data: + description: + - Secure data is not updated per default (see notes!) + - To update secure data you have to enable this option! + - Enabling this, the task will always report changed=True + required: false + type: bool + default: false +extends_documentation_fragment: +- community.grafana.basic_auth +- community.grafana.api_key +notes: +- Secure data will get encrypted by the Grafana API, thus it can not be compared on subsequent runs. To workaround this, secure + 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 = ''' +--- +- name: Create elasticsearch datasource + community.grafana.grafana_datasource: + name: "datasource-elastic" + grafana_url: "https://grafana.company.com" + grafana_user: "admin" + grafana_password: "xxxxxx" + org_id: "1" + ds_type: "elasticsearch" + ds_url: "https://elastic.company.com:9200" + database: "[logstash_]YYYY.MM.DD" + basic_auth_user: "grafana" + 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" + +- name: Create influxdb datasource + community.grafana.grafana_datasource: + name: "datasource-influxdb" + grafana_url: "https://grafana.company.com" + grafana_user: "admin" + grafana_password: "xxxxxx" + org_id: "1" + ds_type: "influxdb" + ds_url: "https://influx.company.com:8086" + database: "telegraf" + time_interval: ">10s" + tls_ca_cert: "/etc/ssl/certs/ca.pem" + +- name: Create postgres datasource + community.grafana.grafana_datasource: + name: "datasource-postgres" + grafana_url: "https://grafana.company.com" + grafana_user: "admin" + grafana_password: "xxxxxx" + org_id: "1" + ds_type: "postgres" + ds_url: "postgres.company.com:5432" + database: "db" + user: "postgres" + sslmode: "verify-full" + additional_json_data: + timescaledb: false + additional_secure_json_data: + password: "iampgroot" + +- name: Create cloudwatch datasource + community.grafana.grafana_datasource: + name: "datasource-cloudwatch" + grafana_url: "https://grafana.company.com" + grafana_user: "admin" + grafana_password: "xxxxxx" + org_id: "1" + ds_type: "cloudwatch" + ds_url: "http://monitoring.us-west-1.amazonaws.com" + aws_auth_type: "keys" + aws_default_region: "us-west-1" + aws_access_key: "speakFriendAndEnter" + aws_secret_key: "mel10n" + aws_custom_metrics_namespaces: "n1,n2" + +- name: grafana - add thruk datasource + community.grafana.grafana_datasource: + name: "datasource-thruk" + grafana_url: "https://grafana.company.com" + grafana_user: "admin" + grafana_password: "xxxxxx" + org_id: "1" + ds_type: "sni-thruk-datasource" + ds_url: "https://thruk.company.com/sitename/thruk" + basic_auth_user: "thruk-user" + basic_auth_password: "******" + +# handle secure data - workflow example +# this will create/update the datasource but dont update the secure data on updates +# so you can assert if all tasks are changed=False +- name: create prometheus datasource + community.grafana.grafana_datasource: + name: openshift_prometheus + ds_type: prometheus + ds_url: https://openshift-monitoring.company.com + access: proxy + tls_skip_verify: true + additional_json_data: + httpHeaderName1: "Authorization" + additional_secure_json_data: + httpHeaderValue1: "Bearer ihavenogroot" + +# in a separate task or even play you then can force to update +# and assert if each datasource is reporting changed=True +- name: update prometheus datasource + community.grafana.grafana_datasource: + name: openshift_prometheus + ds_type: prometheus + ds_url: https://openshift-monitoring.company.com + access: proxy + tls_skip_verify: true + additional_json_data: + httpHeaderName1: "Authorization" + additional_secure_json_data: + httpHeaderValue1: "Bearer ihavenogroot" + enforce_secure_data: true +''' + +RETURN = ''' +--- +datasource: + description: datasource created/updated by module + returned: changed + type: dict + sample: { "access": "proxy", + "basicAuth": false, + "database": "test_*", + "id": 1035, + "isDefault": false, + "jsonData": { + "esVersion": 5, + "timeField": "@timestamp", + "timeInterval": "10s", + }, + "secureJsonFields": { + "JustASecureTest": true, + }, + "name": "grafana_datasource_test", + "orgId": 1, + "type": "elasticsearch", + "url": "http://elastic.company.com:9200", + "user": "", + "password": "", + "withCredentials": false } +''' + +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.six.moves.urllib.parse import quote +from ansible.module_utils.urls import fetch_url, url_argument_spec, basic_auth_header +from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, grafana_required_together, grafana_mutually_exclusive + + +def compare_datasources(new, current, compareSecureData=True): + 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: + del current['basicAuthUser'] + 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) + 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'): + # secureJsonData is not provided so just remove both for comparision + 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') + + return dict(before=current, after=new) + + +def get_datasource_payload(data): + payload = { + 'orgId': data['org_id'], + 'name': data['name'], + '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'], + 'password': data['password'], + 'jsonData': data['additional_json_data'], + 'secureJsonData': data['additional_secure_json_data'] + } + + # define basic auth + if 'basic_auth_user' in data and data['basic_auth_user'] and 'basic_auth_password' in data and data['basic_auth_password']: + payload['basicAuth'] = True + payload['basicAuthUser'] = data['basic_auth_user'] + payload['basicAuthPassword'] = data['basic_auth_password'] + else: + payload['basicAuth'] = False + + # define tls auth + json_data = payload['jsonData'] + secure_json_data = payload['secureJsonData'] + 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'] + else: + json_data['tlsAuth'] = False + json_data['tlsAuthWithCACert'] = False + if data.get('tls_ca_cert'): + secure_json_data['tlsCACert'] = data['tls_ca_cert'] + + if data.get('tls_skip_verify'): + json_data['tlsSkipVerify'] = True + + # datasource type related parameters + if data['ds_type'] == 'elasticsearch': + json_data['esVersion'] = data['es_version'] + json_data['timeField'] = data['time_field'] + if data.get('interval'): + json_data['interval'] = data['interval'] + if data['es_version'] >= 56: + json_data['maxConcurrentShardRequests'] = data['max_concurrent_shard_requests'] + + if data['ds_type'] == 'elasticsearch' or data['ds_type'] == 'influxdb': + if data.get('time_interval'): + json_data['timeInterval'] = data['time_interval'] + + if data['ds_type'] == 'opentsdb': + json_data['tsdbVersion'] = data['tsdb_version'] + if data['tsdb_resolution'] == 'second': + json_data['tsdbResolution'] = 1 + else: + json_data['tsdbResolution'] = 2 + + if data['ds_type'] == 'postgres': + json_data['sslmode'] = data['sslmode'] + + if data['ds_type'] == 'alexanderzobnin-zabbix-datasource': + if data.get('trends'): + json_data['trends'] = True + json_data['username'] = data['zabbix_user'] + json_data['password'] = data['zabbix_password'] + + 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 = module.params.get("url") + # {{{ Authentication header + self.headers = {"Content-Type": "application/json"} + if module.params.get('grafana_api_key', None): + self.headers["Authorization"] = "Bearer %s" % module.params['grafana_api_key'] + else: + self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) + self.switch_organisation(module.params['org_id']) + # }}} + + def _send_request(self, url, data=None, headers=None, method="GET"): + if data is not None: + data = json.dumps(data, sort_keys=True) + if not headers: + 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) + 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)) + 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)) + + def switch_organisation(self, org_id): + url = "/api/user/using/%d" % org_id + 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) + return self._send_request(url, headers=self.headers, method='GET') + + def delete_datasource(self, name): + url = "/api/datasources/name/%s" % quote(name) + 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') + + def create_datasource(self, data): + url = "/api/datasources" + self._send_request(url, data=data, headers=self.headers, method='POST') + + +def main(): + # use the predefined argument spec for url + argument_spec = grafana_argument_spec() + + argument_spec.update( + name=dict(required=True, type='str'), + ds_type=dict(choices=['graphite', + 'prometheus', + 'elasticsearch', + 'influxdb', + 'opentsdb', + 'mysql', + 'postgres', + 'cloudwatch', + 'alexanderzobnin-zabbix-datasource', + 'camptocamp-prometheus-alertmanager-datasource', + 'sni-thruk-datasource', + 'loki'], required=True), + ds_url=dict(required=True, 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='int', default=5, choices=[2, 5, 56, 60, 70]), + 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']), + 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'), + 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_if=[ + ['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 = 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': + 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) + 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) + 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) + else: + if ds is None: + 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) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_folder.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_folder.py new file mode 100644 index 00000000..5f305250 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_folder.py @@ -0,0 +1,274 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. +# +# Copyright: (c) 2019, Rémi REY (@rrey) + +from __future__ import absolute_import, division, print_function + +DOCUMENTATION = ''' +--- +module: grafana_folder +author: + - Rémi REY (@rrey) +version_added: "1.0.0" +short_description: Manage Grafana Folders +description: + - Create/update/delete Grafana Folders through the Folders API. + - The Folders API is only available starting Grafana 5 and the module will fail if the server version is lower than version 5. +options: + name: + description: + - The title of the Grafana Folder. + required: true + type: str + aliases: [ title ] + state: + description: + - Delete the members not found in the C(members) parameters from the + - list of members found on the Folder. + default: present + type: str + choices: ["present", "absent"] +extends_documentation_fragment: +- community.grafana.basic_auth +- community.grafana.api_key +''' + +EXAMPLES = ''' +--- +- name: Create a folder + community.grafana.grafana_folder: + url: "https://grafana.example.com" + grafana_api_key: "{{ some_api_token_value }}" + title: "grafana_working_group" + state: present + +- name: Delete a folder + community.grafana.grafana_folder: + url: "https://grafana.example.com" + grafana_api_key: "{{ some_api_token_value }}" + title: "grafana_working_group" + state: absent +''' + +RETURN = ''' +--- +folder: + description: Information about the Folder + returned: On success + type: complex + contains: + id: + description: The Folder identifier + returned: always + type: int + sample: + - 42 + uid: + description: The Folder uid + returned: always + type: str + sample: + - "nErXDvCkzz" + title: + description: The Folder title + returned: always + type: str + sample: + - "Department ABC" + url: + description: The Folder url + returned: always + type: str + sample: + - "/dashboards/f/nErXDvCkzz/department-abc" + hasAcl: + description: Boolean specifying if folder has acl + returned: always + type: bool + sample: + - false + canSave: + description: Boolean specifying if current user can save in folder + returned: always + type: bool + sample: + - false + canEdit: + description: Boolean specifying if current user can edit in folder + returned: always + type: bool + sample: + - false + canAdmin: + description: Boolean specifying if current user can admin in folder + returned: always + type: bool + sample: + - false + createdBy: + description: The name of the user who created the folder + returned: always + type: str + sample: + - "admin" + created: + description: The folder creation date + returned: always + type: str + sample: + - "2018-01-31T17:43:12+01:00" + updatedBy: + description: The name of the user who last updated the folder + returned: always + type: str + sample: + - "admin" + updated: + description: The date the folder was last updated + returned: always + type: str + sample: + - "2018-01-31T17:43:12+01:00" + version: + description: The folder version + returned: always + type: int + sample: + - 1 +''' + +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.urls import fetch_url, basic_auth_header +from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, grafana_required_together, grafana_mutually_exclusive +from ansible.module_utils.six.moves.urllib.parse import quote +from ansible.module_utils._text import to_text + +__metaclass__ = type + + +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'] + else: + self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) + # }}} + self.grafana_url = module.params.get("url") + grafana_version = self.get_version() + if grafana_version["major"] < 5: + self._module.fail_json(failed=True, msg="Folders API is available starting Grafana v5") + + def _send_request(self, url, data=None, headers=None, method="GET"): + if data is not None: + data = json.dumps(data, sort_keys=True) + if not headers: + 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) + 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)) + elif status_code == 403: + self._module.fail_json(failed=True, msg="Permission Denied") + elif status_code == 412: + error_msg = resp.read()['message'] + self._module.fail_json(failed=True, msg=error_msg) + elif status_code == 200: + return self._module.from_json(resp.read()) + 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") + version = response.get("version") + major, minor, rev = version.split(".") + return {"major": int(major), "minor": int(minor), "rev": int(rev)} + + def create_folder(self, title): + url = "/api/folders" + folder = dict(title=title) + response = self._send_request(url, data=folder, headers=self.headers, method="POST") + return response + + def get_folder(self, title): + url = "/api/search?type=dash-folder&query={title}".format(title=quote(title)) + response = self._send_request(url, headers=self.headers, method="GET") + for item in response: + if item.get("title") == to_text(title): + return item + return None + + def delete_folder(self, folder_uid): + url = "/api/folders/{folder_uid}".format(folder_uid=folder_uid) + response = self._send_request(url, headers=self.headers, method="DELETE") + return response + + +def setup_module_object(): + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=False, + required_together=grafana_required_together(), + mutually_exclusive=grafana_mutually_exclusive(), + ) + return module + + +argument_spec = grafana_argument_spec() +argument_spec.update( + name=dict(type='str', aliases=['title'], required=True), + state=dict(type='str', default='present', choices=['present', 'absent']), +) + + +def main(): + + module = setup_module_object() + state = module.params['state'] + title = module.params['name'] + + grafana_iface = GrafanaFolderInterface(module) + + changed = False + if state == 'present': + folder = grafana_iface.get_folder(title) + if folder is None: + grafana_iface.create_folder(title) + folder = grafana_iface.get_folder(title) + changed = True + folder = grafana_iface.get_folder(title) + module.exit_json(changed=changed, folder=folder) + elif state == 'absent': + folder = grafana_iface.get_folder(title) + if folder is None: + module.exit_json(changed=False, message="No folder found") + result = grafana_iface.delete_folder(folder.get("uid")) + module.exit_json(changed=True, message=result) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_notification_channel.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_notification_channel.py new file mode 100644 index 00000000..2985fb4c --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_notification_channel.py @@ -0,0 +1,816 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +DOCUMENTATION = ''' +--- +module: grafana_notification_channel +author: + - Aliaksandr Mianzhynski (@amenzhinsky) +version_added: "1.1.0" +short_description: Manage Grafana Notification Channels +description: + - Create/Update/Delete Grafana Notification Channels via API. +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.. + default: 1 + type: int + state: + type: str + default: present + choices: + - present + - absent + description: + - Status of the notification channel. + uid: + type: str + description: + - The channel unique identifier. + name: + type: str + description: + - The name of the notification channel. + - Required when I(state) is C(present). + type: + type: str + choices: + - dingding + - discord + - email + - googlechat + - hipchat + - kafka + - line + - teams + - opsgenie + - pagerduty + - prometheus + - pushover + - sensu + - slack + - telegram + - threema + - victorops + - webhook + description: + - The channel notification type. + - Required when I(state) is C(present). + is_default: + type: bool + default: 'no' + description: + - Use this channel for all alerts. + include_image: + type: bool + default: 'no' + description: + - Capture a visualization image and attach it to notifications. + disable_resolve_message: + type: bool + default: 'no' + description: + - Disable the resolve message. + reminder_frequency: + type: str + description: + - Additional notifications interval for triggered alerts. + - For example C(15m). + dingding_url: + type: str + description: + - DingDing webhook URL. + dingding_message_type: + type: list + elements: str + choices: + - link + - action_card + description: + - DingDing message type. + discord_url: + type: str + description: + - Discord webhook URL. + discord_message_content: + type: str + description: + - Overrides message content. + email_addresses: + type: list + elements: str + description: + - List of recipients. + email_single: + type: bool + description: + - Send single email to all recipients. + googlechat_url: + type: str + description: + - Google Hangouts webhook URL. + hipchat_url: + type: str + description: + - HipChat webhook URL. + hipchat_api_key: + type: str + description: + - HipChat API key. + hipchat_room_id: + type: str + description: + - HipChat room ID. + kafka_url: + type: str + description: + - Kafka REST proxy URL. + kafka_topic: + type: str + description: + - Kafka topic name. + line_token: + type: str + description: + - LINE token. + teams_url: + type: str + description: + - Microsoft Teams webhook URL. + opsgenie_url: + type: str + description: + - OpsGenie webhook URL. + opsgenie_api_key: + type: str + description: + - OpsGenie API key. + opsgenie_auto_close: + type: bool + description: + - Automatically close alerts in OpsGenie once the alert goes back to ok. + opsgenie_override_priority: + type: bool + description: + - Allow the alert priority to be set using the og_priority tag. + pagerduty_integration_key: + type: str + description: + - PagerDuty integration key. + pagerduty_severity: + type: list + elements: str + choices: + - critical + - error + - warning + - info + description: + - Alert severity in PagerDuty. + pagerduty_auto_resolve: + type: bool + description: + - Resolve incidents in PagerDuty once the alert goes back to ok. + pagerduty_message_in_details: + type: bool + description: + - Move the alert message from the PD summary into the custom details. + - This changes the custom details object and may break event rules you have configured. + prometheus_url: + type: str + description: + - Prometheus API URL. + prometheus_username: + type: str + description: + - Prometheus username. + prometheus_password: + type: str + description: + - Prometheus password. + pushover_api_token: + type: str + description: + - Pushover API token. + pushover_user_key: + type: str + description: + - Pushover user key. + pushover_devices: + type: list + elements: str + description: + - Devices list in Pushover. + pushover_priority: + type: list + elements: str + choices: + - emergency + - high + - normal + - low + - lowest + description: + - Alert priority in Pushover. + pushover_retry: + type: int + description: + - Retry in C(n) minutes. + - Only when priority is C(emergency). + pushover_expire: + type: int + description: + - Expire alert in C(n) minutes. + - Only when priority is C(emergency). + pushover_alert_sound: + type: str + description: + - Alert sound in Pushover. + - L(https://pushover.net/api#sounds) + pushover_ok_sound: + type: str + description: + - OK sound in Pushover. + - L(https://pushover.net/api#sounds) + sensu_url: + type: str + description: + - Sensu webhook URL. + sensu_source: + type: str + description: + - Source in Sensu. + sensu_handler: + type: str + description: + - Sensu handler name. + sensu_username: + type: str + description: + - Sensu user. + sensu_password: + type: str + description: + - Sensu password. + slack_url: + type: str + description: + - Slack webhook URL. + slack_recipient: + type: str + description: + - Override default Slack channel or user. + slack_username: + type: str + description: + - Set the username for the bot's message. + slack_icon_emoji: + type: str + description: + - An emoji to use for the bot's message. + slack_icon_url: + type: str + description: + - URL to an image to use as the icon for the bot's message + slack_mention_users: + type: list + elements: str + description: + - Mention users list. + slack_mention_groups: + type: list + elements: str + description: + - Mention groups list. + slack_mention_channel: + type: list + elements: str + choices: + - here + - channel + description: + - Mention whole channel or just active members. + slack_token: + type: str + description: + - Slack token. + telegram_bot_token: + type: str + description: + - Telegram bot token; + telegram_chat_id: + type: str + description: + - Telegram chat id. + threema_gateway_id: + type: str + description: + - 8 character Threema Gateway ID (starting with a *). + threema_recepient_id: + type: str + description: + - 8 character Threema ID that should receive the alerts. + threema_api_secret: + type: str + description: + - Threema Gateway API secret. + victorops_url: + type: str + description: + - VictorOps webhook URL. + victorops_auto_resolve: + type: bool + description: + - Resolve incidents in VictorOps once the alert goes back to ok. + webhook_url: + type: str + description: + - Webhook URL + webhook_username: + type: str + description: + - Webhook username. + webhook_password: + type: str + description: + - Webhook password. + webhook_http_method: + type: list + elements: str + choices: + - POST + - PUT + description: + - Webhook HTTP verb to use. + +extends_documentation_fragment: + - community.grafana.basic_auth + - community.grafana.api_key +''' + + +EXAMPLES = ''' +- name: Create slack notification channel + register: result + 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}}" + +- name: Delete slack notification channel + register: result + grafana_notification_channel: + state: absent + uid: slack + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" +''' + +RETURN = ''' +notification_channel: + description: Notification channel created or updated by the module. + returned: changed + type: dict + sample: | + { + "created": "2020-11-10T21:10:19.675308051+03:00", + "disableResolveMessage": false, + "frequency": "", + "id": 37, + "isDefault": false, + "name": "Oops", + "secureFields": {}, + "sendReminder": false, + "settings": { + "uploadImage": false, + "url": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER" + }, + "type": "slack", + "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 + + +class GrafanaAPIException(Exception): + pass + + +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: + 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'] + else: + module.params['force_basic_auth'] = True + grafana_switch_organisation(module, data['grafana_url'], data['org_id'], headers) + return headers + + +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'] + } + } + + if data.get('reminder_frequency'): + payload['sendReminder'] = True + payload['frequency'] = data['reminder_frequency'] + + if data['type'] == 'dingding': + payload['settings']['url'] = data['dingding_url'] + if data.get('dingding_message_type'): + payload['settings']['msgType'] = { + 'link': 'link', + 'action_card': 'actionCard', + }[data['dingding_message_type']] + + elif data['type'] == 'discord': + payload['settings']['url'] = data['discord_url'] + if data.get('discord_message_content'): + payload['settings']['content'] = data['discord_message_content'] + + elif data['type'] == 'email': + payload['settings']['addresses'] = ';'.join(data['email_addresses']) + if data.get('email_single'): + payload['settings']['singleEmail'] = data['email_single'] + + elif data['type'] == 'googlechat': + payload['settings']['url'] = data['googlechat_url'] + + elif data['type'] == 'hipchat': + 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'] + + 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': + 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'] + + elif data['type'] == 'prometheus': + 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'] + + elif data['type'] == 'pushover': + 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'] + + elif data['type'] == 'sensu': + 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'] + + elif data['type'] == 'slack': + 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'] + + elif data['type'] == 'telegram': + payload['settings']['bottoken'] = data['telegram_bot_token'] + payload['settings']['chatid'] = data['telegram_chat_id'] + + elif data['type'] == 'treema': + payload['settings']['gateway_id'] = data['settings_gateway_id'] + payload['settings']['recipient_id'] = data['settings_recipient_id'] + payload['settings']['api_secret'] = data['settings_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': + 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'] + + return payload + + +def grafana_create_notification_channel(module, data, headers, payload): + r, info = fetch_url(module, '%s/api/alert-notifications' % data['grafana_url'], + data=json.dumps(payload), headers=headers, method='POST') + if info['status'] == 200: + return { + 'state': 'present', + 'changed': True, + 'channel': json.loads(to_text(r.read())), + } + else: + raise GrafanaAPIException("Unable to create notification channel: %s" % info) + + +def grafana_update_notification_channel(module, data, headers, payload, before): + r, info = fetch_url(module, '%s/api/alert-notifications/uid/%s' % + (data['grafana_url'], data['uid']), + data=json.dumps(payload), headers=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'] + + if before == after: + return { + 'changed': False + } + else: + return { + 'changed': True, + 'diff': { + 'before': before, + 'after': after, + }, + 'channel': channel, + } + else: + raise GrafanaAPIException("Unable to update notification channel %s : %s" % + (data['uid'], info)) + + +def grafana_create_or_update_notification_channel(module, data): + headers = grafana_headers(module, data) + payload = grafana_notification_channel_payload(data) + r, info = fetch_url(module, '%s/api/alert-notifications/uid/%s' % + (data['grafana_url'], data['uid']), headers=headers) + if info['status'] == 200: + before = json.loads(to_text(r.read())) + return grafana_update_notification_channel(module, data, headers, payload, before) + elif info['status'] == 404: + return grafana_create_notification_channel(module, data, headers, payload) + else: + raise GrafanaAPIException("Unable to get notification channel %s : %s" % + (data['uid'], info)) + + +def grafana_delete_notification_channel(module, data): + headers = grafana_headers(module, data) + r, info = fetch_url(module, '%s/api/alert-notifications/uid/%s' % + (data['grafana_url'], data['uid']), + headers=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)) + + +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'), + telegram_chat_id=dict(type='str'), + + threema_gateway_id=dict(type='str'), + threema_recepient_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_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_recepient_id', + 'threema_api_secret']], + ['type', 'victorops', ['victorops_url']], + ['type', 'webhook', ['webhook_url']] + ] + ) + + if module.params['state'] == 'present': + result = grafana_create_or_update_notification_channel(module, module.params) + module.exit_json(failed=False, **result) + else: + result = grafana_delete_notification_channel(module, module.params) + module.exit_json(failed=False, **result) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_plugin.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_plugin.py new file mode 100644 index 00000000..222165c8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_plugin.py @@ -0,0 +1,264 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2017, Thierry Sallé (@seuf) +# 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 + +DOCUMENTATION = '''module: grafana_plugin +author: +- Thierry Sallé (@seuf) +short_description: Manage Grafana plugins via grafana-cli +description: +- Install and remove Grafana plugins. +- See U(https://grafana.com/docs/plugins/installation/) for upstream documentation. +options: + name: + description: + - Name of the plugin. + required: true + type: str + version: + description: + - Version of the plugin to install. + - Defaults to C(latest). + type: str + grafana_plugins_dir: + description: + - Directory where the Grafana plugin will be installed. + - If omitted, defaults to C(/var/lib/grafana/plugins). + type: str + grafana_repo: + description: + - URL to the Grafana plugin repository. + - 'If omitted, grafana-cli will use the default value: U(https://grafana.com/api/plugins).' + type: str + grafana_plugin_url: + description: + - Full URL to the plugin zip file instead of downloading the file from U(https://grafana.com/api/plugins). + - Requires grafana 4.6.x or later. + type: str + state: + description: + - Whether the plugin should be installed. + choices: + - present + - absent + default: present + type: str +''' + +EXAMPLES = ''' +--- +- name: Install/update Grafana piechart panel plugin + community.grafana.grafana_plugin: + name: grafana-piechart-panel + version: latest + state: present +''' + +RETURN = ''' +--- +version: + description: version of the installed/removed/updated plugin. + type: str + returned: always +''' + +import os +from ansible.module_utils.basic import AnsibleModule + +__metaclass__ = type + + +class GrafanaCliException(Exception): + pass + + +def parse_version(string): + 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' + grafana_cli = None + + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + grafana_cli = program + else: + for path in os.environ["PATH"].split(os.pathsep): + path = path.strip('"') + exe_file = os.path.join(path, program) + if is_exe(exe_file): + grafana_cli = exe_file + break + + if grafana_cli is None: + 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') + + +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)) + stdout_lines = stdout.split("\n") + for line in stdout_lines: + if line.find(' @ ') != -1: + line = line.rstrip() + plugin_name, plugin_version = parse_version(line) + 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'])) + stdout_lines = stdout.split("\n") + if stdout_lines[0]: + return stdout_lines[0].rstrip() + return None + + +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': + 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} + else: + 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']) + else: + 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} + else: + 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']) + else: + cmd = '{0} install {1}'.format(grafana_cli, params['name']) + else: + 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: + 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} + else: + 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)) + + +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'), + state=dict(choices=['present', 'absent'], + default='present') + ), + supports_check_mode=False + ) + + try: + result = grafana_plugin(module, module.params) + except GrafanaCliException as 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) + ) + return + + module.exit_json( + failed=False, + **result + ) + return + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_team.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_team.py new file mode 100644 index 00000000..be9b7210 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_team.py @@ -0,0 +1,335 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. +# +# Copyright: (c) 2019, Rémi REY (@rrey) + +from __future__ import absolute_import, division, print_function + +DOCUMENTATION = ''' +--- +module: grafana_team +author: + - Rémi REY (@rrey) +version_added: "1.0.0" +short_description: Manage Grafana Teams +description: + - Create/update/delete Grafana Teams through the Teams API. + - Also allows to add members in the team (if members exists). + - The Teams API is only available starting Grafana 5 and the module will fail if the server version is lower than version 5. +options: + name: + description: + - The name of the Grafana Team. + required: true + type: str + email: + description: + - The mail address associated with the Team. + required: true + type: str + members: + description: + - List of team members (emails). + - The list can be enforced with C(enforce_members) parameter. + type: list + elements: str + state: + description: + - Delete the members not found in the C(members) parameters from the + - list of members found on the Team. + default: present + type: str + choices: ["present", "absent"] + enforce_members: + description: + - Delete the members not found in the C(members) parameters from the + - list of members found on the Team. + default: False + type: bool +extends_documentation_fragment: +- community.grafana.basic_auth +- community.grafana.api_key +''' + +EXAMPLES = ''' +--- +- name: Create a team + community.grafana.grafana_team: + url: "https://grafana.example.com" + grafana_api_key: "{{ some_api_token_value }}" + name: "grafana_working_group" + email: "foo.bar@example.com" + state: present + +- name: Create a team with members + community.grafana.grafana_team: + url: "https://grafana.example.com" + grafana_api_key: "{{ some_api_token_value }}" + name: "grafana_working_group" + email: "foo.bar@example.com" + members: + - john.doe@example.com + - jane.doe@example.com + state: present + +- name: Create a team with members and enforce the list of members + community.grafana.grafana_team: + url: "https://grafana.example.com" + grafana_api_key: "{{ some_api_token_value }}" + name: "grafana_working_group" + email: "foo.bar@example.com" + members: + - john.doe@example.com + - jane.doe@example.com + enforce_members: yes + state: present + +- name: Delete a team + community.grafana.grafana_team: + url: "https://grafana.example.com" + grafana_api_key: "{{ some_api_token_value }}" + name: "grafana_working_group" + email: "foo.bar@example.com" + state: absent +''' + +RETURN = ''' +--- +team: + description: Information about the Team + returned: On success + type: complex + contains: + avatarUrl: + description: The url of the Team avatar on Grafana server + returned: always + type: str + sample: + - "/avatar/a7440323a684ea47406313a33156e5e9" + email: + description: The Team email address + returned: always + type: str + sample: + - "foo.bar@example.com" + id: + description: The Team email address + returned: always + type: int + sample: + - 42 + memberCount: + description: The number of Team members + returned: always + type: int + sample: + - 42 + name: + description: The name of the team. + returned: always + type: str + sample: + - "grafana_working_group" + members: + description: The list of Team members + returned: always + type: list + sample: + - ["john.doe@exemple.com"] + orgId: + description: The organization id that the team is part of. + returned: always + type: int + sample: + - 1 +''' + +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.urls import fetch_url, basic_auth_header +from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, grafana_required_together, grafana_mutually_exclusive + +__metaclass__ = type + + +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'] + else: + self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) + # }}} + self.grafana_url = module.params.get("url") + grafana_version = self.get_version() + if grafana_version["major"] < 5: + self._module.fail_json(failed=True, msg="Teams API is available starting Grafana v5") + + def _send_request(self, url, data=None, headers=None, method="GET"): + if data is not None: + data = json.dumps(data, sort_keys=True) + if not headers: + 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) + 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)) + 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) + + def get_version(self): + url = "/api/health" + response = self._send_request(url, data=None, headers=self.headers, method="GET") + version = response.get("version") + major, minor, rev = version.split(".") + return {"major": int(major), "minor": int(minor), "rev": int(rev)} + + 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") + return response + + def get_team(self, name): + url = "/api/teams/search?name={team}".format(team=name) + response = self._send_request(url, headers=self.headers, method="GET") + if not response.get("totalCount") <= 1: + raise AssertionError("Expected 1 team, got %d" % response["totalCount"]) + + if len(response.get("teams")) == 0: + return None + return response.get("teams")[0] + + 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") + return response + + def delete_team(self, team_id): + url = "/api/teams/{team_id}".format(team_id=team_id) + response = self._send_request(url, headers=self.headers, method="DELETE") + return response + + def get_team_members(self, team_id): + url = "/api/teams/{team_id}/members".format(team_id=team_id) + response = self._send_request(url, headers=self.headers, method="GET") + members = [item.get("email") for item in response] + return members + + def add_team_member(self, team_id, email): + url = "/api/teams/{team_id}/members".format(team_id=team_id) + data = {"userId": self.get_user_id_from_mail(email)} + self._send_request(url, data=data, headers=self.headers, method="POST") + + 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) + self._send_request(url, headers=self.headers, method="DELETE") + + def get_user_id_from_mail(self, email): + url = "/api/users/lookup?loginOrEmail={email}".format(email=email) + user = self._send_request(url, headers=self.headers, method="GET") + if user is None: + self._module.fail_json(failed=True, msg="User '%s' does not exists" % email) + return user.get("id") + + +def setup_module_object(): + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=False, + required_together=grafana_required_together(), + mutually_exclusive=grafana_mutually_exclusive(), + ) + return module + + +argument_spec = 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), +) + + +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'] + + grafana_iface = GrafanaTeamInterface(module) + + changed = False + if state == 'present': + team = grafana_iface.get_team(name) + if team is None: + grafana_iface.create_team(name, email) + team = grafana_iface.get_team(name) + changed = True + if members is not None: + cur_members = grafana_iface.get_team_members(team.get("id")) + plan = diff_members(members, cur_members) + for member in plan.get("to_add"): + grafana_iface.add_team_member(team.get("id"), member) + changed = True + if enforce_members: + for member in plan.get("to_del"): + 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")) + module.exit_json(failed=False, changed=changed, team=team) + elif state == 'absent': + team = grafana_iface.get_team(name) + if team is None: + module.exit_json(failed=False, changed=False, message="No team found") + result = grafana_iface.delete_team(team.get("id")) + module.exit_json(failed=False, changed=True, message=result.get("message")) + + +def diff_members(target, current): + diff = {"to_del": [], "to_add": []} + for member in target: + if member not in current: + diff["to_add"].append(member) + for member in current: + if member not in target: + diff["to_del"].append(member) + return diff + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_user.py b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_user.py new file mode 100644 index 00000000..c56e6bcb --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/plugins/modules/grafana_user.py @@ -0,0 +1,299 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. +# +# Copyright: (c) 2020, Antoine Tanzilli (@Tailzip), Hong Viet Lê (@pomverte), Julien Alexandre (@jual), Marc Cyprien (@LeFameux) + +from __future__ import absolute_import, division, print_function + +DOCUMENTATION = ''' +--- +module: grafana_user +author: + - Antoine Tanzilli (@Tailzip) + - Hong Viet LE (@pomverte) + - Julien Alexandre (@jual) + - Marc Cyprien (@LeFameux) +version_added: "1.0.0" +short_description: Manage Grafana User +description: + - Create/update/delete Grafana User through the users and admin API. + - Tested with Grafana v6.4.3 + - Password update is not supported at the time +options: + name: + description: + - The name of the Grafana User. + required: false + type: str + email: + description: + - The email of the Grafana User. + required: false + type: str + login: + description: + - The login of the Grafana User. + required: true + type: str + password: + description: + - The password of the Grafana User. + - At the moment, this field is not updated yet. + required: false + type: str + is_admin: + description: + - The Grafana User is an admin. + required: false + type: bool + default: false + state: + description: + - State if the user should be present in Grafana or not + default: present + type: str + choices: ["present", "absent"] +extends_documentation_fragment: +- community.grafana.basic_auth +''' + +EXAMPLES = ''' +--- +- name: Create or update a Grafana user + community.grafana.grafana_user: + url: "https://grafana.example.com" + url_username: admin + url_password: changeme + name: "Bruce Wayne" + email: batman@gotham.city + login: batman + password: robin + is_admin: true + state: present + +- name: Delete a Grafana user + community.grafana.grafana_user: + url: "https://grafana.example.com" + url_username: admin + url_password: changeme + login: batman + state: absent +''' + +RETURN = ''' +--- +user: + description: Information about the User + returned: when state present + type: complex + contains: + id: + description: The User id + returned: always + type: int + sample: + - 42 + email: + description: The User email address + returned: always + type: str + sample: + - "foo.bar@example.com" + login: + description: The User login + returned: always + type: str + sample: + - "batman" + theme: + description: The Grafana theme + returned: always + type: str + sample: + - "light" + orgId: + description: The organization id that the team is part of. + returned: always + type: int + sample: + - 1 + isGrafanaAdmin: + description: The Grafana user permission for admin + returned: always + type: bool + sample: + - false + isDisabled: + description: The Grafana account status + returned: always + type: bool + sample: + - false + isExternal: + description: The Grafana account information on external user provider + returned: always + type: bool + sample: + - false +''' + +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.urls import fetch_url, basic_auth_header +from ansible_collections.community.grafana.plugins.module_utils.base import grafana_argument_spec, grafana_required_together, grafana_mutually_exclusive + +__metaclass__ = type + + +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.grafana_url = module.params.get("url") + + def _send_request(self, url, data=None, headers=None, method="GET"): + if data is not None: + data = json.dumps(data, sort_keys=True) + if not headers: + 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) + 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)) + 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())) + + 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") + 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") + return self.get_user_from_login(login) + + def get_user_from_login(self, login): + # https://grafana.com/docs/http_api/user/#get-single-user-by-username-login-or-email + url = "/api/users/lookup?loginOrEmail={login}".format(login=login) + return self._send_request(url, headers=self.headers, method="GET") + + def update_user(self, user_id, email, name, login): + # https://grafana.com/docs/http_api/user/#user-update + url = "/api/users/{user_id}".format(user_id=user_id) + user = dict(email=email, name=name, login=login) + self._send_request(url, data=user, headers=self.headers, method="PUT") + return self.get_user_from_login(login) + + 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") + + def delete_user(self, user_id): + # https://grafana.com/docs/http_api/admin/#delete-global-user + url = "/api/admin/users/{user_id}".format(user_id=user_id) + return self._send_request(url, headers=self.headers, method="DELETE") + + +def is_user_update_required(target_user, email, name, login, is_admin): + # compare value before in target_user object and param + target_user_dict = dict( + email=target_user.get("email"), + name=target_user.get("name"), + login=target_user.get("login"), + 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 + + +def setup_module_object(): + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=False, + required_if=[ + ['state', 'present', ['name', 'email']], + ], + required_together=grafana_required_together() + ) + return module + + +argument_spec = 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), +) +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'] + + grafana_iface = GrafanaUserInterface(module) + + # search user by login + target_user = grafana_iface.get_user_from_login(login) + if state == 'present': + + if target_user is None: + # create new user + user = grafana_iface.create_user(name, email, login, password) + module.exit_json(changed=True, user=user) + + if is_user_update_required(target_user, email, name, login, is_admin): + # update found user + target_user_id = target_user.get("id") + if is_admin != target_user.get("isGrafanaAdmin"): + grafana_iface.update_user_permissions(target_user_id, is_admin) + user = grafana_iface.update_user(target_user_id, email, name, login) + module.exit_json(changed=True, user=user) + + module.exit_json(user=target_user) + + elif state == 'absent': + if target_user is None: + module.exit_json(message="No user found, nothing to do") + result = grafana_iface.delete_user(target_user.get("id")) + module.exit_json(changed=True, message=result.get("message")) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/.gitignore b/collections-debian-merged/ansible_collections/community/grafana/tests/.gitignore new file mode 100644 index 00000000..ea1472ec --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/.gitignore @@ -0,0 +1 @@ +output/ diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/aliases b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/aliases new file mode 100644 index 00000000..a6dafcf8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/aliases @@ -0,0 +1 @@ +shippable/posix/group1 diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/defaults/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/defaults/main.yml new file mode 100644 index 00000000..500c1bb8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/defaults/main.yml @@ -0,0 +1,7 @@ +--- + +grafana_url: "http://grafana:3000" +grafana_username: "admin" +grafana_password: "admin" + +... diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/files/dashboard.json b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/files/dashboard.json new file mode 100644 index 00000000..70287fa7 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/files/dashboard.json @@ -0,0 +1,85 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": "-- Grafana --", + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "gnetId": null, + "graphTooltip": 0, + "id": 11, + "links": [], + "panels": [ + { + "content": "\n# Title\n\nFor markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)\n\n\n\n", + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 2, + "mode": "markdown", + "options": {}, + "targets": [ + { + "expr": "", + "format": "time_series", + "intervalFactor": 1, + "refId": "A" + } + ], + "timeFrom": null, + "timeShift": null, + "title": "Panel Title", + "type": "text" + } + ], + "schemaVersion": 18, + "style": "dark", + "tags": [], + "templating": { + "list": [] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": { + "refresh_intervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "time_options": [ + "5m", + "15m", + "1h", + "6h", + "12h", + "24h", + "2d", + "7d", + "30d" + ] + }, + "timezone": "", + "title": "test", + "uid": "9ZlJIhhWk", + "version": 7 + }
\ No newline at end of file diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml new file mode 100644 index 00000000..93df1666 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-file.yml @@ -0,0 +1,44 @@ +--- +- name: copy dashboard file + copy: + src: "files/dashboard.json" + dest: "/tmp/dashboard.json" + + +- name: Check import grafana dashboard from file + 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 + +- debug: + var: result + +- assert: + that: + - "result.changed == true" + - "result.msg == 'Dashboard test created'" + +- name: Check import grafana dashboard from file idempotency + 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 + +- debug: + var: result + +- assert: + that: + - "result.changed == false" + - "result.msg == 'Dashboard test unchanged.'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml new file mode 100644 index 00000000..3b81ebf7 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-id.yml @@ -0,0 +1,40 @@ +--- +- name: Check import grafana dashboard from id + grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + dashboard_id: "6098" + dashboard_revision: "1" + overwrite: true + register: result + +- debug: + var: result + +- assert: + that: + - "result.changed == true" + - "result.msg == 'Dashboard Zabbix Host Status created'" + +- name: Check import grafana dashboard from id idempotency + grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + dashboard_id: "6098" + dashboard_revision: "1" + overwrite: true + register: result + +- debug: + var: result + +- assert: + that: + - "result.changed == false" + - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml new file mode 100644 index 00000000..5146fc9a --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/dashboard-from-url.yml @@ -0,0 +1,39 @@ +--- + +- name: Check import grafana dashboard from url + grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download + overwrite: true + register: result + +- debug: + var: result + +- assert: + that: + - "result.changed == true" + - "result.msg == 'Dashboard Zabbix Host Status created'" + +- name: Check import grafana dashboard from url idempotency + grafana_dashboard: + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + state: present + commit_message: Updated by ansible + dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download + overwrite: true + register: result + +- debug: + var: result + +- assert: + that: + - "result.changed == false" + - "result.msg == 'Dashboard Zabbix Host Status unchanged.'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml new file mode 100644 index 00000000..2013324f --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/delete-dashboard.yml @@ -0,0 +1,16 @@ +- name: Check delete dashboard is working + 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: + that: + - "result.changed == true" + - "result.msg == 'Dashboard {{ result.uid }} deleted'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/main.yml new file mode 100644 index 00000000..dd348a2a --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_dashboard/tasks/main.yml @@ -0,0 +1,5 @@ +- block: + - include: dashboard-from-url.yml + - include: delete-dashboard.yml + - include: dashboard-from-id.yml + - include: dashboard-from-file.yml diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/aliases b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/aliases new file mode 100644 index 00000000..a6dafcf8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/aliases @@ -0,0 +1 @@ +shippable/posix/group1 diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/defaults/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/defaults/main.yml new file mode 100644 index 00000000..500c1bb8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/defaults/main.yml @@ -0,0 +1,7 @@ +--- + +grafana_url: "http://grafana:3000" +grafana_username: "admin" +grafana_password: "admin" + +... diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml new file mode 100644 index 00000000..9e778342 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/cloudwatch.yml @@ -0,0 +1,127 @@ +- name: Create cloudwatch datasource + register: result + grafana_datasource: + name: datasource-cloudwatch + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + org_id: '1' + ds_type: cloudwatch + ds_url: http://monitoring.us-west-1.amazonaws.com + aws_auth_type: keys + aws_default_region: us-west-1 + aws_access_key: speakFriendAndEnter + aws_secret_key: mel10n + aws_custom_metrics_namespaces: n1,n2 + +- debug: + var: result + +- 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 + - 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: + name: datasource-cloudwatch + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: cloudwatch + ds_url: http://monitoring.us-west-1.amazonaws.com + aws_auth_type: keys + aws_default_region: us-west-1 + aws_access_key: speakFriendAndEnter + aws_secret_key: mel10n + aws_custom_metrics_namespaces: n1,n2 + +- debug: + var: result + +- 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 + - 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: + name: datasource-cloudwatch + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + org_id: '1' + ds_type: cloudwatch + ds_url: http://monitoring.us-west-1.amazonaws.com + aws_auth_type: keys + aws_default_region: us-west-1 + aws_access_key: speakFriendAndEnter + aws_secret_key: mel10n + aws_custom_metrics_namespaces: n1,n2 + state: absent + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-cloudwatch deleted.'" + +- name: Delete cloudwatch datasource (idempotency) + register: result + grafana_datasource: + name: datasource-cloudwatch + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + org_id: '1' + ds_type: cloudwatch + ds_url: http://monitoring.us-west-1.amazonaws.com + aws_auth_type: keys + aws_default_region: us-west-1 + aws_access_key: speakFriendAndEnter + aws_secret_key: mel10n + aws_custom_metrics_namespaces: n1,n2 + state: absent + +- debug: + var: result + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/elastic.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/elastic.yml new file mode 100644 index 00000000..9185a2d9 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/elastic.yml @@ -0,0 +1,289 @@ +- name: Create elasticsearch datasource + register: result + grafana_datasource: + name: datasource-elastic + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.company.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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: + var: result + +- 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 + - 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 + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.company.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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: + var: result + +- 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 == 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 + - 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 + register: result + grafana_datasource: + name: datasource-elastic + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.example.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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: + var: result + +- 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 + - 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) + register: result + grafana_datasource: + name: datasource-elastic + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.example.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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 + enforce_secure_data: false + additional_json_data: + nonSecureTest: "nonsecure" + additional_secure_json_data: + secureTest: "secure" + +- debug: + var: result + +- 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 + - 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) + register: result + grafana_datasource: + name: datasource-elastic + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.example.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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 + enforce_secure_data: true + additional_json_data: + nonSecureTest: "nonsecure" + additional_secure_json_data: + secureTest: "secure" + +- debug: + var: result + +- 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 + - 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 + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.company.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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 + state: absent + +- assert: + that: + - result.changed + +- name: Delete elasticsearch datasource (idempotency) + register: result + grafana_datasource: + name: datasource-elastic + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: elasticsearch + ds_url: https://elastic.company.com:9200 + database: '[logstash_]YYYY.MM.DD' + basic_auth_user: grafana + 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 + state: absent + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/influx.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/influx.yml new file mode 100644 index 00000000..2ef6a278 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/influx.yml @@ -0,0 +1,100 @@ +- name: Create influxdb datasource + register: result + grafana_datasource: + name: datasource-influxdb + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: influxdb + ds_url: https://influx.company.com:8086 + database: telegraf + time_interval: '>10s' + tls_ca_cert: /etc/ssl/certs/ca.pem + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-influxdb created'" + +- name: Check influxdb datasource creation idempotency + register: result + grafana_datasource: + name: datasource-influxdb + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: influxdb + ds_url: https://influx.company.com:8086 + database: telegraf + time_interval: '>10s' + tls_ca_cert: /etc/ssl/certs/ca.pem + +- debug: + var: result + +- 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 == false + - result.datasource.name == 'datasource-influxdb' + - result.datasource.orgId == 1 + - 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: + name: datasource-influxdb + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: influxdb + ds_url: https://influx.company.com:8086 + database: telegraf + time_interval: '>10s' + tls_ca_cert: /etc/ssl/certs/ca.pem + state: absent + +- debug: + var: result + +- assert: + that: + - result.changed + +- name: Delete influxdb datasource (idempotency) + register: result + grafana_datasource: + name: datasource-influxdb + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: influxdb + ds_url: https://influx.company.com:8086 + database: telegraf + time_interval: '>10s' + tls_ca_cert: /etc/ssl/certs/ca.pem + state: absent + +- debug: + var: result + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/loki.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/loki.yml new file mode 100644 index 00000000..728da609 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/loki.yml @@ -0,0 +1,88 @@ +- name: Create loki datasource + register: result + grafana_datasource: + name: datasource-loki + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + org_id: '1' + ds_type: loki + ds_url: https://loki.company.com:3100 + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-loki created'" + +- name: Check loki datasource creation idempotency + register: result + grafana_datasource: + name: datasource-loki + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: loki + ds_url: https://loki.company.com:3100 + +- debug: + var: result + +- 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 + - 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: + name: datasource-loki + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + org_id: '1' + ds_type: loki + ds_url: https://loki.company.com:3100 + state: absent + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-loki deleted.'" + +- name: Delete loki datasource (idempotency) + register: result + grafana_datasource: + name: datasource-loki + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + org_id: '1' + ds_type: loki + ds_url: https://loki.company.com:3100 + state: absent + +- debug: + var: result + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/main.yml new file mode 100644 index 00000000..c5e5ab2d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/main.yml @@ -0,0 +1,12 @@ +--- + +- block: + - include: elastic.yml + - include: influx.yml + - include: postgres.yml + - include: cloudwatch.yml + - include: thruk.yml + - include: loki.yml + - include: zabbix.yml + +... diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/postgres.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/postgres.yml new file mode 100644 index 00000000..5712a41f --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/postgres.yml @@ -0,0 +1,107 @@ +- name: Create postgres datasource + register: result + grafana_datasource: + name: datasource-postgres + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: postgres + ds_url: postgres.company.com:5432 + database: db + user: postgres + password: iampgroot + sslmode: verify-full + additional_json_data: + timescaledb: true + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-postgres created'" + +- name: Check postgres datasource creation idempotency + register: result + grafana_datasource: + name: datasource-postgres + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: postgres + ds_url: postgres.company.com:5432 + database: db + user: postgres + password: iampgroot + sslmode: verify-full + additional_json_data: + timescaledb: true + +- debug: + var: result + +- 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 + +- name: Delete postgres datasource + register: result + grafana_datasource: + name: datasource-postgres + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: postgres + ds_url: postgres.company.com:5432 + database: db + user: postgres + password: iampgroot + sslmode: verify-full + state: absent + +- debug: + var: result + +- assert: + that: + - result.changed + +- name: Delete postgres datasource + register: result + grafana_datasource: + name: datasource-postgres + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: postgres + ds_url: postgres.company.com:5432 + database: db + user: postgres + password: iampgroot + sslmode: verify-full + state: absent + +- debug: + var: result + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/thruk.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/thruk.yml new file mode 100644 index 00000000..50b7e31d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/thruk.yml @@ -0,0 +1,88 @@ +- name: Create thruk datasource + register: result + 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 + +- debug: + var: result + +- assert: + that: + - result.changed + - "result.msg == 'Datasource datasource-thruk created'" + +- name: Check thruk datasource creation idempotency + register: result + 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 + +- 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 + - 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: + 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 + state: absent + +- debug: + var: result + +- assert: + that: + - result.changed + +- name: Delete thruk datasource (idempotency) + register: result + 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 + state: absent + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/zabbix.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/zabbix.yml new file mode 100644 index 00000000..b4e494e1 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_datasource/tasks/zabbix.yml @@ -0,0 +1,126 @@ +- name: Create zabbix datasource + register: result + grafana_datasource: + name: datasource-zabbix + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: alexanderzobnin-zabbix-datasource + ds_url: https://zabbix.company.com + zabbix_user: grafana + zabbix_password: '******' + +- debug: + var: result + +- assert: + that: + - result.changed + - not result.datasource.isDefault + - result.datasource.jsonData.username == 'grafana' + - result.datasource.name == 'datasource-zabbix' + - result.datasource.orgId == 1 + - 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: + name: datasource-zabbix + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: alexanderzobnin-zabbix-datasource + ds_url: https://zabbix.company.com + zabbix_user: grafana + zabbix_password: '******' + +- debug: + var: result + +- assert: + that: + - not result.changed + - not result.datasource.isDefault + - result.datasource.jsonData.username == 'grafana' + - result.datasource.name == 'datasource-zabbix' + - result.datasource.orgId == 1 + - 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: + name: datasource-zabbix + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: alexanderzobnin-zabbix-datasource + ds_url: https://zabbix.example.com + zabbix_user: grafana + zabbix_password: '******' + +- debug: + var: result + +- assert: + that: + - result.changed + - not result.datasource.isDefault + - result.datasource.jsonData.username == 'grafana' + - result.datasource.name == 'datasource-zabbix' + - result.datasource.orgId == 1 + - 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: + name: datasource-zabbix + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: alexanderzobnin-zabbix-datasource + ds_url: https://zabbix.example.com + zabbix_user: grafana + zabbix_password: '******' + tls_ca_cert: /etc/ssl/certs/ca.pem + state: absent + +- assert: + that: + - result.changed + +- name: Delete zabbix datasource (idempotency) + register: result + grafana_datasource: + name: datasource-zabbix + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password }}" + org_id: '1' + ds_type: alexanderzobnin-zabbix-datasource + ds_url: https://zabbix.example.com + zabbix_user: grafana + zabbix_password: '******' + tls_ca_cert: /etc/ssl/certs/ca.pem + state: absent + +- assert: + that: + - not result.changed diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_folder/defaults/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_folder/defaults/main.yml new file mode 100644 index 00000000..500c1bb8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_folder/defaults/main.yml @@ -0,0 +1,7 @@ +--- + +grafana_url: "http://grafana:3000" +grafana_username: "admin" +grafana_password: "admin" + +... diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_folder/tasks/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_folder/tasks/main.yml new file mode 100644 index 00000000..c6a52056 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_folder/tasks/main.yml @@ -0,0 +1,55 @@ +--- + +- name: Create a Folder + grafana_folder: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + title: "grafana_working_group" + state: present + register: result + +- assert: + that: + - "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 + register: result + +- assert: + that: + - "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 + register: result + +- assert: + that: + - "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 + register: result + +- assert: + that: + - "result.changed == false" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/defaults/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/defaults/main.yml new file mode 100644 index 00000000..500c1bb8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/defaults/main.yml @@ -0,0 +1,7 @@ +--- + +grafana_url: "http://grafana:3000" +grafana_username: "admin" +grafana_password: "admin" + +... diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml new file mode 100644 index 00000000..58cffbb0 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/dingding.yml @@ -0,0 +1,36 @@ +--- +- name: Create dingding notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete dingding notification channel + register: result + grafana_notification_channel: + uid: dingding + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/discord.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/discord.yml new file mode 100644 index 00000000..917d96d9 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/discord.yml @@ -0,0 +1,36 @@ +--- +- name: Create discord notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete discord notification channel + register: result + grafana_notification_channel: + uid: discord + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/email.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/email.yml new file mode 100644 index 00000000..d224cf50 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/email.yml @@ -0,0 +1,38 @@ +--- +- name: Create email notification channel + register: result + grafana_notification_channel: + uid: email + name: email + type: email + email_addresses: + - foo@example.org + - bar@example.org + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete discord notification channel + register: result + grafana_notification_channel: + uid: email + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml new file mode 100644 index 00000000..f45516cf --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/googlechat.yml @@ -0,0 +1,36 @@ +--- +- name: Create googlechat notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete googlechat notification channel + register: result + grafana_notification_channel: + uid: googlechat + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml new file mode 100644 index 00000000..af8fed7f --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/hipchat.yml @@ -0,0 +1,36 @@ +--- +- name: Create hipchat notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete hipchat notification channel + register: result + grafana_notification_channel: + uid: hipchat + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml new file mode 100644 index 00000000..ca950414 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/kafka.yml @@ -0,0 +1,37 @@ +--- +- name: Create kafka notification channel + register: result + grafana_notification_channel: + uid: kafka + name: kafka + type: kafka + kafka_url: https://example.org + kafka_topic: test + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete kafka notification channel + register: result + grafana_notification_channel: + uid: kafka + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/line.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/line.yml new file mode 100644 index 00000000..e8ba02ca --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/line.yml @@ -0,0 +1,36 @@ +--- +- name: Create line notification channel + register: result + grafana_notification_channel: + uid: line + name: line + type: line + line_token: xxx + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete line notification channel + register: result + grafana_notification_channel: + uid: line + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/main.yml new file mode 100644 index 00000000..5ea36676 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/main.yml @@ -0,0 +1,20 @@ +--- +- block: +# - include: dingding.yml +# - include: discord.yml +# - include: email.yml +# - include: googlechat.yml +# - include: hipchat.yml +# - include: kafka.yml +# - include: line.yml +# - include: teams.yml +# - include: opsgenie.yml +# - include: pagerduty.yml +# - include: prometheus.yml +# - include: pushover.yml +# - include: sensu.yml + - include: slack-and-beyond.yml + - include: telegram.yml + - include: threema.yml + - include: victorops.yml + - include: webhook.yml diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml new file mode 100644 index 00000000..bbf8617e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/opsgenie.yml @@ -0,0 +1,37 @@ +--- +- name: Create opsgenie notification channel + register: result + grafana_notification_channel: + uid: opsgenie + name: opsgenie + type: opsgenie + opsgenie_url: https://example.org + opsgenie_api_key: xxx + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete opsgenie notification channel + register: result + grafana_notification_channel: + uid: opsgenie + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml new file mode 100644 index 00000000..d2b09f1a --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/pagerduty.yml @@ -0,0 +1,36 @@ +--- +- name: Create pagerduty notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete pagerduty notification channel + register: result + grafana_notification_channel: + uid: pagerduty + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml new file mode 100644 index 00000000..e42868e5 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/prometheus.yml @@ -0,0 +1,36 @@ +--- +- name: Create prometheus notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete prometheus notification channel + register: result + grafana_notification_channel: + uid: prometheus + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml new file mode 100644 index 00000000..0fe04d55 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/pushover.yml @@ -0,0 +1,37 @@ +--- +- name: Create pushover notification channel + register: result + grafana_notification_channel: + uid: pushover + name: pushover + type: pushover + pushover_api_token: xxx + pushover_user_key: yyy + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete pushover notification channel + register: result + grafana_notification_channel: + uid: pushover + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml new file mode 100644 index 00000000..eaf7ad8a --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/sensu.yml @@ -0,0 +1,36 @@ +--- +- name: Create sensu notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete sensu notification channel + register: result + grafana_notification_channel: + uid: sensu + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml new file mode 100644 index 00000000..db9efe3b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/slack-and-beyond.yml @@ -0,0 +1,72 @@ +--- +- name: Create slack notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Check slack notification channel idempotency + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == False" + +- name: Update slack notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + +- name: Delete slack notification channel + register: result + grafana_notification_channel: + state: absent + uid: slack + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/teams.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/teams.yml new file mode 100644 index 00000000..5f08ee9b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/teams.yml @@ -0,0 +1,36 @@ +--- +- name: Create teams notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete teams notification channel + register: result + grafana_notification_channel: + uid: teams + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml new file mode 100644 index 00000000..2841b336 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/telegram.yml @@ -0,0 +1,37 @@ +--- +- name: Create telegram notification channel + register: result + grafana_notification_channel: + uid: telegram + name: telegram + type: telegram + telegram_bot_token: xxx + telegram_chat_id: yyy + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete telegram notification channel + register: result + grafana_notification_channel: + uid: telegram + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/threema.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/threema.yml new file mode 100644 index 00000000..1a21ff32 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/threema.yml @@ -0,0 +1,38 @@ +--- +- name: Create threema notification channel + register: result + grafana_notification_channel: + uid: threema + name: threema + type: threema + threema_gateway_id: xxx + threema_recepient_id: yyy + threema_api_secret: zzz + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete threema notification channel + register: result + grafana_notification_channel: + uid: threema + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml new file mode 100644 index 00000000..b043d2cf --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/victorops.yml @@ -0,0 +1,36 @@ +--- +- name: Create victorops notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete victorops notification channel + register: result + grafana_notification_channel: + uid: victorops + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml new file mode 100644 index 00000000..fc1cb56a --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_notification_channel/tasks/webhook.yml @@ -0,0 +1,36 @@ +--- +- name: Create webhook notification channel + register: result + 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}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'present'" + +- name: Delete webhook notification channel + register: result + grafana_notification_channel: + uid: webhook + state: absent + grafana_url: "{{ grafana_url }}" + grafana_user: "{{ grafana_username }}" + grafana_password: "{{ grafana_password}}" + +- debug: + var: result + +- assert: + that: + - "result.changed == True" + - "result.state == 'absent'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/defaults/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/defaults/main.yml new file mode 100644 index 00000000..500c1bb8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/defaults/main.yml @@ -0,0 +1,7 @@ +--- + +grafana_url: "http://grafana:3000" +grafana_username: "admin" +grafana_password: "admin" + +... diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/tasks/create_user.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/tasks/create_user.yml new file mode 100644 index 00000000..dfd0bac1 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/tasks/create_user.yml @@ -0,0 +1,29 @@ +- name: Create John Doe for tests purpose through uri module + uri: + url: "{{ grafana_url }}/api/admin/users" + method: POST + user: "{{ grafana_username }}" + password: "{{ grafana_password }}" + force_basic_auth: yes + body: + 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: + url: "{{ grafana_url }}/api/admin/users" + method: POST + user: "{{ grafana_username }}" + password: "{{ grafana_password }}" + force_basic_auth: yes + body: + name: "Jane" + email: "jane.doe@example.com" + login: "jane" + password: "userpassword" + body_format: json + status_code: 200 diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/tasks/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/tasks/main.yml new file mode 100644 index 00000000..104d2281 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_team/tasks/main.yml @@ -0,0 +1,171 @@ +--- + +- name: Create a Team without members + 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: + that: + - "result.changed == true" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 0" + - "result.team.members == []" + - "result.team.email == 'foo.bar@example.com'" + +- 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 + register: result + +- assert: + that: + - "result.changed == false" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 0" + - "result.team.members == []" + - "result.team.email == 'foo.bar@example.com'" + +- 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 + register: result + +- assert: + that: + - "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 + register: result + +- assert: + that: + - "result.changed == false" + - "result.message == 'No team found'" + +- name: Create users for tests purpose + import_tasks: 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 + register: result + +- assert: + that: + - "result.changed == true" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 2" + - "result.team.members == ['jane.doe@example.com', 'john.doe@example.com']" + - "result.team.email == 'foo.bar@example.com'" + +- 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 + register: result + +- assert: + that: + - "result.changed == false" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 2" + - "result.team.members == ['jane.doe@example.com', 'john.doe@example.com']" + - "result.team.email == 'foo.bar@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: + - "john.doe@example.com" + enforce_members: true + state: present + register: result + +- assert: + that: + - "result.changed == true" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 1" + - "result.team.members == ['john.doe@example.com']" + - "result.team.email == 'foo.bar@example.com'" + +- 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 + register: result + +- assert: + that: + - "result.changed == false" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 1" + - "result.team.members == ['john.doe@example.com']" + - "result.team.email == 'foo.bar@example.com'" + +- 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 + register: result + +- assert: + that: + - "result.changed == true" + - "result.team.name == 'grafana_working_group'" + - "result.team.memberCount == 2" + - "result.team.members == ['jane.doe@example.com', 'john.doe@example.com']" + - "result.team.email == 'foo.bar@example.com'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_user/defaults/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_user/defaults/main.yml new file mode 100644 index 00000000..48d728e5 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_user/defaults/main.yml @@ -0,0 +1,4 @@ +--- +grafana_url: "http://grafana:3000" +grafana_username: "admin" +grafana_password: "admin" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_user/tasks/main.yml b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_user/tasks/main.yml new file mode 100644 index 00000000..d63b2b74 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/integration/targets/grafana_user/tasks/main.yml @@ -0,0 +1,97 @@ +--- +- name: Create a Grafana user without password (expect failure) + grafana_user: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: "Bruce Wayne" + email: batman@gotham.city + login: batman + state: present + register: result + ignore_errors: yes +- assert: + that: + - "result.changed == false" + - "result.failed == true" + - "result.msg == 'missing required arguments: password'" + +- name: Create a Grafana user + grafana_user: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: "Bruce Wayne" + email: batman@gotham.city + login: batman + password: robin + state: present + register: result +- assert: + that: + - "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: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: "Bruce Wayne" + email: batman@gotham.city + login: batman + state: present + register: result +- assert: + that: + - "result.changed == false" + - "result.user.name == 'Bruce Wayne'" + - "result.user.email == 'batman@gotham.city'" + - "result.user.isGrafanaAdmin == false" + +- name: Update Grafana user + grafana_user: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + name: "The Dark Knight" + email: thedarkknight@gotham.city + login: batman + password: robin + is_admin: true + state: present + register: result +- assert: + that: + - "result.changed == true" + - "result.user.name == 'The Dark Knight'" + - "result.user.email == 'thedarkknight@gotham.city'" + - "result.user.isGrafanaAdmin == true" + +- name: Delete a Grafana user + grafana_user: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + login: batman + state: absent + register: result +- assert: + that: + - "result.changed == true" + - "result.message == 'User deleted'" + +- name: Check idempotency on user deletion + grafana_user: + url: "{{ grafana_url }}" + url_username: "{{ grafana_username }}" + url_password: "{{ grafana_password }}" + login: batman + state: absent + register: result +- assert: + that: + - "result.changed == false" + - "result.message == 'No user found, nothing to do'" diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.10.txt b/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.10.txt new file mode 100644 index 00000000..feba60d3 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.10.txt @@ -0,0 +1,2 @@ +plugins/modules/grafana_dashboard.py validate-modules:invalid-argument-name +tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py pep8:W291 diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.11.txt b/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.11.txt new file mode 100644 index 00000000..feba60d3 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.11.txt @@ -0,0 +1,2 @@ +plugins/modules/grafana_dashboard.py validate-modules:invalid-argument-name +tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py pep8:W291 diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.9.txt b/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.9.txt new file mode 100644 index 00000000..81db56a9 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/sanity/ignore-2.9.txt @@ -0,0 +1 @@ +tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py pep8:W291 diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py b/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py new file mode 100644 index 00000000..b3b025c4 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_plugin/test_grafana_plugin.py @@ -0,0 +1,111 @@ +from __future__ import (absolute_import, division, print_function) + +from unittest import TestCase +from unittest.mock import patch, MagicMock +from ansible_collections.community.grafana.plugins.modules import grafana_plugin + +__metaclass__ = type + + +def run_command_ls(): + STDERR = "" + STDOUT = """ +installed plugins: +alexanderzobnin-zabbix-app @ 3.10.5 + +Restart grafana after installing plugins . <service grafana-server restart> +""" + return 0, STDOUT, STDERR + + +def run_command_install_zip(): + STDERR = "" + STDOUT = """ +installing alexanderzobnin-grafana-zabbix @ +from: /home/grafana//alexanderzobnin-grafana-zabbix-v3.10.5-1-g2219691.zip +into: /var/lib/grafana/plugins + +... Installed alexanderzobnin-grafana-zabbix successfully + +Restart grafana after installing plugins . <service grafana-server restart> + +""" + return 0, STDOUT, STDERR + + +def run_command_uninstall(): + STDERR = "" + STDOUT = """ +Removing plugin: alexanderzobnin-zabbix-app + +Restart grafana after installing plugins . <service grafana-server restart> +""" + return 0, STDOUT, STDERR + + +def run_command_uninstall_again(): + STDERR = "" + STDOUT = """ +Removing plugin: alexanderzobnin-zabbix-app +Error: ✗ plugin does not exist +""" + return 1, STDOUT, STDERR + + +class GrafanaPlugin(TestCase): + + @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" + } + + module = MagicMock() + module.run_command.return_value = run_command_install_zip() + + 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') + def test_plugin_ls(self, mock_grafana_cli_bin): + mock_grafana_cli_bin.return_value = "grafana-cli plugins" + + params = { + "name": "alexanderzobnin-zabbix-app" + } + + module = MagicMock() + module.run_command.return_value = run_command_ls() + + 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') + def test_plugin_uninstall(self, mock_grafana_cli_bin): + mock_grafana_cli_bin.return_value = "grafana-cli plugins" + + params = { + "name": "alexanderzobnin-zabbix-app" + } + + module = MagicMock() + module.run_command.return_value = run_command_uninstall() + + 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') + def test_plugin_uninstall_again(self, mock_grafana_cli_bin): + mock_grafana_cli_bin.return_value = "grafana-cli plugins" + + params = { + "name": "alexanderzobnin-zabbix-app" + } + + module = MagicMock() + module.run_command.return_value = run_command_uninstall_again() + + result = grafana_plugin.get_grafana_plugin_version(module, params) + self.assertEqual(result, None) diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_team/test_grafana_team.py b/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_team/test_grafana_team.py new file mode 100644 index 00000000..c59953af --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_team/test_grafana_team.py @@ -0,0 +1,447 @@ +from __future__ import (absolute_import, division, print_function) + +from unittest import TestCase +from unittest.mock import patch, MagicMock +from ansible_collections.community.grafana.plugins.modules import grafana_team +from ansible.module_utils._text import to_bytes +from ansible.module_utils import basic +from ansible.module_utils.urls import basic_auth_header +import json + +__metaclass__ = type + + +class MockedReponse(object): + def __init__(self, data): + self.data = data + + def read(self): + return self.data + + +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 + raise AnsibleExitJson(kwargs) + + +def fail_json(*args, **kwargs): + """function to patch over fail_json; package return data into an exception""" + 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}) + basic._ANSIBLE_ARGS = to_bytes(args) + + +def unauthorized_resp(): + return (None, {"status": 401}) + + +def permission_denied_resp(): + return (None, {"status": 403}) + + +def get_version_resp(): + return {"major": 6, "minor": 0, "rev": 0} + + +def get_low_version_resp(): + return {"major": 4, "minor": 6, "rev": 0} + + +def team_exists_resp(): + server_response = json.dumps({"totalCount": 1, "teams": [{"name": "MyTestTeam", "email": "email@test.com"}]}, sort_keys=True) + return (MockedReponse(server_response), {"status": 200}) + + +def team_not_found_resp(): + server_response = json.dumps({"totalCount": 0, "teams": []}) + return (MockedReponse(server_response), {"status": 200}) + + +def team_created_resp(): + server_response = json.dumps({"message": "Team created", "teamId": 2}) + return (MockedReponse(server_response), {"status": 200}) + + +def team_updated_resp(): + server_response = json.dumps({"message": "Team updated"}) + return (MockedReponse(server_response), {"status": 200}) + + +def team_deleted_resp(): + server_response = json.dumps({"message": "Team deleted"}) + return (MockedReponse(server_response), {"status": 200}) + + +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" + }]) + return (MockedReponse(server_response), {"status": 200}) + + +def team_members_no_members_resp(): + server_response = json.dumps([]) + return (MockedReponse(server_response), {"status": 200}) + + +def add_team_member_resp(): + server_response = json.dumps({"message": "Member added to Team"}) + return (MockedReponse(server_response), {"status": 200}) + + +def delete_team_member_resp(): + server_response = json.dumps({"message": "Team Member removed"}) + return (MockedReponse(server_response), {"status": 200}) + + +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.start() + self.addCleanup(self.mock_module_helper.stop) + + def test_module_setup_fails_without_params(self): + set_module_args({}) + + 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') + 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' + }) + + with self.assertRaises(AnsibleFailJson) as result: + grafana_team.main() + 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' + }) + + with self.assertRaises(AnsibleFailJson) as result: + grafana_team.main() + 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', + }) + + with self.assertRaises(AnsibleFailJson) as result: + grafana_team.main() + 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', + }) + + 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') + 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', + }) + + 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', + }) + 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', + }) + 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') + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_exists_resp() + mock_get_version.return_value = get_version_resp() + + 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', + data=None, + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_not_found_resp() + mock_get_version.return_value = get_version_resp() + + 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', + data=None, + 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') + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_created_resp() + mock_get_version.return_value = get_version_resp() + + grafana_iface = grafana_team.GrafanaTeamInterface(module) + + 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') + 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') + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_updated_resp() + mock_get_version.return_value = get_version_resp() + + 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') + 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') + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_deleted_resp() + mock_get_version.return_value = get_version_resp() + + 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', + data=None, + 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') + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_members_resp() + mock_get_version.return_value = get_version_resp() + + 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', + data=None, + 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' + }) + module = grafana_team.setup_module_object() + mock_fetch_url.return_value = team_members_no_members_resp() + mock_get_version.return_value = get_version_resp() + + 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', + data=None, + 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') + 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' + }) + 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: + 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') + 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') + 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' + }) + 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: + 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', + data=None, + headers={'Content-Type': 'application/json', 'Authorization': self.authorization}, + method='DELETE') + self.assertEquals(res, None) + + def test_diff_members_function(self): + list1 = ["foo@example.com", "bar@example.com"] + 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"]}) diff --git a/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_user/test_grafana_user.py b/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_user/test_grafana_user.py new file mode 100644 index 00000000..925c0165 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/grafana/tests/unit/modules/grafana/grafana_user/test_grafana_user.py @@ -0,0 +1,200 @@ +from __future__ import (absolute_import, division, print_function) + +from unittest import TestCase +from unittest.mock import call, patch, MagicMock +from ansible_collections.community.grafana.plugins.modules import grafana_user +from ansible.module_utils._text import to_bytes +from ansible.module_utils import basic +from ansible.module_utils.urls import basic_auth_header +import json + +__metaclass__ = type + + +class MockedReponse(object): + def __init__(self, data): + self.data = data + + def read(self): + return self.data + + +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 + raise AnsibleExitJson(kwargs) + + +def fail_json(*args, **kwargs): + """function to patch over fail_json; package return data into an exception""" + 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}) + basic._ANSIBLE_ARGS = to_bytes(args) + + +def user_deleted_resp(): + server_response = json.dumps({"message": "User deleted"}) + return (MockedReponse(server_response), {"status": 200}) + + +def user_already_exists_resp(): + server_response = json.dumps({"message": "failed to create user"}) + return (MockedReponse(server_response), {"status": 500}) + + +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) + 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.start() + self.addCleanup(self.mock_module_helper.stop) + + # create an already existing user + @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' + }) + 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') + 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') + + # create a new user + @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' + }) + module = grafana_user.setup_module_object() + + mock_fetch_url.return_value = user_created_resp() + + expected_fetch_url_calls = [ + # 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'), + + # second call to return created user + call( + module, + 'https://grafana.example.com/api/users/lookup?loginOrEmail=robin', + data=None, + 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') + 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' + }) + module = grafana_user.setup_module_object() + mock_fetch_url.return_value = user_deleted_resp() + + grafana_iface = grafana_user.GrafanaUserInterface(module) + user_id = 42 + result = grafana_iface.delete_user(user_id) + mock_fetch_url.assert_called_once_with( + module, + 'https://grafana.example.com/api/admin/users/42', + data=None, + headers={'Content-Type': 'application/json', + 'Authorization': self.authorization}, + method='DELETE') + self.assertEquals(result, {"message": "User deleted"}) |