From 975f66f2eebe9dadba04f275774d4ab83f74cf25 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 13 Apr 2024 14:04:41 +0200 Subject: Adding upstream version 7.7.0+dfsg. Signed-off-by: Daniel Baumann --- .../community/hrobot/.github/dependabot.yml | 11 + .../hrobot/.github/workflows/ansible-test.yml | 86 + .../community/hrobot/.github/workflows/docs-pr.yml | 92 + .../hrobot/.github/workflows/docs-push.yml | 52 + .../community/hrobot/.github/workflows/ee.yml | 113 ++ .../hrobot/.github/workflows/extra-tests.yml | 48 + .../hrobot/.github/workflows/import-galaxy.yml | 88 + .../community/hrobot/.github/workflows/reuse.yml | 32 + ansible_collections/community/hrobot/.reuse/dep5 | 5 + ansible_collections/community/hrobot/CHANGELOG.rst | 233 +++ .../community/hrobot/CHANGELOG.rst.license | 3 + ansible_collections/community/hrobot/COPYING | 674 +++++++ ansible_collections/community/hrobot/FILES.json | 796 +++++++++ .../community/hrobot/LICENSES/BSD-2-Clause.txt | 8 + .../community/hrobot/LICENSES/GPL-3.0-or-later.txt | 674 +++++++ ansible_collections/community/hrobot/MANIFEST.json | 37 + ansible_collections/community/hrobot/README.md | 87 + .../community/hrobot/changelogs/changelog.yaml | 212 +++ .../hrobot/changelogs/changelog.yaml.license | 3 + .../community/hrobot/changelogs/config.yaml | 35 + .../community/hrobot/changelogs/fragments/.keep | 0 ansible_collections/community/hrobot/codecov.yml | 7 + .../community/hrobot/docs/docsite/links.yml | 27 + .../hrobot/meta/execution-environment.yml | 7 + .../community/hrobot/meta/runtime.yml | 19 + .../hrobot/plugins/doc_fragments/attributes.py | 95 + .../hrobot/plugins/doc_fragments/robot.py | 24 + .../community/hrobot/plugins/inventory/robot.py | 191 ++ .../hrobot/plugins/module_utils/failover.py | 92 + .../community/hrobot/plugins/module_utils/robot.py | 169 ++ .../community/hrobot/plugins/modules/boot.py | 444 +++++ .../hrobot/plugins/modules/failover_ip.py | 154 ++ .../hrobot/plugins/modules/failover_ip_info.py | 127 ++ .../community/hrobot/plugins/modules/firewall.py | 704 ++++++++ .../hrobot/plugins/modules/firewall_info.py | 318 ++++ .../community/hrobot/plugins/modules/reset.py | 150 ++ .../hrobot/plugins/modules/reverse_dns.py | 133 ++ .../community/hrobot/plugins/modules/server.py | 274 +++ .../hrobot/plugins/modules/server_info.py | 283 +++ .../community/hrobot/plugins/modules/ssh_key.py | 245 +++ .../hrobot/plugins/modules/ssh_key_info.py | 113 ++ .../community/hrobot/plugins/modules/v_switch.py | 504 ++++++ .../community/hrobot/tests/config.yml | 9 + .../community/hrobot/tests/ee/all.yml | 18 + .../ee/roles/smoke/library/smoke_ipaddress.py | 50 + .../hrobot/tests/ee/roles/smoke/tasks/main.yml | 29 + .../community/hrobot/tests/requirements.yml | 7 + .../hrobot/tests/sanity/extra/extra-docs.json | 10 + .../tests/sanity/extra/extra-docs.json.license | 3 + .../hrobot/tests/sanity/extra/extra-docs.py | 24 + .../hrobot/tests/sanity/extra/licenses.json | 4 + .../tests/sanity/extra/licenses.json.license | 3 + .../hrobot/tests/sanity/extra/licenses.py | 110 ++ .../hrobot/tests/sanity/extra/licenses.py.license | 3 + .../tests/sanity/extra/no-unwanted-files.json | 7 + .../sanity/extra/no-unwanted-files.json.license | 3 + .../hrobot/tests/sanity/extra/no-unwanted-files.py | 44 + .../community/hrobot/tests/sanity/ignore-2.10.txt | 8 + .../hrobot/tests/sanity/ignore-2.10.txt.license | 3 + .../community/hrobot/tests/sanity/ignore-2.11.txt | 7 + .../hrobot/tests/sanity/ignore-2.11.txt.license | 3 + .../community/hrobot/tests/sanity/ignore-2.12.txt | 7 + .../hrobot/tests/sanity/ignore-2.12.txt.license | 3 + .../community/hrobot/tests/sanity/ignore-2.13.txt | 1 + .../hrobot/tests/sanity/ignore-2.13.txt.license | 3 + .../community/hrobot/tests/sanity/ignore-2.14.txt | 1 + .../hrobot/tests/sanity/ignore-2.14.txt.license | 3 + .../community/hrobot/tests/sanity/ignore-2.15.txt | 1 + .../hrobot/tests/sanity/ignore-2.15.txt.license | 3 + .../community/hrobot/tests/sanity/ignore-2.9.txt | 3 + .../hrobot/tests/sanity/ignore-2.9.txt.license | 3 + .../tests/unit/plugins/inventory/test_robot.py | 361 ++++ .../unit/plugins/module_utils/test_failover.py | 189 ++ .../tests/unit/plugins/module_utils/test_robot.py | 207 +++ .../hrobot/tests/unit/plugins/modules/test_boot.py | 541 ++++++ .../tests/unit/plugins/modules/test_failover_ip.py | 247 +++ .../unit/plugins/modules/test_failover_ip_info.py | 74 + .../tests/unit/plugins/modules/test_firewall.py | 1865 ++++++++++++++++++++ .../unit/plugins/modules/test_firewall_info.py | 328 ++++ .../tests/unit/plugins/modules/test_reset.py | 237 +++ .../tests/unit/plugins/modules/test_reverse_dns.py | 165 ++ .../tests/unit/plugins/modules/test_server.py | 160 ++ .../tests/unit/plugins/modules/test_server_info.py | 297 ++++ .../tests/unit/plugins/modules/test_ssh_key.py | 452 +++++ .../unit/plugins/modules/test_ssh_key_info.py | 80 + .../tests/unit/plugins/modules/test_v_switch.py | 1123 ++++++++++++ .../community/hrobot/tests/unit/requirements.txt | 9 + 87 files changed, 14077 insertions(+) create mode 100644 ansible_collections/community/hrobot/.github/dependabot.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/ansible-test.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/docs-pr.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/docs-push.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/ee.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/extra-tests.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/import-galaxy.yml create mode 100644 ansible_collections/community/hrobot/.github/workflows/reuse.yml create mode 100644 ansible_collections/community/hrobot/.reuse/dep5 create mode 100644 ansible_collections/community/hrobot/CHANGELOG.rst create mode 100644 ansible_collections/community/hrobot/CHANGELOG.rst.license create mode 100644 ansible_collections/community/hrobot/COPYING create mode 100644 ansible_collections/community/hrobot/FILES.json create mode 100644 ansible_collections/community/hrobot/LICENSES/BSD-2-Clause.txt create mode 100644 ansible_collections/community/hrobot/LICENSES/GPL-3.0-or-later.txt create mode 100644 ansible_collections/community/hrobot/MANIFEST.json create mode 100644 ansible_collections/community/hrobot/README.md create mode 100644 ansible_collections/community/hrobot/changelogs/changelog.yaml create mode 100644 ansible_collections/community/hrobot/changelogs/changelog.yaml.license create mode 100644 ansible_collections/community/hrobot/changelogs/config.yaml create mode 100644 ansible_collections/community/hrobot/changelogs/fragments/.keep create mode 100644 ansible_collections/community/hrobot/codecov.yml create mode 100644 ansible_collections/community/hrobot/docs/docsite/links.yml create mode 100644 ansible_collections/community/hrobot/meta/execution-environment.yml create mode 100644 ansible_collections/community/hrobot/meta/runtime.yml create mode 100644 ansible_collections/community/hrobot/plugins/doc_fragments/attributes.py create mode 100644 ansible_collections/community/hrobot/plugins/doc_fragments/robot.py create mode 100644 ansible_collections/community/hrobot/plugins/inventory/robot.py create mode 100644 ansible_collections/community/hrobot/plugins/module_utils/failover.py create mode 100644 ansible_collections/community/hrobot/plugins/module_utils/robot.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/boot.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/failover_ip.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/failover_ip_info.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/firewall.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/firewall_info.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/reset.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/reverse_dns.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/server.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/server_info.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/ssh_key.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/ssh_key_info.py create mode 100644 ansible_collections/community/hrobot/plugins/modules/v_switch.py create mode 100644 ansible_collections/community/hrobot/tests/config.yml create mode 100644 ansible_collections/community/hrobot/tests/ee/all.yml create mode 100644 ansible_collections/community/hrobot/tests/ee/roles/smoke/library/smoke_ipaddress.py create mode 100644 ansible_collections/community/hrobot/tests/ee/roles/smoke/tasks/main.yml create mode 100644 ansible_collections/community/hrobot/tests/requirements.yml create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json.license create mode 100755 ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.py create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/licenses.json create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/licenses.json.license create mode 100755 ansible_collections/community/hrobot/tests/sanity/extra/licenses.py create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/licenses.py.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json create mode 100644 ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json.license create mode 100755 ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.py create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt.license create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt create mode 100644 ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt.license create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/inventory/test_robot.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_failover.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_robot.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_boot.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip_info.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall_info.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reset.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reverse_dns.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server_info.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key_info.py create mode 100644 ansible_collections/community/hrobot/tests/unit/plugins/modules/test_v_switch.py create mode 100644 ansible_collections/community/hrobot/tests/unit/requirements.txt (limited to 'ansible_collections/community/hrobot') diff --git a/ansible_collections/community/hrobot/.github/dependabot.yml b/ansible_collections/community/hrobot/.github/dependabot.yml new file mode 100644 index 000000000..2f4ff900d --- /dev/null +++ b/ansible_collections/community/hrobot/.github/dependabot.yml @@ -0,0 +1,11 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/ansible_collections/community/hrobot/.github/workflows/ansible-test.yml b/ansible_collections/community/hrobot/.github/workflows/ansible-test.yml new file mode 100644 index 000000000..10a685f4c --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/ansible-test.yml @@ -0,0 +1,86 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +# For the comprehensive list of the inputs supported by the ansible-community/ansible-test-gh-action GitHub Action, see +# https://github.com/marketplace/actions/ansible-test + +name: CI +on: + # Run CI against all pushes (direct commits, also merged PRs), Pull Requests + push: + branches: + - main + - stable-* + pull_request: + # Run CI once per day (at 04:45 UTC) + schedule: + - cron: '45 4 * * *' + +jobs: + sanity: + name: Sanity (Ⓐ${{ matrix.ansible }}) + strategy: + matrix: + ansible: + # It's important that Sanity is tested against all stable-X.Y branches + # Testing against `devel` may fail as new tests are added. + - stable-2.9 + - stable-2.10 + - stable-2.11 + - stable-2.12 + - stable-2.13 + - stable-2.14 + - devel + # Ansible-test on various stable branches does not yet work well with cgroups v2. + # Since ubuntu-latest now uses Ubuntu 22.04, we need to fall back to the ubuntu-20.04 + # image for these stable branches. The list of branches where this is necessary will + # shrink over time, check out https://github.com/ansible-collections/news-for-maintainers/issues/28 + # for the latest list. + runs-on: >- + ${{ contains(fromJson( + '["stable-2.9", "stable-2.10", "stable-2.11"]' + ), matrix.ansible) && 'ubuntu-20.04' || 'ubuntu-latest' }} + steps: + - name: Perform sanity testing + uses: felixfontein/ansible-test-gh-action@main + with: + ansible-core-version: ${{ matrix.ansible }} + testing-type: sanity + + units: + # Ansible-test on various stable branches does not yet work well with cgroups v2. + # Since ubuntu-latest now uses Ubuntu 22.04, we need to fall back to the ubuntu-20.04 + # image for these stable branches. The list of branches where this is necessary will + # shrink over time, check out https://github.com/ansible-collections/news-for-maintainers/issues/28 + # for the latest list. + runs-on: >- + ${{ contains(fromJson( + '["stable-2.9", "stable-2.10", "stable-2.11"]' + ), matrix.ansible) && 'ubuntu-20.04' || 'ubuntu-latest' }} + name: Units (Ⓐ${{ matrix.ansible }}) + strategy: + # As soon as the first unit test fails, cancel the others to free up the CI queue + fail-fast: true + matrix: + ansible: + - stable-2.9 + - stable-2.10 + - stable-2.11 + - stable-2.12 + - stable-2.13 + - stable-2.14 + - devel + + steps: + - name: >- + Perform unit testing against + Ansible version ${{ matrix.ansible }} + uses: felixfontein/ansible-test-gh-action@main + with: + ansible-core-version: ${{ matrix.ansible }} + testing-type: units + # NOTE: we're installing with git to work around Galaxy being a huge PITA (https://github.com/ansible/galaxy/issues/2429) + pre-test-cmd: >- + git clone --depth=1 --single-branch https://github.com/ansible-collections/community.internal_test_tools.git ../../community/internal_test_tools diff --git a/ansible_collections/community/hrobot/.github/workflows/docs-pr.yml b/ansible_collections/community/hrobot/.github/workflows/docs-pr.yml new file mode 100644 index 000000000..c5d5c24b5 --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/docs-pr.yml @@ -0,0 +1,92 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +name: Collection Docs +concurrency: + group: docs-pr-${{ github.head_ref }} + cancel-in-progress: true +on: + pull_request_target: + types: [opened, synchronize, reopened, closed] + +env: + GHP_BASE_URL: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }} + +jobs: + build-docs: + permissions: + contents: read + name: Build Ansible Docs + uses: ansible-community/github-docs-build/.github/workflows/_shared-docs-build-pr.yml@main + with: + collection-name: community.hrobot + init-lenient: false + init-fail-on-error: true + init-project: Community.Hrobot Collection + init-copyright: Community.Hrobot Contributors + init-title: Community.Hrobot Collection Documentation + init-html-short-title: Community.Hrobot Collection Docs + init-extra-html-theme-options: | + documentation_home_url=https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/branch/main/ + squash-hierarchy: true + render-file-line: '> * `$` [$](https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/pr/${{ github.event.number }}/$)' + + publish-docs-gh-pages: + # for now we won't run this on forks + if: github.repository == 'ansible-collections/community.hrobot' + permissions: + contents: write + needs: [build-docs] + name: Publish Ansible Docs + uses: ansible-community/github-docs-build/.github/workflows/_shared-docs-build-publish-gh-pages.yml@main + with: + artifact-name: ${{ needs.build-docs.outputs.artifact-name }} + action: ${{ (github.event.action == 'closed' || needs.build-docs.outputs.changed != 'true') && 'teardown' || 'publish' }} + secrets: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + comment: + permissions: + pull-requests: write + runs-on: ubuntu-latest + needs: [build-docs, publish-docs-gh-pages] + name: PR comments + steps: + - name: PR comment + uses: ansible-community/github-docs-build/actions/ansible-docs-build-comment@main + with: + body-includes: '## Docs Build' + reactions: heart + action: ${{ needs.build-docs.outputs.changed != 'true' && 'remove' || '' }} + on-closed-body: | + ## Docs Build 📝 + + This PR is closed and any previously published docsite has been unpublished. + on-merged-body: | + ## Docs Build 📝 + + Thank you for contribution!✨ + + This PR has been merged and the docs are now incorporated into `main`: + ${{ env.GHP_BASE_URL }}/branch/main + body: | + ## Docs Build 📝 + + Thank you for contribution!✨ + + The docs for **this PR** have been published here: + ${{ env.GHP_BASE_URL }}/pr/${{ github.event.number }} + + You can compare to the docs for the `main` branch here: + ${{ env.GHP_BASE_URL }}/branch/main + + The docsite for **this PR** is also available for download as an artifact from this run: + ${{ needs.build-docs.outputs.artifact-url }} + + File changes: + + ${{ needs.build-docs.outputs.diff-files-rendered }} + + ${{ needs.build-docs.outputs.diff-rendered }} diff --git a/ansible_collections/community/hrobot/.github/workflows/docs-push.yml b/ansible_collections/community/hrobot/.github/workflows/docs-push.yml new file mode 100644 index 000000000..e1db3c2eb --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/docs-push.yml @@ -0,0 +1,52 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +name: Collection Docs +concurrency: + group: docs-push-${{ github.sha }} + cancel-in-progress: true +on: + push: + branches: + - main + - stable-* + tags: + - '*' + # Run CI once per day (at 04:45 UTC) + schedule: + - cron: '45 4 * * *' + # Allow manual trigger (for newer antsibull-docs, sphinx-ansible-theme, ... versions) + workflow_dispatch: + +jobs: + build-docs: + permissions: + contents: read + name: Build Ansible Docs + uses: ansible-community/github-docs-build/.github/workflows/_shared-docs-build-push.yml@main + with: + collection-name: community.hrobot + init-lenient: false + init-fail-on-error: true + init-project: Community.Hrobot Collection + init-copyright: Community.Hrobot Contributors + init-title: Community.Hrobot Collection Documentation + init-html-short-title: Community.Hrobot Collection Docs + init-extra-html-theme-options: | + documentation_home_url=https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/branch/main/ + squash-hierarchy: true + + publish-docs-gh-pages: + # for now we won't run this on forks + if: github.repository == 'ansible-collections/community.hrobot' + permissions: + contents: write + needs: [build-docs] + name: Publish Ansible Docs + uses: ansible-community/github-docs-build/.github/workflows/_shared-docs-build-publish-gh-pages.yml@main + with: + artifact-name: ${{ needs.build-docs.outputs.artifact-name }} + secrets: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/ansible_collections/community/hrobot/.github/workflows/ee.yml b/ansible_collections/community/hrobot/.github/workflows/ee.yml new file mode 100644 index 000000000..04787e8ed --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/ee.yml @@ -0,0 +1,113 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +name: execution environment +on: + # Run CI against all pushes (direct commits, also merged PRs), Pull Requests + push: + branches: + - main + - stable-* + pull_request: + # Run CI once per day (at 04:45 UTC) + # This ensures that even if there haven't been commits that we are still testing against latest version of ansible-builder + schedule: + - cron: '45 4 * * *' + +env: + NAMESPACE: community + COLLECTION_NAME: hrobot + +jobs: + build: + name: Build and test EE (Ⓐ${{ matrix.runner_tag }}) + strategy: + matrix: + runner_tag: + - devel + - stable-2.12-latest + - stable-2.11-latest + - stable-2.9-latest + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v3 + with: + path: ansible_collections/${{ env.NAMESPACE }}/${{ env.COLLECTION_NAME }} + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install ansible-builder and ansible-navigator + run: pip install ansible-builder ansible-navigator + + - name: Verify requirements + run: ansible-builder introspect --sanitize . + + - name: Make sure galaxy.yml has version entry + run: >- + python -c + 'import yaml ; + f = open("galaxy.yml", "rb") ; + data = yaml.safe_load(f) ; + f.close() ; + data["version"] = data.get("version") or "0.0.1" ; + f = open("galaxy.yml", "wb") ; + f.write(yaml.dump(data).encode("utf-8")) ; + f.close() ; + ' + working-directory: ansible_collections/${{ env.NAMESPACE }}/${{ env.COLLECTION_NAME }} + + - name: Build collection + run: | + ansible-galaxy collection build --output-path ../../../ + working-directory: ansible_collections/${{ env.NAMESPACE }}/${{ env.COLLECTION_NAME }} + + - name: Create files for building execution environment + run: | + COLLECTION_FILENAME="$(ls "${{ env.NAMESPACE }}-${{ env.COLLECTION_NAME }}"-*.tar.gz)" + + # EE config + cat > execution-environment.yml < requirements.yml < + ansible-navigator run + --mode stdout + --pull-policy never + --set-environment-variable ANSIBLE_PRIVATE_ROLE_VARS=true + --execution-environment-image test-ee:latest + -v + all.yml + working-directory: ansible_collections/${{ env.NAMESPACE }}/${{ env.COLLECTION_NAME }}/tests/ee diff --git a/ansible_collections/community/hrobot/.github/workflows/extra-tests.yml b/ansible_collections/community/hrobot/.github/workflows/extra-tests.yml new file mode 100644 index 000000000..e00d93822 --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/extra-tests.yml @@ -0,0 +1,48 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +name: extra-tests +on: + # Run CI against all pushes (direct commits, also merged PRs), Pull Requests + push: + branches: + - main + - stable-* + pull_request: + # Run CI once per day (at 04:45 UTC) + # This ensures that even if there haven't been commits that we are still testing against latest version of ansible-test for each ansible-base version + schedule: + - cron: '45 4 * * *' +env: + NAMESPACE: community + COLLECTION_NAME: hrobot + +jobs: + extra-sanity: + name: Extra Sanity + runs-on: ubuntu-latest + steps: + + - name: Check out code + uses: actions/checkout@v3 + with: + path: ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install ansible-core + run: pip install https://github.com/ansible/ansible/archive/devel.tar.gz --disable-pip-version-check + + - name: Install collection dependencies + run: git clone --depth=1 --single-branch https://github.com/ansible-collections/community.internal_test_tools.git ./ansible_collections/community/internal_test_tools + # NOTE: we're installing with git to work around Galaxy being a huge PITA (https://github.com/ansible/galaxy/issues/2429) + # run: ansible-galaxy collection install community.internal_test_tools -p . + + - name: Run sanity tests + run: ../../community/internal_test_tools/tools/run.py --color + working-directory: ./ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} diff --git a/ansible_collections/community/hrobot/.github/workflows/import-galaxy.yml b/ansible_collections/community/hrobot/.github/workflows/import-galaxy.yml new file mode 100644 index 000000000..8a5d43177 --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/import-galaxy.yml @@ -0,0 +1,88 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +name: import-galaxy +on: + # Run CI against all pushes (direct commits, also merged PRs) to main, and all Pull Requests + push: + branches: + - main + - stable-* + pull_request: + +env: + # Adjust this to your collection + NAMESPACE: community + COLLECTION_NAME: hrobot + +jobs: + build-collection: + name: Build collection artifact + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v3 + with: + path: ./checkout + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install ansible-core + run: pip install https://github.com/ansible/ansible/archive/devel.tar.gz --disable-pip-version-check + + - name: Make sure galaxy.yml has version entry + run: >- + python -c + 'import yaml ; + f = open("galaxy.yml", "rb") ; + data = yaml.safe_load(f) ; + f.close() ; + data["version"] = data.get("version") or "0.0.1" ; + f = open("galaxy.yml", "wb") ; + f.write(yaml.dump(data).encode("utf-8")) ; + f.close() ; + ' + working-directory: ./checkout + + - name: Build collection + run: ansible-galaxy collection build + working-directory: ./checkout + + - name: Copy artifact into subdirectory + run: mkdir ./artifact && mv ./checkout/${{ env.NAMESPACE }}-${{ env.COLLECTION_NAME }}-*.tar.gz ./artifact + + - name: Upload artifact + uses: actions/upload-artifact@v3 + with: + name: ${{ env.NAMESPACE }}-${{ env.COLLECTION_NAME }}-${{ github.sha }} + path: ./artifact/ + + import-galaxy: + name: Import artifact with Galaxy importer + runs-on: ubuntu-latest + needs: + - build-collection + steps: + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install ansible-core + run: pip install https://github.com/ansible/ansible/archive/devel.tar.gz --disable-pip-version-check + + - name: Install galaxy-importer + run: pip install galaxy-importer --disable-pip-version-check + + - name: Download artifact + uses: actions/download-artifact@v3 + with: + name: ${{ env.NAMESPACE }}-${{ env.COLLECTION_NAME }}-${{ github.sha }} + + - name: Run Galaxy importer + run: python -m galaxy_importer.main ${{ env.NAMESPACE }}-${{ env.COLLECTION_NAME }}-*.tar.gz diff --git a/ansible_collections/community/hrobot/.github/workflows/reuse.yml b/ansible_collections/community/hrobot/.github/workflows/reuse.yml new file mode 100644 index 000000000..06a3fa455 --- /dev/null +++ b/ansible_collections/community/hrobot/.github/workflows/reuse.yml @@ -0,0 +1,32 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +name: Verify REUSE + +on: + push: + branches: [main] + pull_request: + branches: [main] + # Run CI once per day (at 04:45 UTC) + schedule: + - cron: '45 4 * * *' + +jobs: + check: + permissions: + contents: read + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Install dependencies + run: | + pip install reuse + + - name: Check REUSE compliance + run: | + reuse lint diff --git a/ansible_collections/community/hrobot/.reuse/dep5 b/ansible_collections/community/hrobot/.reuse/dep5 new file mode 100644 index 000000000..0c3745ebf --- /dev/null +++ b/ansible_collections/community/hrobot/.reuse/dep5 @@ -0,0 +1,5 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ + +Files: changelogs/fragments/* +Copyright: Ansible Project +License: GPL-3.0-or-later diff --git a/ansible_collections/community/hrobot/CHANGELOG.rst b/ansible_collections/community/hrobot/CHANGELOG.rst new file mode 100644 index 000000000..9b7559cbf --- /dev/null +++ b/ansible_collections/community/hrobot/CHANGELOG.rst @@ -0,0 +1,233 @@ +================================================ +Community Hetzner Robot Collection Release Notes +================================================ + +.. contents:: Topics + + +v1.8.0 +====== + +Release Summary +--------------- + +Feature release for the Hetzner firewall changes. + +Major Changes +------------- + +- firewall - Hetzner added output rules support to the firewall. This change unfortunately means that using old versions of the firewall module will always set the output rule list to empty, thus disallowing the server to send out packets (https://github.com/ansible-collections/community.hrobot/issues/75, https://github.com/ansible-collections/community.hrobot/pull/76). + +Minor Changes +------------- + +- firewall, firewall_info - add ``filter_ipv6`` and ``rules.output`` output to support the new IPv6 filtering and output rules features (https://github.com/ansible-collections/community.hrobot/issues/75, https://github.com/ansible-collections/community.hrobot/pull/76). +- firewall, firewall_info - add ``server_number`` option that can be used instead of ``server_ip`` to identify the server. Hetzner deprecated configuring the firewall by ``server_ip``, so using ``server_ip`` will stop at some point in the future (https://github.com/ansible-collections/community.hrobot/pull/77). + +v1.7.0 +====== + +Release Summary +--------------- + +Feature release. + +New Modules +----------- + +- community.hrobot.v_switch - Manage Hetzner's vSwitch + +v1.6.0 +====== + +Release Summary +--------------- + +Feature release with improved documentation. + +Minor Changes +------------- + +- Added a ``community.hrobot.robot`` module defaults group / action group. Use with ``group/community.hrobot.robot`` to provide options for all Hetzner Robot modules (https://github.com/ansible-collections/community.hrobot/pull/65). + +v1.5.2 +====== + +Release Summary +--------------- + +Maintenance release with a documentation improvement. + +Minor Changes +------------- + +- The collection repository conforms to the `REUSE specification `__ except for the changelog fragments (https://github.com/ansible-collections/community.hrobot/pull/60). + +v1.5.1 +====== + +Release Summary +--------------- + +Maintenance release with small documentation fixes. + +v1.5.0 +====== + +Release Summary +--------------- + +Maintenance release changing the way licenses are declared. No functional changes. + +Minor Changes +------------- + +- All software licenses are now in the ``LICENSES/`` directory of the collection root. Moreover, ``SPDX-License-Identifier:`` is used to declare the applicable license for every file that is not automatically generated (https://github.com/ansible-collections/community.hrobot/pull/52). + +v1.4.0 +====== + +Release Summary +--------------- + +Feature release. + +Minor Changes +------------- + +- robot inventory plugin - allow to template ``hetzner_user`` and ``hetzner_password`` (https://github.com/ansible-collections/community.hrobot/pull/49). + +v1.3.1 +====== + +Release Summary +--------------- + +Maintenance release. + +Bugfixes +-------- + +- Include ``simplified_bsd.txt`` license file for the ``robot`` and ``failover`` module utils. + +v1.3.0 +====== + +Release Summary +--------------- + +Feature and bugfix release. + +Minor Changes +------------- + +- Prepare collection for inclusion in an Execution Environment by declaring its dependencies (https://github.com/ansible-collections/community.hrobot/pull/45). + +Bugfixes +-------- + +- robot inventory plugin - do not crash if a server neither has name or primary IP set. Instead, fall back to using the server's number as the name. This can happen if unnamed rack reservations show up in your server list (https://github.com/ansible-collections/community.hrobot/issues/40, https://github.com/ansible-collections/community.hrobot/pull/47). + +v1.2.3 +====== + +Release Summary +--------------- + +Docs update release. + +v1.2.2 +====== + +Release Summary +--------------- + +Bugfix release. + +Bugfixes +-------- + +- boot - fix incorrect handling of SSH authorized keys (https://github.com/ansible-collections/community.hrobot/issues/32, https://github.com/ansible-collections/community.hrobot/pull/33). + +v1.2.1 +====== + +Release Summary +--------------- + +Maintenance release. + +Minor Changes +------------- + +- Generic module HTTP support code - fix usage of ``fetch_url`` with changes in latest ansible-core ``devel`` branch (https://github.com/ansible-collections/community.hrobot/pull/30). + +v1.2.0 +====== + +Release Summary +--------------- + +Feature release with multiple new modules. + +Minor Changes +------------- + +- Avoid internal ansible-core module_utils in favor of equivalent public API available since at least Ansible 2.9 (https://github.com/ansible-collections/community.hrobot/pull/18). +- firewall - rename option ``whitelist_hos`` to ``allowlist_hos``, keep old name as alias (https://github.com/ansible-collections/community.hrobot/pull/15). +- firewall, firewall_info - add return value ``allowlist_hos``, which contains the same value as ``whitelist_hos``. The old name ``whitelist_hos`` will be removed eventually (https://github.com/ansible-collections/community.hrobot/pull/15). +- robot module utils - add ``allow_empty_result`` parameter to ``plugin_open_url_json`` and ``fetch_url_json`` (https://github.com/ansible-collections/community.hrobot/pull/16). + +New Modules +----------- + +- community.hrobot.boot - Set boot configuration +- community.hrobot.reset - Reset a dedicated server +- community.hrobot.reverse_dns - Set or remove reverse DNS entry for IP +- community.hrobot.server - Update server information +- community.hrobot.server_info - Query information on one or more servers +- community.hrobot.ssh_key - Add, remove or update SSH key +- community.hrobot.ssh_key_info - Query information on SSH keys + +v1.1.1 +====== + +Release Summary +--------------- + +Bugfix release which reduces the number of HTTPS queries for the modules and plugins. + +Bugfixes +-------- + +- robot - force HTTP basic authentication to reduce number of HTTPS requests (https://github.com/ansible-collections/community.hrobot/pull/9). + +v1.1.0 +====== + +Release Summary +--------------- + +Release with a new inventory plugin. + +New Plugins +----------- + +Inventory +~~~~~~~~~ + +- community.hrobot.robot - Hetzner Robot inventory source + +v1.0.0 +====== + +Release Summary +--------------- + +The ``community.hrobot`` continues the work on the Hetzner Robot modules from their state in ``community.general`` 1.2.0. The changes listed here are thus relative to the modules ``community.general.hetzner_*``. + + +Breaking Changes / Porting Guide +-------------------------------- + +- firewall - now requires the `ipaddress `_ library (https://github.com/ansible-collections/community.hrobot/pull/2). diff --git a/ansible_collections/community/hrobot/CHANGELOG.rst.license b/ansible_collections/community/hrobot/CHANGELOG.rst.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/CHANGELOG.rst.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/COPYING b/ansible_collections/community/hrobot/COPYING new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/ansible_collections/community/hrobot/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/ansible_collections/community/hrobot/FILES.json b/ansible_collections/community/hrobot/FILES.json new file mode 100644 index 000000000..9576b95d8 --- /dev/null +++ b/ansible_collections/community/hrobot/FILES.json @@ -0,0 +1,796 @@ +{ + "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/workflows", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".github/workflows/ansible-test.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3a0024831cf7cc7a832b0478ae964e70e3713af496ce78904f1c820b3878507c", + "format": 1 + }, + { + "name": ".github/workflows/docs-pr.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "369ffbe6357397daf6ef60448f249fc74a2ccd0c023bb37e956f29f1107087a0", + "format": 1 + }, + { + "name": ".github/workflows/docs-push.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a37437b4ac5178def5765173891f1cc0b5562f833d0fabfe8f2dca166cdae6b4", + "format": 1 + }, + { + "name": ".github/workflows/ee.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2ec44891b83956d4816fef844f14e692e56dcd9f46b96aa55dcfa838f1290181", + "format": 1 + }, + { + "name": ".github/workflows/extra-tests.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1dddc4fefe3721d4daf55419948d65be8f05579a015b37e4229fbb1475ae3958", + "format": 1 + }, + { + "name": ".github/workflows/import-galaxy.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "220b0bab6530dfbbe6031eb7d7e569b20af32cfcb82b4bfa8d3e08e7450d9b89", + "format": 1 + }, + { + "name": ".github/workflows/reuse.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c9cc8b1cebfde4ee00c680356325d514c3ee3fa792e04cc6f5d74740fbfd61b4", + "format": 1 + }, + { + "name": ".github/dependabot.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f314f2fce46d346ef9559fdeae3a55ce6d799bab45a255092446c31e17e6874d", + "format": 1 + }, + { + "name": ".reuse", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".reuse/dep5", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9d8cb20d72d7e81aaf2e7f0ddce7eacdb3d47a890541717d7fae08a6cab7ebed", + "format": 1 + }, + { + "name": "LICENSES", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "LICENSES/GPL-3.0-or-later.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "format": 1 + }, + { + "name": "LICENSES/BSD-2-Clause.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f11e51ed1eec39ad21d458ba44d805807a301c17ee9fe39538ccc9e2b280936c", + "format": 1 + }, + { + "name": "changelogs", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "changelogs/fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "changelogs/fragments/.keep", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "changelogs/changelog.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3a3089a66ec4db61793fea71c17024c3aeef4e89818d70ea3d15a67bb2b7a1a9", + "format": 1 + }, + { + "name": "changelogs/changelog.yaml.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "changelogs/config.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "34aff4539b48607175563a83f71ec1c66ee23a2e94906915fe3ac3d89a4d68ef", + "format": 1 + }, + { + "name": "docs", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "docs/docsite", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "docs/docsite/links.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c091fe915e6c06f44c71e85e9a60715caa7e9c4c605cf1942b1554ecfcd87195", + "format": 1 + }, + { + "name": "meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "meta/execution-environment.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e91488df8f6b1f58ae12a45c18f2cb22f54ff7bea89a34a43e037bd158d0d265", + "format": 1 + }, + { + "name": "meta/runtime.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "24fe3900ecea43c7ba9092f959869454c77877400c6af713fb56f0c8465d564e", + "format": 1 + }, + { + "name": "plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/doc_fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/doc_fragments/attributes.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "da39e8bd679e17573a30e351116be4c73b78b6c2c0ea6ab5066091c7dedd7ddf", + "format": 1 + }, + { + "name": "plugins/doc_fragments/robot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "210db37052258f1c9689bf528e89e5a56a097224f52a6d843a2c8a7223d32885", + "format": 1 + }, + { + "name": "plugins/inventory", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/inventory/robot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f012c1189cc2df209e97e7dd5fa8d2502f192abeb922d7dff3d4918fe3f9ca83", + "format": 1 + }, + { + "name": "plugins/module_utils", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/module_utils/failover.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b1118974d44cf0a327ea5418037cbeeddad00bfa82ecf8dab99809214e42a129", + "format": 1 + }, + { + "name": "plugins/module_utils/robot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "dcfd4d5f6854cc2c82f9239d05c0625fdcf38b18b67b4cab8ecdf391afdb6e9e", + "format": 1 + }, + { + "name": "plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules/boot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f9f0adbcd0ce63cebde36f20795961d5c678465b764bd037900cf3c14fb540a7", + "format": 1 + }, + { + "name": "plugins/modules/failover_ip.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c22701e1a41409a583dc8d9bc8f3aee0c5caf61711d1796729c571ce6baf68bc", + "format": 1 + }, + { + "name": "plugins/modules/failover_ip_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a732a481bf7bd2d7956e2b7c73b58e4631dff3a491a38cea47aafa7fc87d70b3", + "format": 1 + }, + { + "name": "plugins/modules/firewall.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8fd6d3567e7077bd4f94c40be87e6519f5e3fe24dcb60559b3c28c133fe1d0e5", + "format": 1 + }, + { + "name": "plugins/modules/firewall_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2492c517ba7e4440913d7760f1cb47b33fe5dbc41ae6e738d08986b0eacdcbce", + "format": 1 + }, + { + "name": "plugins/modules/reset.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c326bd880106c020c0a923b9b2239e5fa7ca02f92df5a2100aef8fd8a2ea83ef", + "format": 1 + }, + { + "name": "plugins/modules/reverse_dns.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "64521ba301cc273f59deb696ab80d8529f3297d9e1dc8d2470926f45ff114c7b", + "format": 1 + }, + { + "name": "plugins/modules/server.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2448b78e391940eb6fb4a955c1d24f5e54a1f519d24dc3e60b30efb4cca916f2", + "format": 1 + }, + { + "name": "plugins/modules/server_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "08f5cb04db19a18ca3ec6fc3cfb01adf6f174dc94c4befb826f854ac0fab42d7", + "format": 1 + }, + { + "name": "plugins/modules/ssh_key.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "56d3a5ef901a3c692d6f5f3dc7a07da8a384fdfefb1d7ad7bcde0e7cae0092ae", + "format": 1 + }, + { + "name": "plugins/modules/ssh_key_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "66e9a12f1325cede6e49ec796d1e3290ff52acc18163eb5b805eb3c632fe9f81", + "format": 1 + }, + { + "name": "plugins/modules/v_switch.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0769c7829fc91038fb4b7ea446d3a5f3fafc3a3d0ec4c6085158d8ae741fe053", + "format": 1 + }, + { + "name": "tests", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/ee", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/ee/roles", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/ee/roles/smoke", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/ee/roles/smoke/library", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/ee/roles/smoke/library/smoke_ipaddress.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "dc144a99fd521db2f52980f205e08aad40ee85918c646f652b4d098451257d21", + "format": 1 + }, + { + "name": "tests/ee/roles/smoke/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/ee/roles/smoke/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e36ed086e25d120a13f9f2f8322a3154bc761513aacbd97db02904bcaeb3a1d1", + "format": 1 + }, + { + "name": "tests/ee/all.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "15124f745ece7c6afe94201049f4b301a64c1ebaef64568ec1c92f429c27e0de", + "format": 1 + }, + { + "name": "tests/sanity", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity/extra", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity/extra/extra-docs.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "63af024dcda47dda7e3cead05953d33c858853d2adc046efb47af28a6a0dc96b", + "format": 1 + }, + { + "name": "tests/sanity/extra/extra-docs.json.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/extra/extra-docs.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "00ae2a5eeec7f3a621074473ee4d0d16f763c67e1c6c1b2f4b7dcd3ca171262c", + "format": 1 + }, + { + "name": "tests/sanity/extra/licenses.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8c111eb62fa6f1b6c8a1260e9ff06c8b76ef8244428c6289969d79678093618f", + "format": 1 + }, + { + "name": "tests/sanity/extra/licenses.json.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/extra/licenses.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ff502f0707adf15a57b2fc48842fc47d154bfbd3aeadf4c0c05e96b0589c3cd4", + "format": 1 + }, + { + "name": "tests/sanity/extra/licenses.py.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "88f745b5d91e1371369c207e3392877af6f3e1de48fbaca63a728d4dcf79e03c", + "format": 1 + }, + { + "name": "tests/sanity/extra/no-unwanted-files.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a3d3b17f699b042958c7cd845a9d685bc935d83062e0bcf077f2c7200e2c0bac", + "format": 1 + }, + { + "name": "tests/sanity/extra/no-unwanted-files.json.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/extra/no-unwanted-files.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "416fdc4ddd0ad89ddad54bcacc8bf5790d3a9610f7c059167123046849f0ade9", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.10.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3b06b0034e5293bd9849a2cc6a13a8738130461e9025e8bcf24023f202bc7a28", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.10.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.11.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b40224986d594e3e69b9ad874d8a47cb0c57e493a42ffa783fb8fc86403d7e1e", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.11.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.12.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b40224986d594e3e69b9ad874d8a47cb0c57e493a42ffa783fb8fc86403d7e1e", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.12.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.13.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5264853edb2c6ff138f5496111c1e758a3a54b61e82d96c0072cb9429fb31c6e", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.13.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.14.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5264853edb2c6ff138f5496111c1e758a3a54b61e82d96c0072cb9429fb31c6e", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.14.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.15.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5264853edb2c6ff138f5496111c1e758a3a54b61e82d96c0072cb9429fb31c6e", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.15.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.9.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e144842493d4a02f039f25ad8a3c3ab0d61c7725600dc51343d9ef485dd296e8", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.9.txt.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "tests/unit", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/inventory", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/inventory/test_robot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1e7aebcb567bfb2c8dd055e5ea6ccb4cb175b4e7df992868e0ef0df2b47cbaf1", + "format": 1 + }, + { + "name": "tests/unit/plugins/module_utils", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/module_utils/test_failover.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "19106763b057e212a13597775a82f939f5b6959b317e93fe3188a64284d8797f", + "format": 1 + }, + { + "name": "tests/unit/plugins/module_utils/test_robot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c8ccfce1d5a536b29c4ce5ab7529e75dc893e4d15f66032fc7b6fa9c6af4e1f0", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_boot.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c33b5e7c7a0f2c498bbef9143ad11a78f45d72c18bdb185f541c04de5732d540", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_failover_ip.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2bba31676d5e53d5698e91d749ef177120d981a3381123aa83f71f57ffc797df", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_failover_ip_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "25622a8270e5d60fec315baea280b6ee460f0eca68e765b30db3ed6662baf168", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_firewall.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "67598f5d3ffd24067cb98d0ad62c87ec89c2d297a2739dbbb02d6fa520bf4052", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_firewall_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "518a4786e9efb69cab4b9f322c294d4b48f83e5b5c5baecc280d1e535b0c1cdf", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_reset.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "eede3ff6da07eda455efa6e758214bf24e96adae50c00517a5ffe19ae7444be6", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_reverse_dns.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bc80fbce0002daa01a475ddae7758209619a14640aa1f3eb2d820fe6006d8da8", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_server.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4ae1a41baee879baa90501bd9c3dc751221cc5c5da235bed97986e91b878544d", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_server_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "143d046a91961c621a50fbd11ca6a0aca472722d2f9d7494595f9fa09897e367", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_ssh_key.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5f3e362f4953011b4986cd14d2d858830297f0644acf508418ab54da370a661f", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_ssh_key_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "31f85dc2a5ab06303fde89dea506f593f07e2acaded3e6f85314fde651d0743b", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_v_switch.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a29ab0d51b9f72f12311a15132b29a73fc36b6fa92158a76307d6b376684c044", + "format": 1 + }, + { + "name": "tests/unit/requirements.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "82f38f73c8f632a007beb1e1688de500376d5b58c5c621a4a6a37d0688b270ca", + "format": 1 + }, + { + "name": "tests/config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "498d46cf08b5abb09880088fa8fd142315f7f775e94cdc7d41364ed20fc2cd65", + "format": 1 + }, + { + "name": "tests/requirements.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "d556aaf12dcf49749ad88e27cb3b2c9995de47c1eccde8b73de744b21ca218cc", + "format": 1 + }, + { + "name": "CHANGELOG.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "240999c1e8b017228a03f0c6fb48e35a637e650fa4fb022fdc2c35d480ba7615", + "format": 1 + }, + { + "name": "CHANGELOG.rst.license", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6eb915239f9f35407fa68fdc41ed6522f1fdcce11badbdcd6057548023179ac1", + "format": 1 + }, + { + "name": "COPYING", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "format": 1 + }, + { + "name": "README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7ffc02a04b50194cf13c5b6b54372e3e29939dafc7efe965ca5193d27f64b6ea", + "format": 1 + }, + { + "name": "codecov.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b30b898c0ffe95e9e776ddf992458dc8c2d74da0acba20453cdf393772b52a4c", + "format": 1 + } + ], + "format": 1 +} \ No newline at end of file diff --git a/ansible_collections/community/hrobot/LICENSES/BSD-2-Clause.txt b/ansible_collections/community/hrobot/LICENSES/BSD-2-Clause.txt new file mode 100644 index 000000000..6810e04e3 --- /dev/null +++ b/ansible_collections/community/hrobot/LICENSES/BSD-2-Clause.txt @@ -0,0 +1,8 @@ +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/ansible_collections/community/hrobot/LICENSES/GPL-3.0-or-later.txt b/ansible_collections/community/hrobot/LICENSES/GPL-3.0-or-later.txt new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/ansible_collections/community/hrobot/LICENSES/GPL-3.0-or-later.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/ansible_collections/community/hrobot/MANIFEST.json b/ansible_collections/community/hrobot/MANIFEST.json new file mode 100644 index 000000000..74cd2a6f1 --- /dev/null +++ b/ansible_collections/community/hrobot/MANIFEST.json @@ -0,0 +1,37 @@ +{ + "collection_info": { + "namespace": "community", + "name": "hrobot", + "version": "1.8.0", + "authors": [ + "Felix Fontein (github.com/felixfontein)" + ], + "readme": "README.md", + "tags": [ + "hetzner", + "robot", + "failover", + "failoverip", + "firewall" + ], + "description": "Modules for controlling Hetzner's Robot", + "license": [ + "GPL-3.0-or-later", + "BSD-2-Clause" + ], + "license_file": null, + "dependencies": {}, + "repository": "https://github.com/ansible-collections/community.hrobot", + "documentation": "https://docs.ansible.com/ansible/devel/collections/community/hrobot/", + "homepage": "https://github.com/ansible-collections/community.hrobot", + "issues": "https://github.com/ansible-collections/community.hrobot/issues" + }, + "file_manifest_file": { + "name": "FILES.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1d5553b60ed857cfc979fd52b7531a8135bec6bde395b4ec3e1356daa2fab3bb", + "format": 1 + }, + "format": 1 +} \ No newline at end of file diff --git a/ansible_collections/community/hrobot/README.md b/ansible_collections/community/hrobot/README.md new file mode 100644 index 000000000..2f78a9aef --- /dev/null +++ b/ansible_collections/community/hrobot/README.md @@ -0,0 +1,87 @@ + + +# Community Hetzner Robot Collection +[![CI](https://github.com/ansible-collections/community.hrobot/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/community.hrobot/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/community.hrobot)](https://codecov.io/gh/ansible-collections/community.hrobot) + +This repository contains the `community.hrobot` Ansible Collection. The collection includes modules to work with [Hetzner's Robot](https://docs.hetzner.com/robot/). + +You can find [documentation for the modules and plugins in this collection here](https://docs.ansible.com/ansible/devel/collections/community/hrobot/). + +Please note that this collection does **not** support Windows targets. + +## Tested with Ansible + +Tested with the current Ansible 2.9, ansible-base 2.10, ansible-core 2.11, ansible-core 2.12, ansible-core 2.13, and ansible-core 2.14 releases and the current development version of ansible-core. Ansible versions before 2.9.10 are not supported. + +## External requirements + +A Hetzner Robot account. + +## Collection Documentation + +Browsing the [**latest** collection documentation](https://docs.ansible.com/ansible/latest/collections/community/hrobot) will show docs for the _latest version released in the Ansible package_, not the latest version of the collection released on Galaxy. + +Browsing the [**devel** collection documentation](https://docs.ansible.com/ansible/devel/collections/community/hrobot) shows docs for the _latest version released on Galaxy_. + +We also separately publish [**latest commit** collection documentation](https://ansible-collections.github.io/community.hrobot/branch/main/) which shows docs for the _latest commit in the `main` branch_. + +If you use the Ansible package and do not update collections independently, use **latest**. If you install or update this collection directly from Galaxy, use **devel**. If you are looking to contribute, use **latest commit**. + +## Included content + +- `community.hrobot.failover_ip` module +- `community.hrobot.failover_ip_info` module +- `community.hrobot.firewall` module +- `community.hrobot.firewall_info` module +- `community.hrobot.hrobot` inventory plugin + +You can find [documentation for the modules and plugins in this collection here](https://docs.ansible.com/ansible/devel/collections/community/hrobot/). + +## Using this collection + +Before using the General community collection, you need to install the collection with the `ansible-galaxy` CLI: + + ansible-galaxy collection install community.hrobot + +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.hrobot +``` + +See [Ansible Using collections](https://docs.ansible.com/ansible/latest/user_guide/collections_using.html) for more details. + +## Contributing to this collection + +If you want to develop new content for this collection or improve what is already here, the easiest way to work on the collection is to clone it into one of the configured [`COLLECTIONS_PATH`](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#collections-paths), and work on it there. + +You can find more information in the [developer guide for collections](https://docs.ansible.com/ansible/devel/dev_guide/developing_collections.html#contributing-to-collections), and in the [Ansible Community Guide](https://docs.ansible.com/ansible/latest/community/index.html). + +## Release notes + +See the [changelog](https://github.com/ansible-collections/community.hrobot/tree/main/CHANGELOG.rst). + +## More information + +- [Ansible Collection overview](https://github.com/ansible-collections/overview) +- [Ansible User guide](https://docs.ansible.com/ansible/latest/user_guide/index.html) +- [Ansible Developer guide](https://docs.ansible.com/ansible/latest/dev_guide/index.html) +- [Ansible Collections Checklist](https://github.com/ansible-collections/overview/blob/master/collection_requirements.rst) +- [Ansible Community code of conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html) +- [The Bullhorn (the Ansible Contributor newsletter)](https://us19.campaign-archive.com/home/?u=56d874e027110e35dea0e03c1&id=d6635f5420) +- [Changes impacting Contributors](https://github.com/ansible-collections/overview/issues/45) + +## Licensing + +This collection is primarily licensed and distributed as a whole under the GNU General Public License v3.0 or later. + +See [LICENSES/GPL-3.0-or-later.txt](https://github.com/ansible-collections/community.hrobot/blob/main/COPYING) for the full text. + +Parts of the collection are licensed under the [BSD 2-Clause license](https://github.com/ansible-collections/community.hrobot/blob/main/LICENSES/BSD-2-Clause.txt). + +All files have a machine readable `SDPX-License-Identifier:` comment denoting its respective license(s) or an equivalent entry in an accompanying `.license` file. Only changelog fragments (which will not be part of a release) are covered by a blanket statement in `.reuse/dep5`. This conforms to the [REUSE specification](https://reuse.software/spec/). diff --git a/ansible_collections/community/hrobot/changelogs/changelog.yaml b/ansible_collections/community/hrobot/changelogs/changelog.yaml new file mode 100644 index 000000000..94785155c --- /dev/null +++ b/ansible_collections/community/hrobot/changelogs/changelog.yaml @@ -0,0 +1,212 @@ +ancestor: null +releases: + 1.0.0: + changes: + breaking_changes: + - firewall - now requires the `ipaddress `_ + library (https://github.com/ansible-collections/community.hrobot/pull/2). + release_summary: 'The ``community.hrobot`` continues the work on the Hetzner + Robot modules from their state in ``community.general`` 1.2.0. The changes + listed here are thus relative to the modules ``community.general.hetzner_*``. + + ' + fragments: + - 1.0.0.yml + - firewall-add-ipaddress.yml + release_date: '2020-11-23' + 1.1.0: + changes: + release_summary: Release with a new inventory plugin. + fragments: + - 1.1.0.yml + plugins: + inventory: + - description: Hetzner Robot inventory source + name: robot + namespace: null + release_date: '2020-12-11' + 1.1.1: + changes: + bugfixes: + - robot - force HTTP basic authentication to reduce number of HTTPS requests + (https://github.com/ansible-collections/community.hrobot/pull/9). + release_summary: Bugfix release which reduces the number of HTTPS queries for + the modules and plugins. + fragments: + - 1.1.1.yml + - 9-force-basic-auth.yaml + release_date: '2021-02-24' + 1.2.0: + changes: + minor_changes: + - Avoid internal ansible-core module_utils in favor of equivalent public API + available since at least Ansible 2.9 (https://github.com/ansible-collections/community.hrobot/pull/18). + - firewall - rename option ``whitelist_hos`` to ``allowlist_hos``, keep old + name as alias (https://github.com/ansible-collections/community.hrobot/pull/15). + - firewall, firewall_info - add return value ``allowlist_hos``, which contains + the same value as ``whitelist_hos``. The old name ``whitelist_hos`` will be + removed eventually (https://github.com/ansible-collections/community.hrobot/pull/15). + - robot module utils - add ``allow_empty_result`` parameter to ``plugin_open_url_json`` + and ``fetch_url_json`` (https://github.com/ansible-collections/community.hrobot/pull/16). + release_summary: Feature release with multiple new modules. + fragments: + - 1.2.0.yml + - 15-firewall-allowlist_hos.yml + - 16-module_utils-allow_empty_result.yml + - ansible-core-_text.yml + modules: + - description: Set boot configuration + name: boot + namespace: '' + - description: Reset a dedicated server + name: reset + namespace: '' + - description: Set or remove reverse DNS entry for IP + name: reverse_dns + namespace: '' + - description: Update server information + name: server + namespace: '' + - description: Query information on one or more servers + name: server_info + namespace: '' + - description: Add, remove or update SSH key + name: ssh_key + namespace: '' + - description: Query information on SSH keys + name: ssh_key_info + namespace: '' + release_date: '2021-10-20' + 1.2.1: + changes: + minor_changes: + - Generic module HTTP support code - fix usage of ``fetch_url`` with changes + in latest ansible-core ``devel`` branch (https://github.com/ansible-collections/community.hrobot/pull/30). + release_summary: Maintenance release. + fragments: + - 1.2.1.yml + - fetch_url-devel.yml + release_date: '2021-11-17' + 1.2.2: + changes: + bugfixes: + - boot - fix incorrect handling of SSH authorized keys (https://github.com/ansible-collections/community.hrobot/issues/32, + https://github.com/ansible-collections/community.hrobot/pull/33). + release_summary: Bugfix release. + fragments: + - 1.2.2.yml + - 33-fix-boot-ssh-key-setting.yaml + release_date: '2022-01-04' + 1.2.3: + changes: + release_summary: Docs update release. + fragments: + - 1.2.3.yml + release_date: '2022-03-22' + 1.3.0: + changes: + bugfixes: + - robot inventory plugin - do not crash if a server neither has name or primary + IP set. Instead, fall back to using the server's number as the name. This + can happen if unnamed rack reservations show up in your server list (https://github.com/ansible-collections/community.hrobot/issues/40, + https://github.com/ansible-collections/community.hrobot/pull/47). + minor_changes: + - Prepare collection for inclusion in an Execution Environment by declaring + its dependencies (https://github.com/ansible-collections/community.hrobot/pull/45). + release_summary: Feature and bugfix release. + fragments: + - 1.3.0.yml + - 45-ee.yml + - 47-inventory-crash.yml + release_date: '2022-04-21' + 1.3.1: + changes: + bugfixes: + - Include ``simplified_bsd.txt`` license file for the ``robot`` and ``failover`` + module utils. + release_summary: Maintenance release. + fragments: + - 1.3.1.yml + - simplified-bsd-license.yml + release_date: '2022-06-02' + 1.4.0: + changes: + minor_changes: + - robot inventory plugin - allow to template ``hetzner_user`` and ``hetzner_password`` + (https://github.com/ansible-collections/community.hrobot/pull/49). + release_summary: Feature release. + fragments: + - 1.4.0.yml + - 49-inventory-templated.yml + release_date: '2022-06-03' + 1.5.0: + changes: + minor_changes: + - All software licenses are now in the ``LICENSES/`` directory of the collection + root. Moreover, ``SPDX-License-Identifier:`` is used to declare the applicable + license for every file that is not automatically generated (https://github.com/ansible-collections/community.hrobot/pull/52). + release_summary: Maintenance release changing the way licenses are declared. + No functional changes. + fragments: + - 1.5.0.yml + - 52-licenses.yml + release_date: '2022-07-23' + 1.5.1: + changes: + release_summary: Maintenance release with small documentation fixes. + fragments: + - 1.5.1.yml + release_date: '2022-08-04' + 1.5.2: + changes: + minor_changes: + - The collection repository conforms to the `REUSE specification `__ + except for the changelog fragments (https://github.com/ansible-collections/community.hrobot/pull/60). + release_summary: Maintenance release with a documentation improvement. + fragments: + - 1.5.2.yml + - licenses.yml + release_date: '2022-08-21' + 1.6.0: + changes: + minor_changes: + - Added a ``community.hrobot.robot`` module defaults group / action group. Use + with ``group/community.hrobot.robot`` to provide options for all Hetzner Robot + modules (https://github.com/ansible-collections/community.hrobot/pull/65). + release_summary: Feature release with improved documentation. + fragments: + - 1.6.0.yml + - action_group.yml + release_date: '2022-11-06' + 1.7.0: + changes: + release_summary: Feature release. + fragments: + - 1.7.0.yml + modules: + - description: Manage Hetzner's vSwitch + name: v_switch + namespace: '' + release_date: '2023-01-27' + 1.8.0: + changes: + major_changes: + - firewall - Hetzner added output rules support to the firewall. This change + unfortunately means that using old versions of the firewall module will always + set the output rule list to empty, thus disallowing the server to send out + packets (https://github.com/ansible-collections/community.hrobot/issues/75, + https://github.com/ansible-collections/community.hrobot/pull/76). + minor_changes: + - firewall, firewall_info - add ``filter_ipv6`` and ``rules.output`` output + to support the new IPv6 filtering and output rules features (https://github.com/ansible-collections/community.hrobot/issues/75, + https://github.com/ansible-collections/community.hrobot/pull/76). + - firewall, firewall_info - add ``server_number`` option that can be used instead + of ``server_ip`` to identify the server. Hetzner deprecated configuring the + firewall by ``server_ip``, so using ``server_ip`` will stop at some point + in the future (https://github.com/ansible-collections/community.hrobot/pull/77). + release_summary: Feature release for the Hetzner firewall changes. + fragments: + - 1.8.0.yml + - 76-firewall-ipv6-output.yml + - 77-firewall-server_number.yml + release_date: '2023-03-15' diff --git a/ansible_collections/community/hrobot/changelogs/changelog.yaml.license b/ansible_collections/community/hrobot/changelogs/changelog.yaml.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/changelogs/changelog.yaml.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/changelogs/config.yaml b/ansible_collections/community/hrobot/changelogs/config.yaml new file mode 100644 index 000000000..4d6ee1a9b --- /dev/null +++ b/ansible_collections/community/hrobot/changelogs/config.yaml @@ -0,0 +1,35 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +changelog_filename_template: ../CHANGELOG.rst +changelog_filename_version_depth: 0 +changes_file: changelog.yaml +changes_format: combined +keep_fragments: false +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: Community Hetzner Robot Collection +trivial_section_name: trivial +use_fqcn: true diff --git a/ansible_collections/community/hrobot/changelogs/fragments/.keep b/ansible_collections/community/hrobot/changelogs/fragments/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/ansible_collections/community/hrobot/codecov.yml b/ansible_collections/community/hrobot/codecov.yml new file mode 100644 index 000000000..dd1f08135 --- /dev/null +++ b/ansible_collections/community/hrobot/codecov.yml @@ -0,0 +1,7 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +fixes: + - "ansible_collections/community/hrobot/::" diff --git a/ansible_collections/community/hrobot/docs/docsite/links.yml b/ansible_collections/community/hrobot/docs/docsite/links.yml new file mode 100644 index 000000000..bf5811601 --- /dev/null +++ b/ansible_collections/community/hrobot/docs/docsite/links.yml @@ -0,0 +1,27 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +edit_on_github: + repository: ansible-collections/community.hrobot + branch: main + path_prefix: '' + +extra_links: + - description: Submit a bug report + url: https://github.com/ansible-collections/community.hrobot/issues/new?assignees=&labels=&template=bug_report.md + - description: Request a feature + url: https://github.com/ansible-collections/community.hrobot/issues/new?assignees=&labels=&template=feature_request.md + +communication: + matrix_rooms: + - topic: General usage and support questions + room: '#users:ansible.im' + irc_channels: + - topic: General usage and support questions + network: Libera + channel: '#ansible' + mailing_lists: + - topic: Ansible Project List + url: https://groups.google.com/g/ansible-project diff --git a/ansible_collections/community/hrobot/meta/execution-environment.yml b/ansible_collections/community/hrobot/meta/execution-environment.yml new file mode 100644 index 000000000..f1d9b8a6f --- /dev/null +++ b/ansible_collections/community/hrobot/meta/execution-environment.yml @@ -0,0 +1,7 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +version: 1 +dependencies: {} diff --git a/ansible_collections/community/hrobot/meta/runtime.yml b/ansible_collections/community/hrobot/meta/runtime.yml new file mode 100644 index 000000000..7ea33e019 --- /dev/null +++ b/ansible_collections/community/hrobot/meta/runtime.yml @@ -0,0 +1,19 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +requires_ansible: '>=2.9.10' +action_groups: + robot: + - boot + - failover_ip + - failover_ip_info + - firewall + - firewall_info + - reset + - reverse_dns + - server + - server_info + - ssh_key + - ssh_key_info diff --git a/ansible_collections/community/hrobot/plugins/doc_fragments/attributes.py b/ansible_collections/community/hrobot/plugins/doc_fragments/attributes.py new file mode 100644 index 000000000..271d940a5 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/doc_fragments/attributes.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +class ModuleDocFragment(object): + + # Standard documentation fragment + DOCUMENTATION = r''' +options: {} +attributes: + check_mode: + description: Can run in C(check_mode) and return changed status prediction without modifying target. + diff_mode: + description: Will return details on what has changed (or possibly needs changing in C(check_mode)), when in diff mode. +''' + + # Should be used together with the standard fragment + INFO_MODULE = r''' +options: {} +attributes: + check_mode: + support: full + details: + - This action does not modify state. + diff_mode: + support: N/A + details: + - This action does not modify state. +''' + + ACTIONGROUP_ROBOT = r''' +options: {} +attributes: + action_group: + description: Use C(group/community.hrobot.robot) in C(module_defaults) to set defaults for this module. + support: full + membership: + - community.hrobot.robot +''' + + CONN = r''' +options: {} +attributes: + become: + description: Is usable alongside C(become) keywords. + connection: + description: Uses the target's configured connection information to execute code on it. + delegation: + description: Can be used in conjunction with C(delegate_to) and related keywords. +''' + + FACTS = r''' +options: {} +attributes: + facts: + description: Action returns an C(ansible_facts) dictionary that will update existing host facts. +''' + + # Should be used together with the standard fragment and the FACTS fragment + FACTS_MODULE = r''' +options: {} +attributes: + check_mode: + support: full + details: + - This action does not modify state. + diff_mode: + support: N/A + details: + - This action does not modify state. + facts: + support: full +''' + + FILES = r''' +options: {} +attributes: + safe_file_operations: + description: Uses Ansible's strict file operation functions to ensure proper permissions and avoid data corruption. +''' + + FLOW = r''' +options: {} +attributes: + action: + description: Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller. + async: + description: Supports being used with the C(async) keyword. +''' diff --git a/ansible_collections/community/hrobot/plugins/doc_fragments/robot.py b/ansible_collections/community/hrobot/plugins/doc_fragments/robot.py new file mode 100644 index 000000000..bfbf234db --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/doc_fragments/robot.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +class ModuleDocFragment(object): + + # Standard files documentation fragment + DOCUMENTATION = r''' +options: + hetzner_user: + description: The username for the Robot webservice user. + type: str + required: true + hetzner_password: + description: The password for the Robot webservice user. + type: str + required: true +''' diff --git a/ansible_collections/community/hrobot/plugins/inventory/robot.py b/ansible_collections/community/hrobot/plugins/inventory/robot.py new file mode 100644 index 000000000..1d5af4537 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/inventory/robot.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Oleksandr Stepanov +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r""" + name: robot + author: + - Oleksandr Stepanov (@alexandrst88) + short_description: Hetzner Robot inventory source + version_added: 1.1.0 + description: + - Reads servers from Hetzner Robot API. + - Uses a YAML configuration file that ends with C(robot.yml) or C(robot.yaml). + - The inventory plugin adds all values from U(https://robot.your-server.de/doc/webservice/en.html#get-server) + prepended with C(hrobot_) to the server's inventory. + For example, the variable C(hrobot_dc) contains the data center the server is located in. + extends_documentation_fragment: + - ansible.builtin.constructed + - ansible.builtin.inventory_cache + - community.hrobot.robot + notes: + - The I(hetzner_user) and I(hetzner_password) options can be templated. + options: + plugin: + description: Token that ensures this is a source file for the plugin. + required: true + choices: ["community.hrobot.robot"] + hetzner_user: + env: + - name: HROBOT_API_USER + hetzner_password: + env: + - name: HROBOT_API_PASSWORD + filters: + description: + - A dictionary of filter value pairs. + - Available filters are listed here are keys of server like C(status) or C(server_ip). + - See U(https://robot.your-server.de/doc/webservice/en.html#get-server) for all values that can be used. + type: dict + default: {} +""" + +EXAMPLES = r""" +# Fetch all hosts in Hetzner Robot +plugin: community.hrobot.robot +# Filters all servers in ready state +filters: + status: ready + +# Example showing encrypted credentials +# (This assumes that Mozilla sops was used to encrypt keys/hetzner.sops.yaml, which contains two values +# hetzner_username and hetzner_password. Needs the community.sops collection to decode that file.) +plugin: community.hrobot.robot +hetzner_user: '{{ (lookup("community.sops.sops", "keys/hetzner.sops.yaml") | from_yaml).hetzner_username }}' +hetzner_password: '{{ (lookup("community.sops.sops", "keys/hetzner.sops.yaml") | from_yaml).hetzner_password }}' + +# Example using constructed features to create groups +plugin: community.hrobot.robot +filters: + status: ready + traffic: unlimited +# keyed_groups may be used to create custom groups +strict: false +keyed_groups: + # Add e.g. groups for every data center + - key: hrobot_dc + separator: "" +# Use the IP address to connect to the host +compose: + server_name_ip: hrobot_server_name ~ '-' ~ hrobot_server_ip +""" + +from ansible.errors import AnsibleError +from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable +from ansible.template import Templar +from ansible.utils.display import Display + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + PluginException, + plugin_open_url_json, +) + +display = Display() + + +class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): + + NAME = 'community.hrobot.robot' + + def verify_file(self, path): + ''' return true/false if this is possibly a valid file for this plugin to consume ''' + valid = False + if super(InventoryModule, self).verify_file(path): + # base class verifies that file exists and is readable by current user + if path.endswith(('robot.yaml', 'robot.yml')): + valid = True + else: + display.debug("robot inventory filename must end with 'robot.yml' or 'robot.yaml'") + return valid + + def parse(self, inventory, loader, path, cache=True): + super(InventoryModule, self).parse(inventory, loader, path) + servers = {} + config = self._read_config_data(path) + self.load_cache_plugin() + cache_key = self.get_cache_key(path) + + self.templar = Templar(loader=loader) + + # cache may be True or False at this point to indicate if the inventory is being refreshed + # get the user's cache option too to see if we should save the cache if it is changing + user_cache_setting = self.get_option('cache') + + # read if the user has caching enabled and the cache isn't being refreshed + attempt_to_read_cache = user_cache_setting and cache + # update if the user has caching enabled and the cache is being refreshed; update this value to True if the cache has expired below + cache_needs_update = user_cache_setting and not cache + + # attempt to read the cache if inventory isn't being refreshed and the user has caching enabled + if attempt_to_read_cache: + try: + servers = self._cache[cache_key] + except KeyError: + # This occurs if the cache_key is not in the cache or if the cache_key expired, so the cache needs to be updated + cache_needs_update = True + elif not cache_needs_update: + servers = self.get_servers() + + if cache_needs_update: + servers = self.get_servers() + + # set the cache + self._cache[cache_key] = servers + + self.populate(servers) + + def populate(self, servers): + filters = self.get_option('filters') + strict = self.get_option('strict') + server_lists = [] + for server in servers: + s = server['server'] + server_name = s.get('server_name') or s.get('server_ip') or str(s['server_number']) + matched = self.filter(s, filters) + if not matched: + continue + + if server_name in server_lists: + display.warning('Two of your Hetzner servers use the same server name ({0}). ' + 'Please make sure that your server names are unique. ' + 'Only the first server named {0} will be included in the inventory.'.format(server_name)) + continue + + self.inventory.add_host(server_name) + server_lists.append(server_name) + if 'server_ip' in s: + self.inventory.set_variable(server_name, 'ansible_host', s['server_ip']) + for hostvar, hostval in s.items(): + self.inventory.set_variable(server_name, "{0}_{1}".format('hrobot', hostvar), hostval) + + # Composed variables + server_vars = self.inventory.get_host(server_name).get_vars() + self._set_composite_vars(self.get_option('compose'), server_vars, server_name, strict=strict) + + # Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group + self._add_host_to_composed_groups(self.get_option('groups'), server, server_name, strict=strict) + + # Create groups based on variable values and add the corresponding hosts to it + self._add_host_to_keyed_groups(self.get_option('keyed_groups'), server, server_name, strict=strict) + + def filter(self, server, filters): + matched = True + for key, value in filters.items(): + if server.get(key) != value: + matched = False + break + return matched + + def get_servers(self): + try: + return plugin_open_url_json(self, '{0}/server'.format(BASE_URL), templar=self.templar)[0] + except PluginException as e: + raise AnsibleError(e.error_message) diff --git a/ansible_collections/community/hrobot/plugins/module_utils/failover.py b/ansible_collections/community/hrobot/plugins/module_utils/failover.py new file mode 100644 index 000000000..2cdc514d7 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/module_utils/failover.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- + +# Copyright (c), Felix Fontein , 2019 +# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause) +# SPDX-License-Identifier: BSD-2-Clause + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +import json + +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + fetch_url_json, +) + + +def get_failover_record(module, ip): + ''' + Get information record of failover IP. + + See https://robot.your-server.de/doc/webservice/en.html#get-failover-failover-ip + ''' + url = "{0}/failover/{1}".format(BASE_URL, ip) + result, error = fetch_url_json(module, url) + if 'failover' not in result: + module.fail_json(msg='Cannot interpret result: {0}'.format(json.dumps(result, sort_keys=True))) + return result['failover'] + + +def get_failover(module, ip): + ''' + Get current routing target of failover IP. + + The value ``None`` represents unrouted. + + See https://robot.your-server.de/doc/webservice/en.html#get-failover-failover-ip + ''' + return get_failover_record(module, ip)['active_server_ip'] + + +def set_failover(module, ip, value, timeout=180): + ''' + Set current routing target of failover IP. + + Return a pair ``(value, changed)``. The value ``None`` for ``value`` represents unrouted. + + See https://robot.your-server.de/doc/webservice/en.html#post-failover-failover-ip + and https://robot.your-server.de/doc/webservice/en.html#delete-failover-failover-ip + ''' + url = "{0}/failover/{1}".format(BASE_URL, ip) + if value is None: + result, error = fetch_url_json( + module, + url, + method='DELETE', + timeout=timeout, + accept_errors=['FAILOVER_ALREADY_ROUTED'] + ) + else: + headers = {"Content-type": "application/x-www-form-urlencoded"} + data = dict( + active_server_ip=value, + ) + result, error = fetch_url_json( + module, + url, + method='POST', + timeout=timeout, + data=urlencode(data), + headers=headers, + accept_errors=['FAILOVER_ALREADY_ROUTED'] + ) + if error is not None: + return value, False + else: + return result['failover']['active_server_ip'], True + + +def get_failover_state(value): + ''' + Create result dictionary for failover IP's value. + + The value ``None`` represents unrouted. + ''' + return dict( + value=value, + state='routed' if value else 'unrouted' + ) diff --git a/ansible_collections/community/hrobot/plugins/module_utils/robot.py b/ansible_collections/community/hrobot/plugins/module_utils/robot.py new file mode 100644 index 000000000..034a3fc48 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/module_utils/robot.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- + +# Copyright (c), Felix Fontein , 2019 +# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause) +# SPDX-License-Identifier: BSD-2-Clause + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +from ansible.module_utils.six import PY3 +from ansible.module_utils.six.moves.urllib.error import HTTPError +from ansible.module_utils.urls import fetch_url, open_url + +import json +import time + + +ROBOT_DEFAULT_ARGUMENT_SPEC = dict( + hetzner_user=dict(type='str', required=True), + hetzner_password=dict(type='str', required=True, no_log=True), +) + +# The API endpoint is fixed. +BASE_URL = "https://robot-ws.your-server.de" + + +def get_x_www_form_urlenconded_dict_from_list(key, values): + '''Return a dictionary with keys values''' + if len(values) == 1: + return {'{key}[]'.format(key=key): values[0]} + else: + return dict(('{key}[{index}]'.format(key=key, index=i), x) for i, x in enumerate(values)) + + +class PluginException(Exception): + def __init__(self, message): + super(PluginException, self).__init__(message) + self.error_message = message + + +def plugin_open_url_json(plugin, url, method='GET', timeout=10, data=None, headers=None, + accept_errors=None, allow_empty_result=False, + allowed_empty_result_status_codes=(200, 204), templar=None): + ''' + Make general request to Hetzner's JSON robot API. + ''' + user = plugin.get_option('hetzner_user') + password = plugin.get_option('hetzner_password') + if templar is not None: + if templar.is_template(user): + user = templar.template(variable=user, disable_lookups=False) + if templar.is_template(password): + password = templar.template(variable=password, disable_lookups=False) + try: + response = open_url( + url, + url_username=user, + url_password=password, + force_basic_auth=True, + data=data, + headers=headers, + method=method, + timeout=timeout, + ) + status = response.code + content = response.read() + except HTTPError as e: + status = e.code + try: + content = e.read() + except AttributeError: + content = b'' + except Exception as e: + raise PluginException('Failed request to Hetzner Robot server endpoint {0}: {1}'.format(url, e)) + + if not content: + if allow_empty_result and status in allowed_empty_result_status_codes: + return None, None + raise PluginException('Cannot retrieve content from {0}, HTTP status code {1}'.format(url, status)) + + try: + result = json.loads(content.decode('utf-8')) + if 'error' in result: + if accept_errors: + if result['error']['code'] in accept_errors: + return result, result['error']['code'] + raise PluginException('Request failed: {0} {1} ({2})'.format( + result['error']['status'], + result['error']['code'], + result['error']['message'] + )) + return result, None + except ValueError: + raise PluginException('Cannot decode content retrieved from {0}'.format(url)) + + +def fetch_url_json(module, url, method='GET', timeout=10, data=None, headers=None, + accept_errors=None, allow_empty_result=False, + allowed_empty_result_status_codes=(200, 204)): + ''' + Make general request to Hetzner's JSON robot API. + ''' + module.params['url_username'] = module.params['hetzner_user'] + module.params['url_password'] = module.params['hetzner_password'] + module.params['force_basic_auth'] = True + resp, info = fetch_url(module, url, method=method, timeout=timeout, data=data, headers=headers) + try: + # In Python 2, reading from a closed response yields a TypeError. + # In Python 3, read() simply returns '' + if PY3 and resp.closed: + raise TypeError + content = resp.read() + except (AttributeError, TypeError): + content = info.pop('body', None) + + if not content: + if allow_empty_result and info.get('status') in allowed_empty_result_status_codes: + return None, None + module.fail_json(msg='Cannot retrieve content from {0}, HTTP status code {1}'.format(url, info.get('status'))) + + try: + result = module.from_json(content.decode('utf8')) + if 'error' in result: + if accept_errors: + if result['error']['code'] in accept_errors: + return result, result['error']['code'] + module.fail_json(msg='Request failed: {0} {1} ({2})'.format( + result['error']['status'], + result['error']['code'], + result['error']['message'] + )) + return result, None + except ValueError: + module.fail_json(msg='Cannot decode content retrieved from {0}'.format(url)) + + +class CheckDoneTimeoutException(Exception): + def __init__(self, result, error): + super(CheckDoneTimeoutException, self).__init__() + self.result = result + self.error = error + + +def fetch_url_json_with_retries(module, url, check_done_callback, check_done_delay=10, check_done_timeout=180, skip_first=False, **kwargs): + ''' + Make general request to Hetzner's JSON robot API, with retries until a condition is satisfied. + + The condition is tested by calling ``check_done_callback(result, error)``. If it is not satisfied, + it will be retried with delays ``check_done_delay`` (in seconds) until a total timeout of + ``check_done_timeout`` (in seconds) since the time the first request is started is reached. + + If ``skip_first`` is specified, will assume that a first call has already been made and will + directly start with waiting. + ''' + start_time = time.time() + if not skip_first: + result, error = fetch_url_json(module, url, **kwargs) + if check_done_callback(result, error): + return result, error + while True: + elapsed = (time.time() - start_time) + left_time = check_done_timeout - elapsed + time.sleep(max(min(check_done_delay, left_time), 0)) + result, error = fetch_url_json(module, url, **kwargs) + if check_done_callback(result, error): + return result, error + if left_time < check_done_delay: + raise CheckDoneTimeoutException(result, error) diff --git a/ansible_collections/community/hrobot/plugins/modules/boot.py b/ansible_collections/community/hrobot/plugins/modules/boot.py new file mode 100644 index 000000000..64917d9b8 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/boot.py @@ -0,0 +1,444 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: boot +short_description: Set boot configuration +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - Set the boot configuration for a dedicated server. +seealso: + - module: community.hrobot.ssh_key + description: Add, remove or update SSH key + - module: community.hrobot.ssh_key_info + description: Query information on SSH keys +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: none + +options: + server_number: + description: + - The server number of the server whose boot configuration to adjust. + type: int + required: true + regular_boot: + description: + - If this option is provided, all special boot configurations are removed and + the installed operating system will be booted up next (assuming it is bootable). + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: bool + choices: + - true + rescue: + description: + - If this option is provided, the rescue system will be activated for the next boot. + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: dict + suboptions: + os: + description: + - The operating system to use for the rescue system. Possible choices can + change over time. + - Currently, C(linux), C(linuxold), C(freebsd), C(freebsdold), C(freebsdax), + C(freebsdbetaax), C(vkvm), and C(vkvmold) seem to be available. + type: str + required: true + arch: + description: + - The architecture to use for the rescue system. + - Not all architectures are available for all operating systems. + - Defaults to C(64). + type: int + choices: + - 32 + - 64 + authorized_keys: + description: + - One or more SSH key fingerprints to equip the rescue system with. + - Only fingerprints for SSH keys deposited in the Robot API can be used. + - You can use the M(community.hrobot.ssh_key_info) module to query the + SSH keys you can use, and the M(community.hrobot.ssh_key) module to + add or update SSH keys. + type: list + elements: str + install_linux: + description: + - If this option is provided, a Linux system install will be activated for the next boot. + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: dict + suboptions: + dist: + description: + - The distribution to install. + type: str + required: true + arch: + description: + - The architecture to use for the install. + - Not all architectures are available for all distributions. + - Defaults to C(64). + type: int + choices: + - 32 + - 64 + lang: + description: + - The language to use for the operating system. + type: str + required: true + authorized_keys: + description: + - One or more SSH key fingerprints to equip the rescue system with. + - Only fingerprints for SSH keys deposited in the Robot API can be used. + - You can use the M(community.hrobot.ssh_key_info) module to query the + SSH keys you can use, and the M(community.hrobot.ssh_key) module to + add or update SSH keys. + type: list + elements: str + install_vnc: + description: + - If this option is provided, a VNC installation will be activated for the next boot. + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: dict + suboptions: + dist: + description: + - The distribution to install. + type: str + required: true + arch: + description: + - The architecture to use for the install. + - Not all architectures are available for all distributions. + - Defaults to C(64). + type: int + choices: + - 32 + - 64 + lang: + description: + - The language to use for the operating system. + type: str + required: true + install_windows: + description: + - If this option is provided, a Windows installation will be activated for the next boot. + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: dict + suboptions: + lang: + description: + - The language to use for Windows. + type: str + required: true + install_plesk: + description: + - If this option is provided, a Plesk installation will be activated for the next boot. + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: dict + suboptions: + dist: + description: + - The distribution to install. + type: str + required: true + arch: + description: + - The architecture to use for the install. + - Not all architectures are available for all distributions. + - Defaults to C(64). + type: int + choices: + - 32 + - 64 + lang: + description: + - The language to use for the operating system. + type: str + required: true + hostname: + description: + - The hostname. + type: str + required: true + install_cpanel: + description: + - If this option is provided, a cPanel installation will be activated for the next boot. + - Precisely one of I(regular_boot), I(rescue), I(install_linux), I(install_vnc), + I(install_windows), I(install_plesk), and I(install_cpanel) must be provided. + type: dict + suboptions: + dist: + description: + - The distribution to install. + type: str + required: true + arch: + description: + - The architecture to use for the install. + - Not all architectures are available for all distributions. + - Defaults to C(64). + type: int + choices: + - 32 + - 64 + lang: + description: + - The language to use for the operating system. + type: str + required: true + hostname: + description: + - The hostname. + type: str + required: true +''' + +EXAMPLES = r''' +- name: Disable all special boot configurations + community.hrobot.boot: + hetzner_user: foo + hetzner_password: bar + regular_boot: true + +- name: Enable a rescue system (64bit Linux) for the next boot + community.hrobot.boot: + hetzner_user: foo + hetzner_password: bar + rescue: + os: linux + +- name: Enable a Linux install for the next boot + community.hrobot.boot: + hetzner_user: foo + hetzner_password: bar + install_linux: + dist: CentOS 5.5 minimal + lang: en + authorized_keys: + - 56:29:99:a4:5d:ed:ac:95:c1:f5:88:82:90:5d:dd:10 + - 15:28:b0:03:95:f0:77:b3:10:56:15:6b:77:22:a5:bb +''' + +RETURN = r''' +configuration_type: + description: + - Describes the active boot configuration. + returned: success + type: str + choices: + - regular_boot + - rescue + - install_linux + - install_vnc + - install_windows + - install_plesk + - install_cpanel +password: + description: + - The root password for the active boot configuration, if available. + - For non-rescue boot configurations, it is avised to change the root password + as soon as possible. + returned: success and if a boot configuration other than C(regular_boot) is active + type: str +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +BOOT_CONFIGURATION_DATA = [ + ('rescue', 'rescue', { + 'os': ('os', 'os'), + 'arch': ('arch', 'arch'), + 'authorized_keys': ('authorized_key', 'authorized_key'), + }), + ('install_linux', 'linux', { + 'dist': ('dist', 'dist'), + 'arch': ('arch', 'arch'), + 'lang': ('lang', 'lang'), + 'authorized_keys': ('authorized_key', 'authorized_key'), + }), + ('install_vnc', 'vnc', { + 'dist': ('dist', 'dist'), + 'arch': ('arch', 'arch'), + 'lang': ('lang', 'lang'), + }), + ('install_windows', 'windows', { + 'lang': ('lang', 'lang'), + }), + ('install_plesk', 'plesk', { + 'dist': ('dist', 'dist'), + 'arch': ('arch', 'arch'), + 'lang': ('lang', 'lang'), + 'hostname': ('hostname', 'hostname'), + }), + ('install_cpanel', 'cpanel', { + 'dist': ('dist', 'dist'), + 'arch': ('arch', 'arch'), + 'lang': ('lang', 'lang'), + 'hostname': ('hostname', 'hostname'), + }), +] + + +def main(): + argument_spec = dict( + server_number=dict(type='int', required=True), + regular_boot=dict(type='bool', choices=[True]), + rescue=dict(type='dict', options=dict( + os=dict(type='str', required=True), + arch=dict(type='int', choices=[32, 64]), + authorized_keys=dict(type='list', elements='str', no_log=False), + )), + install_linux=dict(type='dict', options=dict( + dist=dict(type='str', required=True), + arch=dict(type='int', choices=[32, 64]), + lang=dict(type='str', required=True), + authorized_keys=dict(type='list', elements='str', no_log=False), + )), + install_vnc=dict(type='dict', options=dict( + dist=dict(type='str', required=True), + arch=dict(type='int', choices=[32, 64]), + lang=dict(type='str', required=True), + )), + install_windows=dict(type='dict', options=dict( + lang=dict(type='str', required=True), + )), + install_plesk=dict(type='dict', options=dict( + dist=dict(type='str', required=True), + arch=dict(type='int', choices=[32, 64]), + lang=dict(type='str', required=True), + hostname=dict(type='str', required=True), + )), + install_cpanel=dict(type='dict', options=dict( + dist=dict(type='str', required=True), + arch=dict(type='int', choices=[32, 64]), + lang=dict(type='str', required=True), + hostname=dict(type='str', required=True), + )), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + mutually_exclusive=[('regular_boot', 'rescue', 'install_linux', 'install_vnc', 'install_windows', 'install_plesk', 'install_cpanel')], + required_one_of=[('regular_boot', 'rescue', 'install_linux', 'install_vnc', 'install_windows', 'install_plesk', 'install_cpanel')], + ) + + server_number = module.params['server_number'] + changed = False + + # Retrieve current boot config + url = "{0}/boot/{1}".format(BASE_URL, server_number) + result, error = fetch_url_json(module, url, accept_errors=['SERVER_NOT_FOUND', 'BOOT_NOT_AVAILABLE']) + if error is not None: + if error == 'SERVER_NOT_FOUND': + module.fail_json(msg='This server does not exist, or you do not have access rights for it') + if error == 'BOOT_NOT_AVAILABLE': + module.fail_json(msg='There is no boot configuration available for this server') + raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover + + # Deactivate current boot configurations that are not requested + for option_name, other_name, dummy in BOOT_CONFIGURATION_DATA: + if (result['boot'].get(other_name) or {}).get('active') and not module.params[option_name]: + changed = True + if not module.check_mode: + url = "{0}/boot/{1}/{2}".format(BASE_URL, server_number, other_name) + fetch_url_json(module, url, method='DELETE', allow_empty_result=True) + + # Enable/compare boot configuration + return_values = { + 'configuration_type': 'regular_boot', + 'password': None, + } + for option_name, other_name, options in BOOT_CONFIGURATION_DATA: + if module.params[option_name]: + return_values['configuration_type'] = option_name + existing = result['boot'].get(other_name) or {} + return_values['password'] = existing.get('password') + data = {} + for option_key, (result_key, data_key) in options.items(): + option = module.params[option_name][option_key] + if option is None or option == []: + continue + data[data_key] = option + if existing.get('active'): + # Idempotence check + needs_change = False + for option_key, (result_key, data_key) in options.items(): + should = module.params[option_name][option_key] + if should is None: + continue + # unfold the return object for the idempotence check to work correctly + has = existing.get(data_key) + if has and option_key == 'authorized_keys': + has = [x['key']['fingerprint'] for x in has] + if isinstance(has, list): + has = sorted(has) + if not isinstance(should, list): + should = [should] + should = sorted(should) + if should != has: + needs_change = True + else: + needs_change = True + + if needs_change: + changed = True + if not module.check_mode: + url = "{0}/boot/{1}/{2}".format(BASE_URL, server_number, other_name) + if existing.get('active'): + # Deactivate existing boot configuration + fetch_url_json(module, url, method='DELETE', allow_empty_result=True) + # Enable new boot configuration + headers = {"Content-type": "application/x-www-form-urlencoded"} + result, dummy = fetch_url_json( + module, + url, + data=urlencode(data, True), + headers=headers, + method='POST', + ) + return_values['password'] = (result.get(other_name) or {}).get('password') + else: + return_values['password'] = None + + module.exit_json(changed=changed, **return_values) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/failover_ip.py b/ansible_collections/community/hrobot/plugins/modules/failover_ip.py new file mode 100644 index 000000000..da2da356a --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/failover_ip.py @@ -0,0 +1,154 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: failover_ip +short_description: Manage Hetzner's failover IPs +author: + - Felix Fontein (@felixfontein) +description: + - Manage Hetzner's failover IPs. +seealso: + - name: Failover IP documentation + description: Hetzner's documentation on failover IPs. + link: https://docs.hetzner.com/robot/dedicated-server/ip/failover/ + - module: community.hrobot.failover_ip_info + description: Retrieve information on failover IPs. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: full + +options: + failover_ip: + description: The failover IP address. + type: str + required: true + state: + description: + - Defines whether the IP will be routed or not. + - If set to C(routed), I(value) must be specified. + type: str + choices: + - routed + - unrouted + default: routed + value: + description: + - The new value for the failover IP address. + - Required when setting I(state) to C(routed). + type: str + timeout: + description: + - Timeout to use when routing or unrouting the failover IP. + - Note that the API call returns when the failover IP has been + successfully routed to the new address, respectively successfully + unrouted. + type: int + default: 180 +''' + +EXAMPLES = r''' +- name: Set value of failover IP 1.2.3.4 to 5.6.7.8 + community.hrobot.failover_ip: + hetzner_user: foo + hetzner_password: bar + failover_ip: 1.2.3.4 + value: 5.6.7.8 + +- name: Set value of failover IP 1.2.3.4 to unrouted + community.hrobot.failover_ip: + hetzner_user: foo + hetzner_password: bar + failover_ip: 1.2.3.4 + state: unrouted +''' + +RETURN = r''' +value: + description: + - The value of the failover IP. + - Will be C(none) if the IP is unrouted. + returned: success + type: str +state: + description: + - Will be C(routed) or C(unrouted). + returned: success + type: str +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + ROBOT_DEFAULT_ARGUMENT_SPEC, +) +from ansible_collections.community.hrobot.plugins.module_utils.failover import ( + get_failover, + set_failover, + get_failover_state, +) + + +def main(): + argument_spec = dict( + failover_ip=dict(type='str', required=True), + state=dict(type='str', default='routed', choices=['routed', 'unrouted']), + value=dict(type='str'), + timeout=dict(type='int', default=180), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + required_if=( + ('state', 'routed', ['value']), + ), + ) + + failover_ip = module.params['failover_ip'] + value = get_failover(module, failover_ip) + changed = False + before = get_failover_state(value) + + if module.params['state'] == 'routed': + new_value = module.params['value'] + else: + new_value = None + + if value != new_value: + if module.check_mode: + value = new_value + changed = True + else: + value, changed = set_failover(module, failover_ip, new_value, timeout=module.params['timeout']) + + after = get_failover_state(value) + module.exit_json( + changed=changed, + diff=dict( + before=before, + after=after, + ), + **after + ) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/failover_ip_info.py b/ansible_collections/community/hrobot/plugins/modules/failover_ip_info.py new file mode 100644 index 000000000..b656b0499 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/failover_ip_info.py @@ -0,0 +1,127 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: failover_ip_info +short_description: Retrieve information on Hetzner's failover IPs +author: + - Felix Fontein (@felixfontein) +description: + - Retrieve information on Hetzner's failover IPs. +seealso: + - name: Failover IP documentation + description: Hetzner's documentation on failover IPs. + link: https://docs.hetzner.com/robot/dedicated-server/ip/failover/ + - module: community.hrobot.failover_ip + description: Manage failover IPs. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + - community.hrobot.attributes.info_module + +attributes: + action_group: + version_added: 1.6.0 + +options: + failover_ip: + description: The failover IP address. + type: str + required: true +''' + +EXAMPLES = r''' +- name: Get value of failover IP 1.2.3.4 + community.hrobot.failover_ip_info: + hetzner_user: foo + hetzner_password: bar + failover_ip: 1.2.3.4 + value: 5.6.7.8 + register: result + +- name: Print value of failover IP 1.2.3.4 in case it is routed + ansible.builtin.debug: + msg: "1.2.3.4 routes to {{ result.value }}" + when: result.state == 'routed' +''' + +RETURN = r''' +value: + description: + - The value of the failover IP. + - Will be C(none) if the IP is unrouted. + returned: success + type: str +state: + description: + - Will be C(routed) or C(unrouted). + returned: success + type: str +failover_ip: + description: + - The failover IP. + returned: success + type: str + sample: '1.2.3.4' +failover_netmask: + description: + - The netmask for the failover IP. + returned: success + type: str + sample: '255.255.255.255' +server_ip: + description: + - The main IP of the server this failover IP is associated to. + - This is I(not) the server the failover IP is routed to. + returned: success + type: str +server_number: + description: + - The number of the server this failover IP is associated to. + - This is I(not) the server the failover IP is routed to. + returned: success + type: int +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + ROBOT_DEFAULT_ARGUMENT_SPEC, +) +from ansible_collections.community.hrobot.plugins.module_utils.failover import ( + get_failover_record, + get_failover_state, +) + + +def main(): + argument_spec = dict( + failover_ip=dict(type='str', required=True), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + failover = get_failover_record(module, module.params['failover_ip']) + result = get_failover_state(failover['active_server_ip']) + result['failover_ip'] = failover['ip'] + result['failover_netmask'] = failover['netmask'] + result['server_ip'] = failover['server_ip'] + result['server_number'] = failover['server_number'] + result['changed'] = False + module.exit_json(**result) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/firewall.py b/ansible_collections/community/hrobot/plugins/modules/firewall.py new file mode 100644 index 000000000..2677a1186 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/firewall.py @@ -0,0 +1,704 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: firewall +short_description: Manage Hetzner's dedicated server firewall +author: + - Felix Fontein (@felixfontein) +description: + - Manage Hetzner's dedicated server firewall. + - Note that idempotency check for TCP flags simply compares strings and doesn't + try to interpret the rules. This might change in the future. +requirements: + - ipaddress +seealso: + - name: Firewall documentation + description: Hetzner's documentation on the stateless firewall for dedicated servers + link: https://docs.hetzner.com/robot/dedicated-server/firewall/ + - module: community.hrobot.firewall_info + description: Retrieve information on firewall configuration. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: full + +options: + server_ip: + description: + - The server's main IP address. + - Exactly one of I(server_ip) and I(server_number) must be specified. + - Note that Hetzner deprecated identifying the server's firewall by the server's main IP. + Using this option can thus stop working at any time in the future. Use I(server_number) instead. + type: str + server_number: + description: + - The server's number. + - Exactly one of I(server_ip) and I(server_number) must be specified. + type: int + version_added: 1.8.0 + filter_ipv6: + description: + - Whether to filter IPv6 traffic as well. + - IPv4 traffic is always filtered, IPv6 traffic filtering needs to be explicitly enabled. + type: bool + version_added: 1.8.0 + port: + description: + - Switch port of firewall. + type: str + choices: [ main, kvm ] + default: main + state: + description: + - Status of the firewall. + - Firewall is active if state is C(present), and disabled if state is C(absent). + type: str + default: present + choices: [ present, absent ] + allowlist_hos: + description: + - Whether Hetzner services have access. + type: bool + aliases: + - whitelist_hos + rules: + description: + - Firewall rules. + type: dict + suboptions: + input: + description: + - Input firewall rules. + type: list + elements: dict + suboptions: + name: + description: + - Name of the firewall rule. + type: str + ip_version: + description: + - Internet protocol version. + - Leave away to filter both protocols. Note that in that case, none of I(dst_ip), I(src_ip), or I(protocol) can be specified. + type: str + dst_ip: + description: + - Destination IP address or subnet address. + - CIDR notation. + type: str + dst_port: + description: + - Destination port or port range. + type: str + src_ip: + description: + - Source IP address or subnet address. + - CIDR notation. + type: str + src_port: + description: + - Source port or port range. + type: str + protocol: + description: + - Protocol above IP layer. + type: str + tcp_flags: + description: + - TCP flags or logical combination of flags. + - Flags supported by Hetzner are C(syn), C(fin), C(rst), C(psh) and C(urg). + - They can be combined with C(|) (logical or) and C(&) (logical and). + - See L(the documentation,https://wiki.hetzner.de/index.php/Robot_Firewall/en#Parameter) + for more information. + type: str + action: + description: + - Action if rule matches. + required: true + type: str + choices: [ accept, discard ] + output: + description: + - Output firewall rules. + type: list + elements: dict + version_added: 1.8.0 + suboptions: + name: + description: + - Name of the firewall rule. + type: str + ip_version: + description: + - Internet protocol version. + - Leave away to filter both protocols. Note that in that case, none of I(dst_ip), I(src_ip), or I(protocol) can be specified. + type: str + dst_ip: + description: + - Destination IP address or subnet address. + - CIDR notation. + type: str + dst_port: + description: + - Destination port or port range. + type: str + src_ip: + description: + - Source IP address or subnet address. + - CIDR notation. + type: str + src_port: + description: + - Source port or port range. + type: str + protocol: + description: + - Protocol above IP layer. + type: str + tcp_flags: + description: + - TCP flags or logical combination of flags. + - Flags supported by Hetzner are C(syn), C(fin), C(rst), C(psh) and C(urg). + - They can be combined with C(|) (logical or) and C(&) (logical and). + - See L(the documentation,https://wiki.hetzner.de/index.php/Robot_Firewall/en#Parameter) + for more information. + type: str + action: + description: + - Action if rule matches. + required: true + type: str + choices: [ accept, discard ] + update_timeout: + description: + - Timeout to use when configuring the firewall. + - Note that the API call returns before the firewall has been + successfully set up. + type: int + default: 30 + wait_for_configured: + description: + - Whether to wait until the firewall has been successfully configured before + determining what to do, and before returning from the module. + - The API returns status C(in progress) when the firewall is currently + being configured. If this happens, the module will try again until + the status changes to C(active) or C(disabled). + - Please note that there is a request limit. If you have to do multiple + updates, it can be better to disable waiting, and regularly use + M(community.hrobot.firewall_info) to query status. + type: bool + default: true + wait_delay: + description: + - Delay to wait (in seconds) before checking again whether the firewall has + been configured. + type: int + default: 10 + timeout: + description: + - Timeout (in seconds) for waiting for firewall to be configured. + type: int + default: 180 +''' + +EXAMPLES = r''' +- name: Configure firewall for server with main IP 1.2.3.4 + community.hrobot.firewall: + hetzner_user: foo + hetzner_password: bar + server_ip: 1.2.3.4 + state: present + filter_ipv6: true + allowlist_hos: true + rules: + input: + - name: Allow ICMP protocol, so you can ping your server + ip_version: ipv4 + protocol: icmp + action: accept + # Note that it is not possible to disable ICMP for IPv6 + # (https://robot.hetzner.com/doc/webservice/en.html#post-firewall-server-id) + - name: Allow responses to incoming TCP connections + protocol: tcp + dst_port: '32768-65535' + tcp_flags: ack + action: accept + - name: Allow everything to ports 20-23 from 4.3.2.1/24 (IPv4 only) + ip_version: ipv4 + src_ip: 4.3.2.1/24 + dst_port: '20-23' + action: accept + - name: Allow everything to port 443 + dst_port: '443' + action: accept + - name: Drop everything else + action: discard + output: + - name: Accept everything + action: accept + register: result + +- ansible.builtin.debug: + msg: "{{ result }}" +''' + +RETURN = r''' +firewall: + description: + - The firewall configuration. + type: dict + returned: success + contains: + port: + description: + - Switch port of firewall. + - C(main) or C(kvm). + type: str + sample: main + server_ip: + description: + - Server's main IP address. + type: str + sample: 1.2.3.4 + server_number: + description: + - Hetzner's internal server number. + type: int + sample: 12345 + status: + description: + - Status of the firewall. + - C(active) or C(disabled). + - Will be C(in process) if the firewall is currently updated, and + I(wait_for_configured) is set to C(false) or I(timeout) to a too small value. + type: str + sample: active + allowlist_hos: + description: + - Whether Hetzner services have access. + type: bool + sample: true + version_added: 1.2.0 + whitelist_hos: + description: + - Whether Hetzner services have access. + - Old name of return value C(allowlist_hos), will be removed eventually. + type: bool + sample: true + rules: + description: + - Firewall rules. + type: dict + contains: + input: + description: + - Input firewall rules. + type: list + elements: dict + contains: + name: + description: + - Name of the firewall rule. + type: str + sample: Allow HTTP access to server + ip_version: + description: + - Internet protocol version. + - No value means the rule applies both to IPv4 and IPv6. + type: str + sample: ipv4 + dst_ip: + description: + - Destination IP address or subnet address. + - CIDR notation. + type: str + sample: 1.2.3.4/32 + dst_port: + description: + - Destination port or port range. + type: str + sample: "443" + src_ip: + description: + - Source IP address or subnet address. + - CIDR notation. + type: str + sample: null + src_port: + description: + - Source port or port range. + type: str + sample: null + protocol: + description: + - Protocol above IP layer. + type: str + sample: tcp + tcp_flags: + description: + - TCP flags or logical combination of flags. + type: str + sample: null + action: + description: + - Action if rule matches. + - C(accept) or C(discard). + type: str + sample: accept + choices: + - accept + - discard + output: + description: + - Output firewall rules. + type: list + elements: dict + contains: + name: + description: + - Name of the firewall rule. + type: str + sample: Allow HTTP access to server + ip_version: + description: + - Internet protocol version. + - No value means the rule applies both to IPv4 and IPv6. + type: str + sample: ~ + dst_ip: + description: + - Destination IP address or subnet address. + - CIDR notation. + type: str + sample: 1.2.3.4/32 + dst_port: + description: + - Destination port or port range. + type: str + sample: "443" + src_ip: + description: + - Source IP address or subnet address. + - CIDR notation. + type: str + sample: null + src_port: + description: + - Source port or port range. + type: str + sample: null + protocol: + description: + - Protocol above IP layer. + type: str + sample: tcp + tcp_flags: + description: + - TCP flags or logical combination of flags. + type: str + sample: null + action: + description: + - Action if rule matches. + - C(accept) or C(discard). + type: str + sample: accept + choices: + - accept + - discard +''' + +import traceback + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + ROBOT_DEFAULT_ARGUMENT_SPEC, + BASE_URL, + fetch_url_json, + fetch_url_json_with_retries, + CheckDoneTimeoutException, +) +from ansible.module_utils.six.moves.urllib.parse import urlencode +from ansible.module_utils.common.text.converters import to_native, to_text + +try: + import ipaddress + HAS_IPADDRESS = True + IPADDRESS_IMP_ERR = None +except ImportError as exc: + IPADDRESS_IMP_ERR = traceback.format_exc() + HAS_IPADDRESS = False + + +RULE_OPTION_NAMES = [ + 'name', 'ip_version', 'dst_ip', 'dst_port', 'src_ip', 'src_port', + 'protocol', 'tcp_flags', 'action', +] + +RULES = ['input', 'output'] + + +def restrict_dict(dictionary, fields): + result = dict() + for k, v in dictionary.items(): + if k in fields: + result[k] = v + return result + + +def restrict_firewall_config(config): + result = restrict_dict(config, ['port', 'status', 'filter_ipv6', 'whitelist_hos']) + result['rules'] = dict() + for ruleset in RULES: + result['rules'][ruleset] = [ + restrict_dict(rule, RULE_OPTION_NAMES) + for rule in config['rules'].get(ruleset) or [] + ] + return result + + +def update(before, after, params, name, param_name=None): + bv = before.get(name) + after[name] = bv + changed = False + pv = params[param_name or name] + if pv is not None: + changed = pv != bv + if changed: + after[name] = pv + return changed + + +def normalize_ip(ip, ip_version): + if ip is None or ip_version is None: + return ip + if '/' in ip: + ip, range = ip.split('/') + else: + ip, range = ip, '' # pylint: disable=self-assigning-variable + ip_addr = to_native(ipaddress.ip_address(to_text(ip)).compressed) + if range == '': + range = '32' if ip_version.lower() == 'ipv4' else '128' + return ip_addr + '/' + range + + +def update_rules(before, after, params, ruleset): + before_rules = before['rules'][ruleset] + after_rules = after['rules'][ruleset] + params_rules = params['rules'][ruleset] + changed = len(before_rules) != len(params_rules) + for no, rule in enumerate(params_rules): + rule['src_ip'] = normalize_ip(rule['src_ip'], rule['ip_version']) + rule['dst_ip'] = normalize_ip(rule['dst_ip'], rule['ip_version']) + if no < len(before_rules): + before_rule = before_rules[no] + before_rule['src_ip'] = normalize_ip(before_rule['src_ip'], before_rule['ip_version']) + before_rule['dst_ip'] = normalize_ip(before_rule['dst_ip'], before_rule['ip_version']) + if before_rule != rule: + changed = True + after_rules.append(rule) + return changed + + +def encode_rule(output, rulename, input): + for i, rule in enumerate(input['rules'][rulename]): + for k, v in rule.items(): + if v is not None: + output['rules[{0}][{1}][{2}]'.format(rulename, i, k)] = v + + +def create_default_rules_object(): + rules = dict() + for ruleset in RULES: + rules[ruleset] = [] + return rules + + +def fix_naming(firewall_result): + firewall_result = firewall_result.copy() + firewall_result['allowlist_hos'] = firewall_result.get('whitelist_hos', False) + return firewall_result + + +def firewall_configured(result, error): + return result['firewall']['status'] != 'in process' + + +def main(): + argument_spec = dict( + server_ip=dict(type='str'), + server_number=dict(type='int'), + port=dict(type='str', default='main', choices=['main', 'kvm']), + filter_ipv6=dict(type='bool'), + state=dict(type='str', default='present', choices=['present', 'absent']), + allowlist_hos=dict(type='bool', aliases=['whitelist_hos']), + rules=dict(type='dict', options=dict( + input=dict(type='list', elements='dict', options=dict( + name=dict(type='str'), + ip_version=dict(type='str'), + dst_ip=dict(type='str'), + dst_port=dict(type='str'), + src_ip=dict(type='str'), + src_port=dict(type='str'), + protocol=dict(type='str'), + tcp_flags=dict(type='str'), + action=dict(type='str', required=True, choices=['accept', 'discard']), + ), required_by=dict(dst_ip=['ip_version'], src_ip=['ip_version'], protocol=['ip_version'])), + output=dict(type='list', elements='dict', options=dict( + name=dict(type='str'), + ip_version=dict(type='str'), + dst_ip=dict(type='str'), + dst_port=dict(type='str'), + src_ip=dict(type='str'), + src_port=dict(type='str'), + protocol=dict(type='str'), + tcp_flags=dict(type='str'), + action=dict(type='str', required=True, choices=['accept', 'discard']), + ), required_by=dict(dst_ip=['ip_version'], src_ip=['ip_version'], protocol=['ip_version'])), + )), + update_timeout=dict(type='int', default=30), + wait_for_configured=dict(type='bool', default=True), + wait_delay=dict(type='int', default=10), + timeout=dict(type='int', default=180), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + if not HAS_IPADDRESS: + module.fail_json(msg=missing_required_lib('ipaddress'), exception=IPADDRESS_IMP_ERR) + + # Sanitize input + module.params['status'] = 'active' if (module.params['state'] == 'present') else 'disabled' + if module.params['rules'] is None: + module.params['rules'] = {} + for chain in RULES: + if module.params['rules'].get(chain) is None: + module.params['rules'][chain] = [] + + server_id = module.params['server_ip'] or module.params['server_number'] + + # https://robot.your-server.de/doc/webservice/en.html#get-firewall-server-ip + url = "{0}/firewall/{1}".format(BASE_URL, server_id) + if module.params['wait_for_configured']: + try: + result, error = fetch_url_json_with_retries( + module, + url, + check_done_callback=firewall_configured, + check_done_delay=module.params['wait_delay'], + check_done_timeout=module.params['timeout'], + ) + except CheckDoneTimeoutException as dummy: + module.fail_json(msg='Timeout while waiting for firewall to be configured.') + else: + result, error = fetch_url_json(module, url) + if not firewall_configured(result, error): + module.fail_json(msg='Firewall configuration cannot be read as it is not configured.') + + full_before = result['firewall'] + if not full_before.get('rules'): + full_before['rules'] = create_default_rules_object() + before = restrict_firewall_config(full_before) + + # Build wanted (after) state and compare + after = dict(before) + changed = False + changed |= update(before, after, module.params, 'filter_ipv6') + changed |= update(before, after, module.params, 'port') + changed |= update(before, after, module.params, 'status') + changed |= update(before, after, module.params, 'whitelist_hos', 'allowlist_hos') + after['rules'] = create_default_rules_object() + if module.params['status'] == 'active': + for ruleset in RULES: + changed |= update_rules(before, after, module.params, ruleset) + + # Update if different + construct_result = True + construct_status = None + if changed and not module.check_mode: + # https://robot.your-server.de/doc/webservice/en.html#post-firewall-server-ip + url = "{0}/firewall/{1}".format(BASE_URL, server_id) + headers = {"Content-type": "application/x-www-form-urlencoded"} + data = dict(after) + data['filter_ipv6'] = str(data['filter_ipv6']).lower() + data['whitelist_hos'] = str(data['whitelist_hos']).lower() + del data['rules'] + for ruleset in RULES: + encode_rule(data, ruleset, after) + result, error = fetch_url_json( + module, + url, + method='POST', + timeout=module.params['update_timeout'], + data=urlencode(data), + headers=headers, + ) + if module.params['wait_for_configured'] and not firewall_configured(result, error): + try: + result, error = fetch_url_json_with_retries( + module, + url, + check_done_callback=firewall_configured, + check_done_delay=module.params['wait_delay'], + check_done_timeout=module.params['timeout'], + skip_first=True, + ) + except CheckDoneTimeoutException as e: + result, error = e.result, e.error + module.warn('Timeout while waiting for firewall to be configured.') + + full_after = result['firewall'] + if not full_after.get('rules'): + full_after['rules'] = create_default_rules_object() + construct_status = full_after['status'] + if construct_status != 'in process': + # Only use result if configuration is done, so that diff will be ok + after = restrict_firewall_config(full_after) + construct_result = False + + if construct_result: + # Construct result (used for check mode, and configuration still in process) + full_after = dict(full_before) + for k, v in after.items(): + if k != 'rules': + full_after[k] = after[k] + if construct_status is not None: + # We want 'in process' here + full_after['status'] = construct_status + full_after['rules'] = dict() + for ruleset in RULES: + full_after['rules'][ruleset] = after['rules'][ruleset] + + module.exit_json( + changed=changed, + diff=dict( + before=fix_naming(before), + after=fix_naming(after), + ), + firewall=fix_naming(full_after), + ) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/firewall_info.py b/ansible_collections/community/hrobot/plugins/modules/firewall_info.py new file mode 100644 index 000000000..49f98ab64 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/firewall_info.py @@ -0,0 +1,318 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: firewall_info +short_description: Manage Hetzner's dedicated server firewall +author: + - Felix Fontein (@felixfontein) +description: + - Manage Hetzner's dedicated server firewall. +seealso: + - name: Firewall documentation + description: Hetzner's documentation on the stateless firewall for dedicated servers + link: https://docs.hetzner.com/robot/dedicated-server/firewall/ + - module: community.hrobot.firewall + description: Configure firewall. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + - community.hrobot.attributes.info_module + +attributes: + action_group: + version_added: 1.6.0 + +options: + server_ip: + description: + - The server's main IP address. + - Exactly one of I(server_ip) and I(server_number) must be specified. + - Note that Hetzner deprecated identifying the server's firewall by the server's main IP. + Using this option can thus stop working at any time in the future. Use I(server_number) instead. + type: str + server_number: + description: + - The server's number. + - Exactly one of I(server_ip) and I(server_number) must be specified. + type: int + version_added: 1.8.0 + wait_for_configured: + description: + - Whether to wait until the firewall has been successfully configured before + returning from the module. + - The API returns status C(in progress) when the firewall is currently + being configured. If this happens, the module will try again until + the status changes to C(active) or C(disabled). + - Please note that there is a request limit. If you have to do multiple + updates, it can be better to disable waiting, and regularly use + M(community.hrobot.firewall_info) to query status. + type: bool + default: true + wait_delay: + description: + - Delay to wait (in seconds) before checking again whether the firewall has + been configured. + type: int + default: 10 + timeout: + description: + - Timeout (in seconds) for waiting for firewall to be configured. + type: int + default: 180 +''' + +EXAMPLES = r''' +- name: Get firewall configuration for server with main IP 1.2.3.4 + community.hrobot.firewall_info: + hetzner_user: foo + hetzner_password: bar + server_ip: 1.2.3.4 + register: result + +- ansible.builtin.debug: + msg: "{{ result.firewall }}" +''' + +RETURN = r''' +firewall: + description: + - The firewall configuration. + type: dict + returned: success + contains: + port: + description: + - Switch port of firewall. + - C(main) or C(kvm). + type: str + sample: main + filter_ipv6: + description: + - Whether the firewall rules apply to IPv6 as well or not. + type: bool + sample: false + server_ip: + description: + - Server's main IP address. + type: str + sample: 1.2.3.4 + server_number: + description: + - Hetzner's internal server number. + type: int + sample: 12345 + status: + description: + - Status of the firewall. + - C(active) or C(disabled). + - Will be C(in process) if the firewall is currently updated, and + I(wait_for_configured) is set to C(false) or I(timeout) to a too small value. + type: str + sample: active + allowlist_hos: + description: + - Whether Hetzner services have access. + type: bool + sample: true + version_added: 1.2.0 + whitelist_hos: + description: + - Whether Hetzner services have access. + - Old name of return value C(allowlist_hos), will be removed eventually. + type: bool + sample: true + rules: + description: + - Firewall rules. + type: dict + contains: + input: + description: + - Input firewall rules. + type: list + elements: dict + contains: + name: + description: + - Name of the firewall rule. + type: str + sample: Allow HTTP access to server + ip_version: + description: + - Internet protocol version. + - No value means the rule applies both to IPv4 and IPv6. + type: str + sample: ipv4 + dst_ip: + description: + - Destination IP address or subnet address. + - CIDR notation. + type: str + sample: 1.2.3.4/32 + dst_port: + description: + - Destination port or port range. + type: str + sample: "443" + src_ip: + description: + - Source IP address or subnet address. + - CIDR notation. + type: str + sample: null + src_port: + description: + - Source port or port range. + type: str + sample: null + protocol: + description: + - Protocol above IP layer. + type: str + sample: tcp + tcp_flags: + description: + - TCP flags or logical combination of flags. + type: str + sample: null + action: + description: + - Action if rule matches. + - C(accept) or C(discard). + type: str + sample: accept + choices: + - accept + - discard + output: + description: + - Output firewall rules. + type: list + elements: dict + contains: + name: + description: + - Name of the firewall rule. + type: str + sample: Allow HTTP access to server + ip_version: + description: + - Internet protocol version. + - No value means the rule applies both to IPv4 and IPv6. + type: str + sample: ~ + dst_ip: + description: + - Destination IP address or subnet address. + - CIDR notation. + type: str + sample: 1.2.3.4/32 + dst_port: + description: + - Destination port or port range. + type: str + sample: "443" + src_ip: + description: + - Source IP address or subnet address. + - CIDR notation. + type: str + sample: null + src_port: + description: + - Source port or port range. + type: str + sample: null + protocol: + description: + - Protocol above IP layer. + type: str + sample: tcp + tcp_flags: + description: + - TCP flags or logical combination of flags. + type: str + sample: null + action: + description: + - Action if rule matches. + - C(accept) or C(discard). + type: str + sample: accept + choices: + - accept + - discard +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + ROBOT_DEFAULT_ARGUMENT_SPEC, + BASE_URL, + fetch_url_json, + fetch_url_json_with_retries, + CheckDoneTimeoutException, +) + + +def firewall_configured(result, error): + return result['firewall']['status'] != 'in process' + + +def main(): + argument_spec = dict( + server_ip=dict(type='str'), + server_number=dict(type='int'), + wait_for_configured=dict(type='bool', default=True), + wait_delay=dict(type='int', default=10), + timeout=dict(type='int', default=180), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + server_id = module.params['server_ip'] or module.params['server_number'] + + # https://robot.your-server.de/doc/webservice/en.html#get-firewall-server-ip + url = "{0}/firewall/{1}".format(BASE_URL, server_id) + if module.params['wait_for_configured']: + try: + result, error = fetch_url_json_with_retries( + module, + url, + check_done_callback=firewall_configured, + check_done_delay=module.params['wait_delay'], + check_done_timeout=module.params['timeout'], + ) + except CheckDoneTimeoutException as dummy: + module.fail_json(msg='Timeout while waiting for firewall to be configured.') + else: + result, error = fetch_url_json(module, url) + + firewall = result['firewall'] + firewall['allowlist_hos'] = firewall.get('whitelist_hos', False) + if not firewall.get('rules'): + firewall['rules'] = dict() + for ruleset in ['input']: + firewall['rules'][ruleset] = [] + + module.exit_json( + changed=False, + firewall=firewall, + ) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/reset.py b/ansible_collections/community/hrobot/plugins/modules/reset.py new file mode 100644 index 000000000..d367936e0 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/reset.py @@ -0,0 +1,150 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: reset +short_description: Reset a dedicated server +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - Reset a dedicated server with a software or hardware reset, or by requesting a manual reset. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: none + +options: + server_number: + description: + - The server number of the server to reset. + type: int + required: true + reset_type: + description: + - How to reset the server. + - C(software) is a software reset. This should be similar to pressing Ctrl+Alt+Del on the keyboard. + - C(power) is a hardware reset similar to pressing the Power button. An ACPI signal is sent, and if the + server is configured correctly, this will trigger a regular shutdown. + - C(hardware) is a hardware reset similar to pressing the Restart button. The power is cycled for the server. + - C(manual) is a manual reset. This requests a technician to manually do the shutdown while looking at the + screen output. B(Be careful) and only use this when really necessary! + - Note that not every server supports every reset method! + type: str + required: true + choices: + - software + - hardware + - power + - manual +''' + +EXAMPLES = r''' +- name: Send ACPI signal to server to request controlled shutdown + community.hrobot.reset: + hetzner_user: foo + hetzner_password: bar + failover_ip: 1.2.3.4 + state: power + +- name: Make sure that the server supports manual reset + community.hrobot.reset: + hetzner_user: foo + hetzner_password: bar + server_number: 1234 + reset_type: manual + check_mode: true + +- name: Request a manual reset (by a technican) + community.hrobot.reset: + hetzner_user: foo + hetzner_password: bar + server_number: 1234 + reset_type: manual +''' + +RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +def main(): + argument_spec = dict( + server_number=dict(type='int', required=True), + reset_type=dict(type='str', required=True, choices=['software', 'hardware', 'power', 'manual']), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + server_number = module.params['server_number'] + reset_type = { + 'software': 'sw', + 'hardware': 'hw', + 'power': 'power', + 'manual': 'man', + }[module.params['reset_type']] + + if module.check_mode: + url = "{0}/reset/{1}".format(BASE_URL, server_number) + result, error = fetch_url_json(module, url, accept_errors=['SERVER_NOT_FOUND', 'RESET_NOT_AVAILABLE']) + if not error and reset_type not in result['reset']['type']: + module.fail_json(msg='The chosen reset method is not supported for this server') + else: + headers = {"Content-type": "application/x-www-form-urlencoded"} + data = dict( + type=reset_type, + ) + url = "{0}/reset/{1}".format(BASE_URL, server_number) + result, error = fetch_url_json( + module, + url, + data=urlencode(data), + headers=headers, + method='POST', + accept_errors=['INVALID_INPUT', 'SERVER_NOT_FOUND', 'RESET_NOT_AVAILABLE', 'RESET_MANUAL_ACTIVE', 'RESET_FAILED'], + ) + if error and error == 'INVALID_INPUT': + module.fail_json(msg='The chosen reset method is not supported for this server') + if error: + if error == 'SERVER_NOT_FOUND': + module.fail_json(msg='This server does not exist, or you do not have access rights for it') + if error == 'RESET_NOT_AVAILABLE': + module.fail_json(msg='The server has no reset option available') + if error == 'RESET_MANUAL_ACTIVE': + module.fail_json(msg='A manual reset is already running') + if error == 'RESET_FAILED': + module.fail_json(msg='The reset failed due to an internal error at Hetzner') + raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover + + module.exit_json(changed=True) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/reverse_dns.py b/ansible_collections/community/hrobot/plugins/modules/reverse_dns.py new file mode 100644 index 000000000..200489217 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/reverse_dns.py @@ -0,0 +1,133 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: reverse_dns +short_description: Set or remove reverse DNS entry for IP +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - Allows to set, update or remove a reverse DNS entry for an IP address. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot +notes: + - For the main IPv4 address of a server, deleting it actually sets it to a default hostname like + C(static.X.Y.Z.W.clients.your-server.de). This substitution (delete is replaced by changing to + this value) is done automatically by the API and results in the module not being idempotent + in this case. + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: none + +options: + ip: + description: + - The IP address to set or remove a reverse DNS entry for. + type: str + required: true + state: + description: + - Whether to set or update (C(present)) or delete (C(absent)) the reverse DNS entry for I(ip). + type: str + default: present + choices: + - present + - absent + value: + description: + - The reverse DNS entry for I(ip). + - Required if I(state=present). + type: str +''' + +EXAMPLES = r''' +- name: Set reverse DNS entry for 1.2.3.4 + community.hrobot.reverse_dns: + hetzner_user: foo + hetzner_password: bar + ip: 1.2.3.4 + value: foo.example.com + +- name: Remove reverse DNS entry for 2a01:f48:111:4221::1 + community.hrobot.reverse_dns: + hetzner_user: foo + hetzner_password: bar + ip: 2a01:f48:111:4221::1 + state: absent +''' + +RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +def main(): + argument_spec = dict( + ip=dict(type='str', required=True), + state=dict(type='str', choices=['present', 'absent'], default='present'), + value=dict(type='str'), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + required_if=[('state', 'present', ['value'])], + ) + + ip = module.params['ip'] + state = module.params['state'] + value = module.params['value'] + + url = "{0}/rdns/{1}".format(BASE_URL, ip) + result, error = fetch_url_json(module, url, accept_errors=['IP_NOT_FOUND', 'RDNS_NOT_FOUND']) + if error == 'RDNS_NOT_FOUND': + current = None + elif error: + if error == 'IP_NOT_FOUND': + module.fail_json(msg='The IP address was not found') + raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover + else: + current = result['rdns']['ptr'] + + changed = False + expected = value if state == 'present' else None + + if current != expected: + changed = True + if not module.check_mode: + if expected is None: + fetch_url_json(module, url, method='DELETE', allow_empty_result=True) + else: + headers = {'Content-type': 'application/x-www-form-urlencoded'} + data = {'ptr': expected} + fetch_url_json(module, url, data=urlencode(data), headers=headers, method='POST') + + module.exit_json(changed=changed) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/server.py b/ansible_collections/community/hrobot/plugins/modules/server.py new file mode 100644 index 000000000..2a24986e3 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/server.py @@ -0,0 +1,274 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: server +short_description: Update server information +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - Allows to update server information. + - Right now the API only supports updating the server's name. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: none + +options: + server_number: + description: + - The server number of the server to update. + type: int + required: true + server_name: + description: + - The server's name. + - If this option is not provided, it will not be adjusted. + type: str +''' + +EXAMPLES = r''' +- name: Set server's name to foo.example.com + community.hrobot.server: + hetzner_user: foo + hetzner_password: bar + server_number: 123 + server_name: foo.example.com +''' + +RETURN = r''' +server: + description: + - Information on the server. + returned: success + type: dict + contains: + server_ip: + description: + - The server's main IP address. + type: str + sample: 123.123.123.123 + returned: success + server_ipv6_net: + description: + - The server's main IPv6 network address. + type: str + sample: '2a01:f48:111:4221::' + returned: success + server_number: + description: + - The server's numeric ID. + type: int + sample: 321 + returned: success + server_name: + description: + - The user-defined server's name. + type: str + sample: server1 + returned: success + product: + description: + - The server product name. + type: str + sample: EQ 8 + returned: success + dc: + description: + - The data center the server is located in. + type: str + sample: NBG1-DC1 + returned: success + traffic: + description: + - Free traffic quota. + - C(unlimited) in case of unlimited traffic. + type: str + sample: 5 TB + returned: success + status: + description: + - Server status. + type: str + choices: + - ready + - in process + sample: ready + returned: success + cancelled: + description: + - Whether the server is cancelled. + type: bool + sample: false + returned: success + paid_until: + description: + - The date until the server has been paid. + type: str + sample: "2018-08-04" + returned: success + ip: + description: + - List of assigned single IP addresses. + type: list + elements: str + sample: + - 123.123.123.123 + returned: success + subnet: + description: + - List of assigned subnets. + type: list + elements: dict + sample: + - ip: '2a01:4f8:111:4221::' + mask: 64 + contains: + ip: + description: + - The first IP in the subnet. + type: str + sample: '2a01:4f8:111:4221::' + mask: + description: + - The masks bitlength. + type: str + sample: "64" + returned: success + reset: + description: + - Whether the server can be automatically reset. + type: bool + sample: true + returned: success + rescue: + description: + - Whether the rescue system is available. + type: bool + sample: false + returned: success + vnc: + description: + - Flag of VNC installation availability. + type: bool + sample: true + returned: success + windows: + description: + - Flag of Windows installation availability. + type: bool + sample: true + returned: success + plesk: + description: + - Flag of Plesk installation availability. + type: bool + sample: true + returned: success + cpanel: + description: + - Flag of cPanel installation availability. + type: bool + sample: true + returned: success + wol: + description: + - Flag of Wake On Lan availability. + type: bool + sample: true + returned: success + hot_swap: + description: + - Flag of Hot Swap availability. + type: bool + sample: true + returned: success + linked_storagebox: + description: + - Linked Storage Box ID. + type: int + sample: 12345 + returned: success +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +def main(): + argument_spec = dict( + server_number=dict(type='int', required=True), + server_name=dict(type='str'), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + server_number = module.params['server_number'] + server_name = module.params['server_name'] + + url = "{0}/server/{1}".format(BASE_URL, server_number) + server, error = fetch_url_json(module, url, accept_errors=['SERVER_NOT_FOUND']) + if error: + module.fail_json(msg='This server does not exist, or you do not have access rights for it') + + result = { + 'changed': False, + 'server': server['server'], + } + + update = {} + if server_name is not None: + if server_name != result['server']['server_name']: + update['server_name'] = server_name + + if update: + result['changed'] = True + if module.check_mode: + result['server'].update(update) + else: + headers = {"Content-type": "application/x-www-form-urlencoded"} + url = "{0}/server/{1}".format(BASE_URL, server_number) + server, error = fetch_url_json( + module, + url, + data=urlencode(update), + headers=headers, + method='POST', + accept_errors=['INVALID_INPUT'], + ) + if error: + module.fail_json(msg='The values to update were invalid ({0})'.format(module.jsonify(update))) + result['server'] = server['server'] + + module.exit_json(**result) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/server_info.py b/ansible_collections/community/hrobot/plugins/modules/server_info.py new file mode 100644 index 000000000..b3f6da11d --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/server_info.py @@ -0,0 +1,283 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: server_info +short_description: Query information on one or more servers +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - Query information on one or more servers. +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + - community.hrobot.attributes.info_module + +attributes: + action_group: + version_added: 1.6.0 + +options: + server_number: + description: + - Limit result list to server with this number. + type: int + server_name: + description: + - Limit result list to servers of this name. + type: str + full_info: + description: + - Whether to provide full information for every server. + - Setting this to C(true) requires one REST call per server, + which is slow and reduces your rate limit. Use with care. + - When I(server_number) is specified, this option is set to C(true). + type: bool + default: false +''' + +EXAMPLES = r''' +- name: Query a list of all servers + community.hrobot.server_info: + hetzner_user: foo + hetzner_password: bar + register: result + +- name: Query a specific server + community.hrobot.server_info: + hetzner_user: foo + hetzner_password: bar + server_number: 23 + register: result + +- name: Output data on specific server + ansible.builtin.debug: + msg: "Server name: {{ result.servers[0].server_name }}" +''' + +RETURN = r''' +servers: + description: + - List of servers matching the provided options. + returned: success + type: list + elements: dict + contains: + server_ip: + description: + - The server's main IP address. + type: str + sample: 123.123.123.123 + returned: success + server_ipv6_net: + description: + - The server's main IPv6 network address. + type: str + sample: '2a01:f48:111:4221::' + returned: success + server_number: + description: + - The server's numeric ID. + type: int + sample: 321 + returned: success + server_name: + description: + - The user-defined server's name. + type: str + sample: server1 + returned: success + product: + description: + - The server product name. + type: str + sample: EQ 8 + returned: success + dc: + description: + - The data center the server is located in. + type: str + sample: NBG1-DC1 + returned: success + traffic: + description: + - Free traffic quota. + - C(unlimited) in case of unlimited traffic. + type: str + sample: 5 TB + returned: success + status: + description: + - Server status. + type: str + choices: + - ready + - in process + sample: ready + returned: success + cancelled: + description: + - Whether the server is cancelled. + type: bool + sample: false + returned: success + paid_until: + description: + - The date until the server has been paid. + type: str + sample: "2018-08-04" + returned: success + ip: + description: + - List of assigned single IP addresses. + type: list + elements: str + sample: + - 123.123.123.123 + returned: success + subnet: + description: + - List of assigned subnets. + type: list + elements: dict + sample: + - ip: '2a01:4f8:111:4221::' + mask: 64 + contains: + ip: + description: + - The first IP in the subnet. + type: str + sample: '2a01:4f8:111:4221::' + mask: + description: + - The masks bitlength. + type: str + sample: "64" + returned: success + reset: + description: + - Whether the server can be automatically reset. + type: bool + sample: true + returned: when I(full_info=true) + rescue: + description: + - Whether the rescue system is available. + type: bool + sample: false + returned: when I(full_info=true) + vnc: + description: + - Flag of VNC installation availability. + type: bool + sample: true + returned: when I(full_info=true) + windows: + description: + - Flag of Windows installation availability. + type: bool + sample: true + returned: when I(full_info=true) + plesk: + description: + - Flag of Plesk installation availability. + type: bool + sample: true + returned: when I(full_info=true) + cpanel: + description: + - Flag of cPanel installation availability. + type: bool + sample: true + returned: when I(full_info=true) + wol: + description: + - Flag of Wake On Lan availability. + type: bool + sample: true + returned: when I(full_info=true) + hot_swap: + description: + - Flag of Hot Swap availability. + type: bool + sample: true + returned: when I(full_info=true) + linked_storagebox: + description: + - Linked Storage Box ID. + type: int + sample: 12345 + returned: when I(full_info=true) +''' + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +def main(): + argument_spec = dict( + server_number=dict(type='int'), + server_name=dict(type='str'), + full_info=dict(type='bool', default=False), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + server_number = module.params['server_number'] + server_name = module.params['server_name'] + full_info = module.params['full_info'] + + servers = [] + if server_number is not None: + server_numbers = [server_number] + else: + url = "{0}/server".format(BASE_URL) + result, error = fetch_url_json(module, url, accept_errors=['SERVER_NOT_FOUND']) + server_numbers = [] + if not error: + for entry in result: + if server_name is not None: + if entry['server']['server_name'] != server_name: + continue + if full_info: + server_numbers.append(entry['server']['server_number']) + else: + servers.append(entry['server']) + + for server_number in server_numbers: + url = "{0}/server/{1}".format(BASE_URL, server_number) + result, error = fetch_url_json(module, url, accept_errors=['SERVER_NOT_FOUND']) + if not error: + if server_name is not None: + if result['server']['server_name'] != server_name: + continue + servers.append(result['server']) + + module.exit_json( + changed=False, + servers=servers, + ) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/ssh_key.py b/ansible_collections/community/hrobot/plugins/modules/ssh_key.py new file mode 100644 index 000000000..2353514b9 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/ssh_key.py @@ -0,0 +1,245 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: ssh_key +short_description: Add, remove or update SSH key +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - Add, remove or update an SSH key stored in Hetzner's Robot. +seealso: + - module: community.hrobot.ssh_key_info + description: Query information on SSH keys +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + action_group: + version_added: 1.6.0 + check_mode: + support: full + diff_mode: + support: none + +options: + state: + description: + - Whether to make sure a public SSH key is present or absent. + - C(present) makes sure that the SSH key is available, and + potentially updates names for existing SHS public keys. + - C(absent) makes sure that the SSH key is not available. + The fingerprint or public key data is used for matching the + key. + required: true + type: str + choices: + - present + - absent + name: + description: + - The public key's name. + - Required if I(state=present), and ignored if I(state=absent). + type: str + fingerprint: + description: + - The MD5 fingerprint of the public SSH key to remove. + - One of I(public_key) and I(fingerprint) are required if I(state=absent). + type: str + public_key: + description: + - The public key data in OpenSSH format. + - "Example: C(ssh-rsa AAAAB3NzaC1yc+...)" + - One of I(public_key) and I(fingerprint) are required if I(state=absent). + - Required if I(state=present). + type: str +''' + +EXAMPLES = r''' +- name: Add an SSH key + community.hrobot.ssh_key: + hetzner_user: foo + hetzner_password: bar + state: present + name: newKey + public_key: ssh-rsa AAAAB3NzaC1yc+... + +- name: Remove a SSH key by fingerprint + community.hrobot.ssh_key: + hetzner_user: foo + hetzner_password: bar + state: absent + fingerprint: cb:8b:ef:a7:fe:04:87:3f:e5:55:cd:12:e3:e8:9f:99 +''' + +RETURN = r''' +fingerprint: + description: + - The MD5 fingerprint of the key. + - This is the value used to reference the SSH public key, for example in the M(community.hrobot.boot) module. + returned: success + type: str + sample: cb:8b:ef:a7:fe:04:87:3f:e5:55:cd:12:e3:e8:9f:99 +''' + +import base64 +import binascii +import re + +from ansible.module_utils.basic import AnsibleModule, AVAILABLE_HASH_ALGORITHMS +from ansible.module_utils.common.text.converters import to_native +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +class FingerprintError(Exception): + pass + + +SPACE_RE = re.compile(' +') +FINGERPRINT_PART = re.compile('^[0-9a-f]{2}$') + + +def normalize_fingerprint(fingerprint, size=16): + if ':' in fingerprint: + fingerprint = fingerprint.split(':') + else: + fingerprint = [fingerprint[i:i + 2] for i in range(0, len(fingerprint), 2)] + if len(fingerprint) != size: + raise FingerprintError( + 'Fingerprint must consist of {0} 8-bit hex numbers: got {1} 8-bit hex numbers instead'.format(size, len(fingerprint))) + for i, part in enumerate(fingerprint): + new_part = part.lower() + if len(new_part) < 2: + new_part = '0{0}'.format(new_part) + if not FINGERPRINT_PART.match(new_part): + raise FingerprintError( + 'Fingerprint must consist of {0} 8-bit hex numbers: number {1} is invalid: "{2}"'.format(size, i + 1, part)) + fingerprint[i] = new_part + return ':'.join(fingerprint) + + +def extract_fingerprint(public_key, alg='md5', size=16): + try: + public_key = SPACE_RE.split(public_key.strip())[1] + except IndexError: + raise FingerprintError( + 'Error while extracting fingerprint from public key data: cannot split public key into at least two parts') + try: + public_key = base64.b64decode(public_key) + except (binascii.Error, TypeError) as exc: + raise FingerprintError( + 'Error while extracting fingerprint from public key data: {0}'.format(exc)) + try: + algorithm = AVAILABLE_HASH_ALGORITHMS[alg] + except KeyError: + raise FingerprintError( + 'Hash algorithm {0} is not available. Possibly running in FIPS mode.'.format(alg.upper())) + digest = algorithm() + digest.update(public_key) + return normalize_fingerprint(digest.hexdigest(), size=size) + + +def main(): + argument_spec = dict( + state=dict(type='str', required=True, choices=['present', 'absent']), + name=dict(type='str'), + fingerprint=dict(type='str'), + public_key=dict(type='str'), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + mutually_exclusive=[ + ('fingerprint', 'public_key'), + ], + required_if=[ + ('state', 'present', ['name', 'public_key']), + ('state', 'absent', ['fingerprint', 'public_key'], True), + ], + ) + + state = module.params['state'] + name = module.params['name'] + fingerprint = module.params['fingerprint'] + public_key = module.params['public_key'] + + try: + if fingerprint is not None: + fingerprint = normalize_fingerprint(fingerprint) + else: + fingerprint = extract_fingerprint(public_key) + except FingerprintError as exc: + module.fail_json(msg=to_native(exc)) + + url = "{0}/key/{1}".format(BASE_URL, fingerprint) + + # Remove key + if state == 'absent': + if module.check_mode: + dummy, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND']) + else: + dummy, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND'], method='DELETE', allow_empty_result=True) + if error == 'NOT_FOUND': + changed = False + elif error is not None: + raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover + else: + changed = True + module.exit_json(changed=changed, fingerprint=fingerprint) + + # Make sure key is present + result, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND']) + if error == 'NOT_FOUND': + changed = True + exists = False + elif error is not None: + raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover + else: + exists = True + changed = False + # The only thing we can update is the name + if result['key'].get('name') != name: + changed = True + + if changed and not module.check_mode: + data = { + 'name': name, + } + if not exists: + # Create key + data['data'] = ' '.join(SPACE_RE.split(public_key.strip())[:2]) + url = "{0}/key".format(BASE_URL) + # Update or create key + headers = {"Content-type": "application/x-www-form-urlencoded"} + result, dummy = fetch_url_json( + module, + url, + data=urlencode(data), + headers=headers, + method='POST', + ) + + module.exit_json(changed=changed, fingerprint=fingerprint) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/ssh_key_info.py b/ansible_collections/community/hrobot/plugins/modules/ssh_key_info.py new file mode 100644 index 000000000..69d4d8111 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/ssh_key_info.py @@ -0,0 +1,113 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: ssh_key_info +short_description: Query information on SSH keys +version_added: 1.2.0 +author: + - Felix Fontein (@felixfontein) +description: + - List information on all your SSH keys stored in Hetzner's Robot. +seealso: + - module: community.hrobot.ssh_key + description: Add, remove or update SSH key +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + - community.hrobot.attributes.info_module +attributes: + action_group: + version_added: 1.6.0 +''' + +EXAMPLES = r''' +- name: List all SSH keys + community.hrobot.ssh_key_info: + hetzner_user: foo + hetzner_password: bar + register: ssh_keys + +- name: Show how many keys were found + ansible.builtin.debug: + msg: "Found {{ ssh_keys.ssh_keys | length }} keys" +''' + +RETURN = r''' +ssh_keys: + description: + - The list of all SSH keys stored in Hetzner's Robot for your user. + returned: success + type: list + elements: dict + contains: + name: + description: + - The key's name shown in the UI. + type: str + sample: key1 + fingerprint: + description: + - The key's MD5 fingerprint. + type: str + sample: 56:29:99:a4:5d:ed:ac:95:c1:f5:88:82:90:5d:dd:10 + type: + description: + - The key's algorithm type. + type: str + sample: ECDSA + size: + description: + - The key's size in bits. + type: int + sample: 521 + data: + description: + - The key data in OpenSSH's format. + type: str + sample: ecdsa-sha2-nistp521 AAAAE2VjZHNh ... +''' + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + fetch_url_json, +) + + +def main(): + argument_spec = dict() + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + url = "{0}/key".format(BASE_URL) + result, error = fetch_url_json(module, url, accept_errors=['NOT_FOUND']) + if error == 'NOT_FOUND': + result = [] + elif error is not None: + raise AssertionError('Unexpected error {0}'.format(error)) # pragma: no cover + + keys = [] + for key in result: + keys.append(key['key']) + + module.exit_json(changed=False, ssh_keys=keys) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/plugins/modules/v_switch.py b/ansible_collections/community/hrobot/plugins/modules/v_switch.py new file mode 100644 index 000000000..6035392a4 --- /dev/null +++ b/ansible_collections/community/hrobot/plugins/modules/v_switch.py @@ -0,0 +1,504 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2022 Alexander Gil Casas +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: v_switch +short_description: Manage Hetzner's vSwitch +version_added: 1.7.0 +author: + - Alexander Gil Casas (@pando85) +description: + - Manage Hetzner's vSwitch. +seealso: + - name: vSwitch documentation + description: Hetzner's documentation on vSwitch for connecting dedicated servers. + link: https://docs.hetzner.com/robot/dedicated-server/network/vswitch +extends_documentation_fragment: + - community.hrobot.robot + - community.hrobot.attributes + - community.hrobot.attributes.actiongroup_robot + +attributes: + check_mode: + support: full + diff_mode: + support: none + +options: + vlan: + description: + - The vSwitch's VLAN ID. + - Range can be from 4000 to 4091. + - In order to identify a vSwitch both name and VLAN must match. If not, a new vSwitch will be created. + type: int + required: true + name: + description: + - The vSwitch's name. + - In order to identify a vSwitch both name and VLAN must match. If not, a new vSwitch will be created. + type: str + required: true + state: + description: + - State of the vSwitch. + - vSwitch is created if state is C(present), and deleted if state is C(absent). + - C(absent) just cancels the vSwitch at the end of the current day. + - When cancelling, you have to specify I(servers=[]) if you want to actively remove the servers in the vSwitch. + type: str + default: present + choices: [ present, absent ] + servers: + description: + - List of server identifiers (server's numeric ID or server's main IPv4 or IPv6). + - If servers is not specified, servers are not going to be deleted. + type: list + elements: str + wait: + description: + - Whether to wait until the vSwitch has been successfully configured before + determining what to do, and before returning from the module. + - The API returns status C(in process) when the vSwitch is currently + being set up in the servers. If this happens, the module will try again until + the status changes to C(ready) or server has been removed from vSwitch. + - Please note that if you disable wait while deleting and removing servers module + will fail with C(VSWITCH_IN_PROCESS) error. + type: bool + default: true + wait_delay: + description: + - Delay to wait (in seconds) before checking again whether the vSwitch servers has been configured. + type: int + default: 10 + timeout: + description: + - Timeout (in seconds) for waiting for vSwitch servers to be configured. + type: int + default: 180 +''' + +EXAMPLES = r''' +- name: Create vSwitch with VLAN 4010 and name foo + community.hrobot.v_switch: + hetzner_user: foo + hetzner_password: bar + vlan: 4010 + name: foo + +- name: Create vSwitch with VLAN 4020 and name foo with two servers + community.hrobot.v_switch: + hetzner_user: foo + hetzner_password: bar + vlan: 4010 + name: foo + servers: + - 123.123.123.123 + - 154323 +''' + +RETURN = r''' +v_switch: + description: + - Information on the vSwitch. + returned: success + type: dict + contains: + id: + description: + - The vSwitch's ID. + type: int + sample: 4321 + returned: success + name: + description: + - The vSwitch's name. + type: str + sample: 'my vSwitch' + returned: success + vlan: + description: + - The vSwitch's VLAN ID. + type: int + sample: 4000 + returned: success + cancelled: + description: + - Cancellation status. + type: bool + sample: false + returned: success + server: + description: + - The vSwitch's VLAN. + type: list + elements: dict + sample: + - server_ip: '123.123.123.123' + server_ipv6_net: '2a01:4f8:111:4221::' + server_number: 321 + status: 'ready' + contains: + server_ip: + description: + - The server's main IP address. + type: str + sample: '123.123.123.123' + server_ipv6_net: + description: + - The server's main IPv6 network address. + type: str + sample: '2a01:f48:111:4221::' + server_number: + description: + - The server's numeric ID. + type: int + sample: 321 + status: + description: + - Status of vSwitch for this server. + type: str + choices: + - ready + - in process + - failed + sample: 'ready' + returned: success + subnet: + description: + - List of assigned IP addresses. + type: list + elements: dict + sample: + - ip: '213.239.252.48' + mask: 29 + gateway: '213.239.252.49' + contains: + ip: + description: + - IP address. + type: str + sample: '213.239.252.48' + mask: + description: + - Subnet mask in CIDR notation. + type: int + sample: 29 + gateway: + description: + - Gateway of the subnet. + type: str + sample: '213.239.252.49' + returned: success + cloud_network: + description: + - List of assigned Cloud networks. + type: list + elements: dict + sample: + - id: 123 + ip: '10.0.2.0' + mask: 24 + gateway: '10.0.2.1' + contains: + id: + description: + - Cloud network ID. + type: int + sample: 123 + ip: + description: + - IP address. + type: str + sample: '10.0.2.0' + mask: + description: + - Subnet mask in CIDR notation. + type: int + sample: 24 + gateway: + description: + - Gateway. + type: str + sample: '10.0.2.1' + returned: success +''' + + +from datetime import datetime + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.common.text.converters import to_native +from ansible.module_utils.six.moves.urllib.parse import urlencode + +from ansible_collections.community.hrobot.plugins.module_utils.robot import ( + BASE_URL, + ROBOT_DEFAULT_ARGUMENT_SPEC, + get_x_www_form_urlenconded_dict_from_list, + fetch_url_json, + fetch_url_json_with_retries, + CheckDoneTimeoutException, +) + +V_SWITCH_BASE_URL = '{0}/vswitch'.format(BASE_URL) + + +def get_v_switch(module, id_, wait_condition=None): + url = '{0}/{1}'.format(V_SWITCH_BASE_URL, id_) + accept_errors = ['NOT_FOUND'] + if wait_condition: + try: + result, error = fetch_url_json_with_retries( + module, + url, + check_done_callback=wait_condition, + check_done_delay=module.params['wait_delay'], + check_done_timeout=module.params['timeout'], + accept_errors=accept_errors, + ) + except CheckDoneTimeoutException as dummy: + module.fail_json(msg='Timeout waiting vSwitch operation to finish') + else: + result, error = fetch_url_json( + module, + url, + accept_errors=accept_errors, + ) + + if error == 'NOT_FOUND': + module.fail_json(msg='vSwitch not found.') + + return result + + +def print_list(possible_list): + if isinstance(possible_list, list): + return [to_native(x) for x in possible_list] + + +def create_v_switch(module): + headers = {'Content-type': 'application/x-www-form-urlencoded'} + data = {'name': module.params['name'], 'vlan': module.params['vlan']} + result, error = fetch_url_json( + module, + V_SWITCH_BASE_URL, + data=urlencode(data), + headers=headers, + method='POST', + accept_errors=['INVALID_INPUT', 'VSWITCH_LIMIT_REACHED'], + ) + if error == 'INVALID_INPUT': + invalid_parameters = print_list(result['error']['invalid']) + module.fail_json(msg='vSwitch invalid parameter ({0})'.format(invalid_parameters)) + elif error == 'VSWITCH_LIMIT_REACHED': + module.fail_json(msg='The maximum count of vSwitches is reached') + + return result + + +def delete_v_switch(module, id_): + url = '{0}/{1}'.format(V_SWITCH_BASE_URL, id_) + headers = {'Content-type': 'application/x-www-form-urlencoded'} + data = {'cancellation_date': datetime.now().strftime('%y-%m-%d')} + result, error = fetch_url_json( + module, + url, + data=urlencode(data), + headers=headers, + method='DELETE', + accept_errors=['INVALID_INPUT', 'NOT_FOUND', 'CONFLICT'], + allow_empty_result=True, + ) + if error == 'INVALID_INPUT': + invalid_parameters = print_list(result['error']['invalid']) + module.fail_json(msg='vSwitch invalid parameter ({0})'.format(invalid_parameters)) + elif error == 'NOT_FOUND': + module.fail_json(msg='vSwitch not found to delete') + elif error == 'CONFLICT': + module.fail_json(msg='The vSwitch is already cancelled') + + return result + + +def is_all_servers_ready(result, dummy): + return all(server['status'] == 'ready' for server in result['server']) + + +def add_servers(module, id_, servers): + url = '{0}/{1}/server'.format(V_SWITCH_BASE_URL, id_) + headers = {'Content-type': 'application/x-www-form-urlencoded'} + data = get_x_www_form_urlenconded_dict_from_list('server', servers) + result, error = fetch_url_json( + module, + url, + data=urlencode(data), + headers=headers, + method='POST', + # TODO: missing NOT_FOUND, VSWITCH_NOT_AVAILABLE, VSWITCH_PER_SERVER_LIMIT_REACHED + accept_errors=[ + 'INVALID_INPUT', + 'SERVER_NOT_FOUND', + 'VSWITCH_VLAN_NOT_UNIQUE', + 'VSWITCH_IN_PROCESS', + 'VSWITCH_SERVER_LIMIT_REACHED', + ], + allow_empty_result=True, + allowed_empty_result_status_codes=(201,), + ) + if error == 'INVALID_INPUT': + invalid_parameters = print_list(result['error']['invalid']) + module.fail_json(msg='Invalid parameter adding server ({0})'.format(invalid_parameters)) + elif error == 'SERVER_NOT_FOUND': + # information about which servers are failing is only there + module.fail_json(msg=result['error']['message']) + elif error == 'VSWITCH_VLAN_NOT_UNIQUE': + # information about which servers are failing is only there + module.fail_json(msg=result['error']['message']) + elif error == 'VSWITCH_IN_PROCESS': + module.fail_json(msg='There is a update running, therefore the vswitch can not be updated') + elif error == 'VSWITCH_SERVER_LIMIT_REACHED': + module.fail_json(msg='The maximum number of servers is reached for this vSwitch') + + # TODO: add and delete with `wait=false` + wait_condition = is_all_servers_ready if module.params['wait'] else None + return get_v_switch(module, id_, wait_condition) + + +def delete_servers(module, id_, servers): + url = '{0}/{1}/server'.format(V_SWITCH_BASE_URL, id_) + headers = {'Content-type': 'application/x-www-form-urlencoded'} + data = get_x_www_form_urlenconded_dict_from_list('server', servers) + result, error = fetch_url_json( + module, + url, + data=urlencode(data), + headers=headers, + method='DELETE', + # TODO: missing INVALID_INPUT, NOT_FOUND + accept_errors=['SERVER_NOT_FOUND', 'VSWITCH_IN_PROCESS'], + allow_empty_result=True, + ) + if error == 'SERVER_NOT_FOUND': + # information about which servers are failing is only there + module.fail_json(msg=result['error']['message']) + elif error == 'VSWITCH_IN_PROCESS': + module.fail_json(msg='There is a update running, therefore the vswitch can not be updated') + + wait_condition = is_all_servers_ready if module.params['wait'] else None + return get_v_switch(module, id_, wait_condition) + + +def get_servers_to_delete(current_servers, desired_servers): + return [ + server['server_ip'] + for server in current_servers + if server['server_ip'] not in desired_servers + and server['server_ipv6_net'] not in desired_servers + and str(server['server_number']) not in desired_servers + ] + + +def get_servers_to_add(current_servers, desired_servers): + current_ids = [str(server['server_number']) for server in current_servers] + current_ips = [server['server_ip'] for server in current_servers] + current_ipv6s = [server['server_ipv6_net'] for server in current_servers] + + return [ + server + for server in desired_servers + if server not in current_ips and server not in current_ids and server not in current_ipv6s + ] + + +def set_desired_servers(module, id_): + v_switch = get_v_switch(module, id_) + changed = False + + if module.params['servers'] is None: + return (v_switch, changed) + + servers_to_delete = get_servers_to_delete(v_switch['server'], module.params['servers']) + if servers_to_delete: + if not module.check_mode: + v_switch = delete_servers(module, id_, servers_to_delete) + changed = True + servers_to_add = get_servers_to_add(v_switch['server'], module.params['servers']) + if servers_to_add: + if not module.check_mode: + v_switch = add_servers(module, id_, servers_to_add) + changed = True + return (v_switch, changed) + + +def main(): + argument_spec = dict( + vlan=dict(type='int', required=True), + name=dict(type='str', required=True), + state=dict(type='str', default='present', choices=['present', 'absent']), + servers=dict(type='list', elements='str'), + wait=dict(type='bool', default=True), + wait_delay=dict(type='int', default=10), + timeout=dict(type='int', default=180), + ) + argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + v_switches, error = fetch_url_json(module, V_SWITCH_BASE_URL, accept_errors=['UNAUTHORIZED']) + + if error: + module.fail_json(msg='Please check your current user and password configuration') + + matched_v_switches = [ + v + for v in v_switches + if v['name'] == module.params['name'] and v['vlan'] == module.params['vlan'] + ] + non_cancelled_v_switches = [m for m in matched_v_switches if m['cancelled'] is False] + result = {'changed': False} + + if len(non_cancelled_v_switches) > 1: + module.fail_json( + msg='Multiple vSwitches with same name and VLAN ID in non cancelled status. Clean it.' + ) + + elif len(non_cancelled_v_switches) == 1: + id_ = non_cancelled_v_switches[0]['id'] + v_switch, changed = set_desired_servers(module, id_) + if changed: + result['changed'] = True + + if module.params['state'] == 'present': + result['v_switch'] = v_switch + elif module.params['state'] == 'absent': + if not module.check_mode: + delete_v_switch(module, id_) + result['changed'] = True + else: + # not reachable + raise NotImplementedError + else: + if module.params['state'] == 'present': + result['changed'] = True + if not module.check_mode: + v_switch = create_v_switch(module) + if module.params['servers']: + result['v_switch'] = add_servers(module, v_switch['id'], module.params['servers']) + else: + result['v_switch'] = v_switch + + module.exit_json(**result) + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/tests/config.yml b/ansible_collections/community/hrobot/tests/config.yml new file mode 100644 index 000000000..38590f2e4 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/config.yml @@ -0,0 +1,9 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +# See template for more information: +# https://github.com/ansible/ansible/blob/devel/test/lib/ansible_test/config/config.yml +modules: + python_requires: default diff --git a/ansible_collections/community/hrobot/tests/ee/all.yml b/ansible_collections/community/hrobot/tests/ee/all.yml new file mode 100644 index 000000000..26f198b4f --- /dev/null +++ b/ansible_collections/community/hrobot/tests/ee/all.yml @@ -0,0 +1,18 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +- hosts: localhost + tasks: + - name: Find all roles + find: + paths: + - "{{ (playbook_dir | default('.')) ~ '/roles' }}" + file_type: directory + depth: 1 + register: result + - name: Include all roles + include_role: + name: "{{ item }}" + loop: "{{ result.files | map(attribute='path') | map('regex_replace', '.*/', '') | sort }}" diff --git a/ansible_collections/community/hrobot/tests/ee/roles/smoke/library/smoke_ipaddress.py b/ansible_collections/community/hrobot/tests/ee/roles/smoke/library/smoke_ipaddress.py new file mode 100644 index 000000000..6c2156135 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/ee/roles/smoke/library/smoke_ipaddress.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2022 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: smoke_ipaddress +short_description: Check whether ipaddress is present +author: + - Felix Fontein (@felixfontein) +description: + - Check whether C(ipaddress) is present. +options: {} +''' + +EXAMPLES = r''' # ''' + +RETURN = r''' # ''' + +import traceback + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +try: + import ipaddress # noqa: F401, pylint: disable=unused-import + HAS_IPADDRESS = True + IPADDRESS_IMP_ERR = None +except ImportError as exc: + IPADDRESS_IMP_ERR = traceback.format_exc() + HAS_IPADDRESS = False + + +def main(): + module = AnsibleModule(argument_spec=dict(), supports_check_mode=True) + + if not HAS_IPADDRESS: + module.fail_json(msg=missing_required_lib('ipaddress'), exception=IPADDRESS_IMP_ERR) + + module.exit_json(msg='Everything is ok') + + +if __name__ == '__main__': # pragma: no cover + main() # pragma: no cover diff --git a/ansible_collections/community/hrobot/tests/ee/roles/smoke/tasks/main.yml b/ansible_collections/community/hrobot/tests/ee/roles/smoke/tasks/main.yml new file mode 100644 index 000000000..a83cfbb30 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/ee/roles/smoke/tasks/main.yml @@ -0,0 +1,29 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +- name: Check whether ipaddress is present + smoke_ipaddress: + register: result + +- name: Validate result + assert: + that: + - result.msg == 'Everything is ok' + +- name: Check ssh_key module with invalid fingerprint + community.hrobot.ssh_key: + hetzner_user: foo + hetzner_password: bar + name: baz + state: absent + fingerprint: f0:0b + ignore_errors: true + register: result + +- name: Validate result + assert: + that: + - result is failed + - "result.msg == 'Fingerprint must consist of 16 8-bit hex numbers: got 2 8-bit hex numbers instead'" diff --git a/ansible_collections/community/hrobot/tests/requirements.yml b/ansible_collections/community/hrobot/tests/requirements.yml new file mode 100644 index 000000000..dde980c10 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/requirements.yml @@ -0,0 +1,7 @@ +--- +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +unit_tests_dependencies: +- community.internal_test_tools diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json b/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json new file mode 100644 index 000000000..c2e612e5f --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json @@ -0,0 +1,10 @@ +{ + "include_symlinks": false, + "prefixes": [ + "docs/docsite/" + ], + "output": "path-line-column-message", + "requirements": [ + "antsibull-docs" + ] +} diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json.license b/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.json.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.py b/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.py new file mode 100755 index 000000000..673104923 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/extra-docs.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later +"""Check extra collection docs with antsibull-docs.""" +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import sys +import subprocess + + +def main(): + """Main entry point.""" + if not os.path.isdir(os.path.join('docs', 'docsite')): + return + p = subprocess.run(['antsibull-docs', 'lint-collection-docs', '.'], check=False) + if p.returncode not in (0, 3): + print('{0}:0:0: unexpected return code {1}'.format(sys.argv[0], p.returncode)) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/licenses.json b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.json new file mode 100644 index 000000000..50e47ca88 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.json @@ -0,0 +1,4 @@ +{ + "include_symlinks": false, + "output": "path-message" +} diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/licenses.json.license b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.json.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.json.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/licenses.py b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.py new file mode 100755 index 000000000..80eb795ef --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# Copyright (c) 2022, Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later +"""Prevent files without a correct license identifier from being added to the source tree.""" +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import glob +import sys + + +def format_license_list(licenses): + if not licenses: + return '(empty)' + return ', '.join(['"%s"' % license for license in licenses]) + + +def find_licenses(filename, relax=False): + spdx_license_identifiers = [] + other_license_identifiers = [] + has_copyright = False + try: + with open(filename, 'r', encoding='utf-8') as f: + for line in f: + line = line.rstrip() + if 'Copyright ' in line: + has_copyright = True + if 'Copyright: ' in line: + print('%s: found copyright line with "Copyright:". Please remove the colon.' % (filename, )) + if 'SPDX-FileCopyrightText: ' in line: + has_copyright = True + idx = line.find('SPDX-License-Identifier: ') + if idx >= 0: + lic_id = line[idx + len('SPDX-License-Identifier: '):] + spdx_license_identifiers.extend(lic_id.split(' OR ')) + if 'GNU General Public License' in line: + if 'v3.0+' in line: + other_license_identifiers.append('GPL-3.0-or-later') + if 'version 3 or later' in line: + other_license_identifiers.append('GPL-3.0-or-later') + if 'Simplified BSD License' in line: + other_license_identifiers.append('BSD-2-Clause') + if 'Apache License 2.0' in line: + other_license_identifiers.append('Apache-2.0') + if 'PSF License' in line or 'Python-2.0' in line: + other_license_identifiers.append('PSF-2.0') + if 'MIT License' in line: + other_license_identifiers.append('MIT') + except Exception as exc: + print('%s: error while processing file: %s' % (filename, exc)) + if len(set(spdx_license_identifiers)) < len(spdx_license_identifiers): + print('%s: found identical SPDX-License-Identifier values' % (filename, )) + if other_license_identifiers and set(other_license_identifiers) != set(spdx_license_identifiers): + print('%s: SPDX-License-Identifier yielded the license list %s, while manual guessing yielded the license list %s' % ( + filename, format_license_list(spdx_license_identifiers), format_license_list(other_license_identifiers))) + if not has_copyright and not relax: + print('%s: found no copyright notice' % (filename, )) + return sorted(spdx_license_identifiers) + + +def main(): + """Main entry point.""" + paths = sys.argv[1:] or sys.stdin.read().splitlines() + + # The following paths are allowed to have no license identifier + no_comments_allowed = [ + 'changelogs/fragments/*.yml', + 'changelogs/fragments/*.yaml', + ] + + # These files are completely ignored + ignore_paths = [ + '.ansible-test-timeout.json', + '.reuse/dep5', + 'LICENSES/*.txt', + 'COPYING', + ] + + no_comments_allowed = [fn for pattern in no_comments_allowed for fn in glob.glob(pattern)] + ignore_paths = [fn for pattern in ignore_paths for fn in glob.glob(pattern)] + + valid_licenses = [license_file[len('LICENSES/'):-len('.txt')] for license_file in glob.glob('LICENSES/*.txt')] + + for path in paths: + if path.startswith('./'): + path = path[2:] + if path in ignore_paths or path.startswith('tests/output/'): + continue + if os.stat(path).st_size == 0: + continue + if not path.endswith('.license') and os.path.exists(path + '.license'): + path = path + '.license' + valid_licenses_for_path = valid_licenses + if path.startswith('plugins/') and not path.startswith(('plugins/modules/', 'plugins/module_utils/')): + valid_licenses_for_path = [license for license in valid_licenses if license == 'GPL-3.0-or-later'] + licenses = find_licenses(path, relax=path in no_comments_allowed) + if not licenses: + if path not in no_comments_allowed: + print('%s: must have at least one license' % (path, )) + else: + for license in licenses: + if license not in valid_licenses_for_path: + print('%s: found not allowed license "%s", must be one of %s' % ( + path, license, format_license_list(valid_licenses_for_path))) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/licenses.py.license b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.py.license new file mode 100644 index 000000000..6c4958feb --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/licenses.py.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: 2022, Felix Fontein diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json b/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json new file mode 100644 index 000000000..c789a7fd3 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json @@ -0,0 +1,7 @@ +{ + "include_symlinks": true, + "prefixes": [ + "plugins/" + ], + "output": "path-message" +} diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json.license b/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.json.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.py b/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.py new file mode 100755 index 000000000..51444ab75 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/extra/no-unwanted-files.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later +"""Prevent unwanted files from being added to the source tree.""" +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import sys + + +def main(): + """Main entry point.""" + paths = sys.argv[1:] or sys.stdin.read().splitlines() + + allowed_extensions = ( + '.cs', + '.ps1', + '.psm1', + '.py', + ) + + skip_paths = set([ + ]) + + skip_directories = ( + ) + + for path in paths: + if path in skip_paths: + continue + + if any(path.startswith(skip_directory) for skip_directory in skip_directories): + continue + + ext = os.path.splitext(path)[1] + + if ext not in allowed_extensions: + print('%s: extension must be one of: %s' % (path, ', '.join(allowed_extensions))) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt new file mode 100644 index 000000000..c368addc9 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt @@ -0,0 +1,8 @@ +plugins/modules/boot.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall.py pylint:bad-option-value # a pylint test that is disabled was modified over time +plugins/modules/firewall.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall_info.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/server.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/server_info.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/v_switch.py validate-modules:return-syntax-error # only allowed in 2.13+ +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.10.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt new file mode 100644 index 000000000..cfbc8b045 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt @@ -0,0 +1,7 @@ +plugins/modules/boot.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall_info.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/server.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/server_info.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/v_switch.py validate-modules:return-syntax-error # only allowed in 2.13+ +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.11.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt new file mode 100644 index 000000000..cfbc8b045 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt @@ -0,0 +1,7 @@ +plugins/modules/boot.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall_info.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/server.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/server_info.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/v_switch.py validate-modules:return-syntax-error # only allowed in 2.13+ +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.12.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt new file mode 100644 index 000000000..0d9329fad --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt @@ -0,0 +1 @@ +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.13.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt new file mode 100644 index 000000000..0d9329fad --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt @@ -0,0 +1 @@ +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.14.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt new file mode 100644 index 000000000..0d9329fad --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt @@ -0,0 +1 @@ +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.15.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt b/ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt new file mode 100644 index 000000000..fd7a4e740 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt @@ -0,0 +1,3 @@ +plugins/modules/boot.py validate-modules:return-syntax-error # only allowed in 2.13+ +plugins/modules/firewall.py pylint:bad-option-value # a pylint test that is disabled was modified over time +tests/ee/roles/smoke/library/smoke_ipaddress.py shebang diff --git a/ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt.license b/ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt.license new file mode 100644 index 000000000..edff8c768 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/sanity/ignore-2.9.txt.license @@ -0,0 +1,3 @@ +GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +SPDX-License-Identifier: GPL-3.0-or-later +SPDX-FileCopyrightText: Ansible Project diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/inventory/test_robot.py b/ansible_collections/community/hrobot/tests/unit/plugins/inventory/test_robot.py new file mode 100644 index 000000000..31d6adae0 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/inventory/test_robot.py @@ -0,0 +1,361 @@ +# Copyright (c), Felix Fontein , 2020 +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +import json +import os +import textwrap + +import pytest + +from ansible import constants as C +from ansible.inventory.data import InventoryData +from ansible.inventory.manager import InventoryManager +from ansible.module_utils.common.text.converters import to_native +from ansible.template import Templar + +from ansible_collections.community.internal_test_tools.tests.unit.mock.path import mock_unfrackpath_noop +from ansible_collections.community.internal_test_tools.tests.unit.mock.loader import DictDataLoader +from ansible_collections.community.internal_test_tools.tests.unit.utils.open_url_framework import ( + OpenUrlCall, + OpenUrlProxy, +) + +from ansible_collections.community.hrobot.plugins.inventory.robot import InventoryModule +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL + + +original_exists = os.path.exists +original_access = os.access + + +def exists_mock(path, exists=True): + def exists(f): + if to_native(f) == path: + return exists + return original_exists(f) + + return exists + + +def access_mock(path, can_access=True): + def access(f, m, *args, **kwargs): + if to_native(f) == path: + return can_access + return original_access(f, m, *args, **kwargs) + + return access + + +@pytest.fixture(scope="module") +def inventory(): + r = InventoryModule() + r.inventory = InventoryData() + r.templar = Templar(loader=DictDataLoader({})) + return r + + +def get_option(option): + if option == 'filters': + return {} + if option == 'hetzner_user': + return 'test' + if option == 'hetzner_password': + return 'hunter2' + return False + + +def test_populate(inventory, mocker): + open_url = OpenUrlProxy([ + OpenUrlCall('GET', 200) + .result_json([ + { + 'server': { + 'server_ip': '1.2.3.4', + }, + }, + { + 'server': { + 'server_ip': '1.2.3.5', + 'server_name': 'test-server', + }, + }, + { + 'server': { + 'server_number': 5, + }, + }, + ]) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + + inventory.get_option = mocker.MagicMock(side_effect=get_option) + inventory.populate(inventory.get_servers()) + + open_url.assert_is_done() + + host_1 = inventory.inventory.get_host('1.2.3.4') + host_2 = inventory.inventory.get_host('test-server') + host_3 = inventory.inventory.get_host('5') + + host_1_vars = host_1.get_vars() + host_2_vars = host_2.get_vars() + host_3_vars = host_3.get_vars() + + assert host_1_vars['ansible_host'] == '1.2.3.4' + assert host_1_vars['hrobot_server_ip'] == '1.2.3.4' + assert 'hrobot_server_name' not in host_1_vars + assert host_2_vars['ansible_host'] == '1.2.3.5' + assert host_2_vars['hrobot_server_ip'] == '1.2.3.5' + assert host_2_vars['hrobot_server_name'] == 'test-server' + assert 'ansible_host' not in host_3_vars + assert 'hrobot_server_ip' not in host_3_vars + assert 'hrobot_server_name' not in host_3_vars + + +def test_inventory_file_simple(mocker): + open_url = OpenUrlProxy([ + OpenUrlCall('GET', 200) + .result_json([ + { + 'server': { + 'server_ip': '1.2.3.4', + 'dc': 'foo', + }, + }, + { + 'server': { + 'server_ip': '1.2.3.5', + 'server_name': 'test-server', + 'dc': 'foo', + }, + }, + { + 'server': { + 'server_ip': '1.2.3.6', + 'server_name': 'test-server-2', + 'dc': 'bar', + }, + }, + ]) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + inventory_filename = "test.robot.yaml" + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + mocker.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop) + mocker.patch('os.path.exists', exists_mock(inventory_filename)) + mocker.patch('os.access', access_mock(inventory_filename)) + + C.INVENTORY_ENABLED = ['community.hrobot.robot'] + inventory_file = {inventory_filename: textwrap.dedent("""\ + --- + plugin: community.hrobot.robot + hetzner_user: test + hetzner_password: hunter2 + filters: + dc: foo + """)} + im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename) + open_url.assert_is_done() + + assert im._inventory.hosts + assert '1.2.3.4' in im._inventory.hosts + assert 'test-server' in im._inventory.hosts + assert 'test-server-2' not in im._inventory.hosts + assert im._inventory.get_host('1.2.3.4') in im._inventory.groups['ungrouped'].hosts + assert im._inventory.get_host('test-server') in im._inventory.groups['ungrouped'].hosts + assert len(im._inventory.groups['ungrouped'].hosts) == 2 + assert len(im._inventory.groups['all'].hosts) == 0 + + +def test_inventory_file_simple_2(mocker): + open_url = OpenUrlProxy([ + OpenUrlCall('GET', 200) + .result_json([ + { + 'server': { + 'server_ip': '1.2.3.4', + 'dc': 'foo', + }, + }, + { + 'server': { + 'server_ip': '1.2.3.5', + 'server_name': 'test-server', + 'dc': 'foo', + }, + }, + { + 'server': { + 'server_ip': '1.2.3.6', + 'server_name': 'test-server-2', + 'dc': 'bar', + }, + }, + ]) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + inventory_filename = "test.robot.yaml" + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + mocker.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop) + mocker.patch('os.path.exists', exists_mock(inventory_filename)) + mocker.patch('os.access', access_mock(inventory_filename)) + + C.INVENTORY_ENABLED = ['community.hrobot.robot'] + inventory_file = {inventory_filename: textwrap.dedent("""\ + --- + plugin: community.hrobot.robot + hetzner_user: '{{ "test" }}' + hetzner_password: '{{ "hunter2" }}' + filters: + dc: foo + """)} + im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename) + open_url.assert_is_done() + + assert im._inventory.hosts + assert '1.2.3.4' in im._inventory.hosts + assert 'test-server' in im._inventory.hosts + assert 'test-server-2' not in im._inventory.hosts + assert im._inventory.get_host('1.2.3.4') in im._inventory.groups['ungrouped'].hosts + assert im._inventory.get_host('test-server') in im._inventory.groups['ungrouped'].hosts + assert len(im._inventory.groups['ungrouped'].hosts) == 2 + assert len(im._inventory.groups['all'].hosts) == 0 + + +@pytest.mark.parametrize("error_result", [ + None, + json.dumps(dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + ), sort_keys=True).encode('utf-8') +]) +def test_inventory_file_fail(mocker, error_result): + open_url = OpenUrlProxy([ + OpenUrlCall('GET', 200) + .result_error(error_result) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + inventory_filename = "test.robot.yml" + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + mocker.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop) + mocker.patch('os.path.exists', exists_mock(inventory_filename)) + mocker.patch('os.access', access_mock(inventory_filename)) + + C.INVENTORY_ENABLED = ['community.hrobot.robot'] + inventory_file = {inventory_filename: textwrap.dedent("""\ + --- + plugin: community.hrobot.robot + hetzner_user: test + hetzner_password: hunter2 + filters: + dc: foo + """)} + im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename) + open_url.assert_is_done() + + assert not im._inventory.hosts + assert '1.2.3.4' not in im._inventory.hosts + assert 'test-server' not in im._inventory.hosts + assert 'test-server-2' not in im._inventory.hosts + assert len(im._inventory.groups['ungrouped'].hosts) == 0 + assert len(im._inventory.groups['all'].hosts) == 0 + + +def test_inventory_wrong_file(mocker): + open_url = OpenUrlProxy([]) + inventory_filename = "test.bobot.yml" + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + mocker.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop) + mocker.patch('os.path.exists', exists_mock(inventory_filename)) + mocker.patch('os.access', access_mock(inventory_filename)) + + C.INVENTORY_ENABLED = ['community.hrobot.robot'] + inventory_file = {inventory_filename: textwrap.dedent("""\ + --- + plugin: community.hrobot.robot + hetzner_user: test + hetzner_password: hunter2 + """)} + im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename) + open_url.assert_is_done() + + assert not im._inventory.hosts + assert '1.2.3.4' not in im._inventory.hosts + assert 'test-server' not in im._inventory.hosts + assert 'test-server-2' not in im._inventory.hosts + assert len(im._inventory.groups['ungrouped'].hosts) == 0 + assert len(im._inventory.groups['all'].hosts) == 0 + + +def test_inventory_no_file(mocker): + open_url = OpenUrlProxy([]) + inventory_filename = "test.robot.yml" + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + mocker.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop) + mocker.patch('os.path.exists', exists_mock(inventory_filename, False)) + mocker.patch('os.access', access_mock(inventory_filename, False)) + + C.INVENTORY_ENABLED = ['community.hrobot.robot'] + im = InventoryManager(loader=DictDataLoader({}), sources=inventory_filename) + open_url.assert_is_done() + + assert not im._inventory.hosts + assert len(im._inventory.groups['ungrouped'].hosts) == 0 + assert len(im._inventory.groups['all'].hosts) == 0 + + +def test_inventory_file_collision(mocker): + open_url = OpenUrlProxy([ + OpenUrlCall('GET', 200) + .result_json([ + { + 'server': { + 'server_ip': '1.2.3.4', + 'server_name': 'test-server', + }, + }, + { + 'server': { + 'server_ip': '1.2.3.5', + 'server_name': 'test-server', + }, + }, + ]) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + inventory_filename = "test.robot.yaml" + mocker.patch('ansible_collections.community.hrobot.plugins.module_utils.robot.open_url', open_url) + mocker.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop) + mocker.patch('os.path.exists', exists_mock(inventory_filename)) + mocker.patch('os.access', access_mock(inventory_filename)) + + C.INVENTORY_ENABLED = ['community.hrobot.robot'] + inventory_file = {inventory_filename: textwrap.dedent("""\ + --- + plugin: community.hrobot.robot + hetzner_user: test + hetzner_password: hunter2 + """)} + im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename) + open_url.assert_is_done() + + assert im._inventory.hosts + assert 'test-server' in im._inventory.hosts + assert im._inventory.get_host('test-server').get_vars()['ansible_host'] == '1.2.3.4' + assert im._inventory.get_host('test-server') in im._inventory.groups['ungrouped'].hosts + assert len(im._inventory.groups['ungrouped'].hosts) == 1 + assert len(im._inventory.groups['all'].hosts) == 0 + # TODO: check for warning diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_failover.py b/ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_failover.py new file mode 100644 index 000000000..56cd02944 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_failover.py @@ -0,0 +1,189 @@ +# Copyright (c) 2017 Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import copy +import json +import pytest + +from mock import MagicMock +from ansible_collections.community.hrobot.plugins.module_utils import robot +from ansible_collections.community.hrobot.plugins.module_utils import failover + + +class ModuleFailException(Exception): + def __init__(self, msg, **kwargs): + super(ModuleFailException, self).__init__(msg) + self.fail_msg = msg + self.fail_kwargs = kwargs + + +def get_module_mock(): + def f(msg, **kwargs): + raise ModuleFailException(msg, **kwargs) + + module = MagicMock() + module.fail_json = f + module.from_json = json.loads + return module + + +# ######################################################################################## + +GET_FAILOVER_SUCCESS = [ + ( + '1.2.3.4', + (None, dict( + body=json.dumps(dict( + failover=dict( + active_server_ip='1.1.1.1', + ip='1.2.3.4', + netmask='255.255.255.255', + ) + )).encode('utf-8'), + )), + '1.1.1.1', + dict( + active_server_ip='1.1.1.1', + ip='1.2.3.4', + netmask='255.255.255.255', + ) + ), +] + + +GET_FAILOVER_FAIL = [ + ( + '1.2.3.4', + (None, dict( + body=json.dumps(dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + )).encode('utf-8'), + )), + 'Request failed: 400 foo (bar)' + ), + ( + '1.2.3.4', + (None, dict( + body='{"foo": "bar"}'.encode('utf-8'), + )), + 'Cannot interpret result: {"foo": "bar"}' + ), +] + + +@pytest.mark.parametrize("ip, return_value, result, record", GET_FAILOVER_SUCCESS) +def test_get_failover_record(monkeypatch, ip, return_value, result, record): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=copy.deepcopy(return_value)) + + assert failover.get_failover_record(module, ip) == record + + +@pytest.mark.parametrize("ip, return_value, result", GET_FAILOVER_FAIL) +def test_get_failover_record_fail(monkeypatch, ip, return_value, result): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=copy.deepcopy(return_value)) + + with pytest.raises(ModuleFailException) as exc: + failover.get_failover_record(module, ip) + + assert exc.value.fail_msg == result + assert exc.value.fail_kwargs == dict() + + +@pytest.mark.parametrize("ip, return_value, result, record", GET_FAILOVER_SUCCESS) +def test_get_failover(monkeypatch, ip, return_value, result, record): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=copy.deepcopy(return_value)) + + assert failover.get_failover(module, ip) == result + + +@pytest.mark.parametrize("ip, return_value, result", GET_FAILOVER_FAIL) +def test_get_failover_fail(monkeypatch, ip, return_value, result): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=copy.deepcopy(return_value)) + + with pytest.raises(ModuleFailException) as exc: + failover.get_failover(module, ip) + + assert exc.value.fail_msg == result + assert exc.value.fail_kwargs == dict() + + +# ######################################################################################## + +SET_FAILOVER_SUCCESS = [ + ( + '1.2.3.4', + '1.1.1.1', + (None, dict( + body=json.dumps(dict( + failover=dict( + active_server_ip='1.1.1.2', + ) + )).encode('utf-8'), + )), + ('1.1.1.2', True) + ), + ( + '1.2.3.4', + '1.1.1.1', + (None, dict( + body=json.dumps(dict( + error=dict( + code="FAILOVER_ALREADY_ROUTED", + status=400, + message="Failover already routed", + ), + )).encode('utf-8'), + )), + ('1.1.1.1', False) + ), +] + + +SET_FAILOVER_FAIL = [ + ( + '1.2.3.4', + '1.1.1.1', + (None, dict( + body=json.dumps(dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + )).encode('utf-8'), + )), + 'Request failed: 400 foo (bar)' + ), +] + + +@pytest.mark.parametrize("ip, value, return_value, result", SET_FAILOVER_SUCCESS) +def test_set_failover(monkeypatch, ip, value, return_value, result): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=copy.deepcopy(return_value)) + + assert failover.set_failover(module, ip, value) == result + + +@pytest.mark.parametrize("ip, value, return_value, result", SET_FAILOVER_FAIL) +def test_set_failover_fail(monkeypatch, ip, value, return_value, result): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=copy.deepcopy(return_value)) + + with pytest.raises(ModuleFailException) as exc: + failover.set_failover(module, ip, value) + + assert exc.value.fail_msg == result + assert exc.value.fail_kwargs == dict() diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_robot.py b/ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_robot.py new file mode 100644 index 000000000..b53049e8b --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_robot.py @@ -0,0 +1,207 @@ +# Copyright (c) 2017 Ansible Project +# Copyright (c), Felix Fontein , 2019-2020 +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json +import pytest + +from mock import MagicMock +from ansible_collections.community.hrobot.plugins.module_utils import robot + + +class ModuleFailException(Exception): + def __init__(self, msg, **kwargs): + super(ModuleFailException, self).__init__(msg) + self.fail_msg = msg + self.fail_kwargs = kwargs + + +def get_module_mock(): + def f(msg, **kwargs): + raise ModuleFailException(msg, **kwargs) + + module = MagicMock() + module.fail_json = f + module.from_json = json.loads + return module + + +# ######################################################################################## + +FETCH_URL_JSON_SUCCESS = [ + ( + (None, dict( + body=json.dumps(dict( + a='b' + )).encode('utf-8'), + )), + None, + (dict( + a='b' + ), None) + ), + ( + (None, dict( + body=json.dumps(dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + a='b' + )).encode('utf-8'), + )), + ['foo'], + (dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + a='b' + ), 'foo') + ), +] + + +FETCH_URL_JSON_FAIL = [ + ( + (None, dict( + body=json.dumps(dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + )).encode('utf-8'), + )), + None, + 'Request failed: 400 foo (bar)' + ), + ( + (None, dict( + body=json.dumps(dict( + error=dict( + code="foo", + status=400, + message="bar", + ), + )).encode('utf-8'), + )), + ['bar'], + 'Request failed: 400 foo (bar)' + ), + ( + (None, dict(body='{this is not json}'.encode('utf-8'))), + [], + 'Cannot decode content retrieved from https://foo/bar' + ), + ( + (None, dict(status=400)), + [], + 'Cannot retrieve content from https://foo/bar, HTTP status code 400' + ), +] + + +@pytest.mark.parametrize("return_value, accept_errors, result", FETCH_URL_JSON_SUCCESS) +def test_fetch_url_json(monkeypatch, return_value, accept_errors, result): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=return_value) + + assert robot.fetch_url_json(module, 'https://foo/bar', accept_errors=accept_errors) == result + + +@pytest.mark.parametrize("return_value, accept_errors, result", FETCH_URL_JSON_FAIL) +def test_fetch_url_json_fail(monkeypatch, return_value, accept_errors, result): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=return_value) + + with pytest.raises(ModuleFailException) as exc: + robot.fetch_url_json(module, 'https://foo/bar', accept_errors=accept_errors) + + assert exc.value.fail_msg == result + assert exc.value.fail_kwargs == dict() + + +def test_fetch_url_json_empty(monkeypatch): + module = get_module_mock() + robot.fetch_url = MagicMock(return_value=(None, dict(status=204, body=''))) + + assert robot.fetch_url_json(module, 'https://foo/bar', allow_empty_result=True) == (None, None) + + robot.fetch_url = MagicMock(return_value=(None, dict(status=400, body=''))) + + with pytest.raises(ModuleFailException) as exc: + robot.fetch_url_json(module, 'https://foo/bar', allow_empty_result=True) + + assert exc.value.fail_msg == 'Cannot retrieve content from https://foo/bar, HTTP status code 400' + assert exc.value.fail_kwargs == dict() + + +@pytest.mark.parametrize("return_value, accept_errors, result", FETCH_URL_JSON_SUCCESS) +def test_plugin_open_url_json(monkeypatch, return_value, accept_errors, result): + response = MagicMock() + response.read = MagicMock(return_value=return_value[1]['body']) + robot.open_url = MagicMock(return_value=response) + plugin = MagicMock() + + assert robot.plugin_open_url_json(plugin, 'https://foo/bar', accept_errors=accept_errors) == result + + +@pytest.mark.parametrize("return_value, accept_errors, result", FETCH_URL_JSON_FAIL) +def test_plugin_open_url_json_fail(monkeypatch, return_value, accept_errors, result): + response = MagicMock() + response.read = MagicMock(return_value=return_value[1].get('body', '')) + robot.open_url = MagicMock(side_effect=robot.HTTPError('https://foo/bar', 400, 'Error!', {}, response)) + plugin = MagicMock() + + with pytest.raises(robot.PluginException) as exc: + robot.plugin_open_url_json(plugin, 'https://foo/bar', accept_errors=accept_errors) + + assert exc.value.error_message == result + + +def test_plugin_open_url_json_fail_other(monkeypatch): + robot.open_url = MagicMock(side_effect=Exception('buh!')) + plugin = MagicMock() + + with pytest.raises(robot.PluginException) as exc: + robot.plugin_open_url_json(plugin, 'https://foo/bar') + + assert exc.value.error_message == 'Failed request to Hetzner Robot server endpoint https://foo/bar: buh!' + + +def test_plugin_open_url_json_fail_other_2(monkeypatch): + response = MagicMock() + response.read = MagicMock(side_effect=AttributeError('read')) + robot.open_url = MagicMock(side_effect=robot.HTTPError('https://foo/bar', 400, 'Error!', {}, response)) + plugin = MagicMock() + + with pytest.raises(robot.PluginException) as exc: + robot.plugin_open_url_json(plugin, 'https://foo/bar') + + assert exc.value.error_message == 'Cannot retrieve content from https://foo/bar, HTTP status code 400' + + +def test_plugin_open_url_json_empty_result(monkeypatch): + response = MagicMock() + response.read = MagicMock(return_value='') + response.code = 200 + robot.open_url = MagicMock(return_value=response) + plugin = MagicMock() + + assert robot.plugin_open_url_json(plugin, 'https://foo/bar', allow_empty_result=True) == (None, None) + + response = MagicMock() + response.read = MagicMock(side_effect=AttributeError('read')) + robot.open_url = MagicMock(side_effect=robot.HTTPError('https://foo/bar', 400, 'Error!', {}, response)) + + with pytest.raises(robot.PluginException) as exc: + robot.plugin_open_url_json(plugin, 'https://foo/bar') + + assert exc.value.error_message == 'Cannot retrieve content from https://foo/bar, HTTP status code 400' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_boot.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_boot.py new file mode 100644 index 000000000..7117afb21 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_boot.py @@ -0,0 +1,541 @@ +# Copyright (c) 2021 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import boot + + +def _amend_server_data(data): + data.update({ + 'server_ip': '123.123.123.123', + 'server_ipv6_net': '2a01:4f8:111:4221::', + 'server_number': 23, + }) + return data + + +def create_rescue_inactive(): + return _amend_server_data({ + 'active': False, + 'arch': [64, 32], + 'authorized_key': [], + 'boot_time': None, + 'host_key': [], + 'os': ['linux', 'linuxold', 'freebsd', 'freebsdbeta', 'freebsdax', 'freebsdbetaax', 'vkvm', 'vkvmold'], + 'password': None, + }) + + +def create_rescue_active(os='linux', arch=64, authorized_key=None, host_key=None): + return _amend_server_data({ + 'active': True, + 'arch': arch, + 'authorized_key': authorized_key or [], + 'boot_time': None, + 'host_key': host_key or [], + 'os': os, + 'password': 'aBcDeFgHiJ1234', + }) + + +def create_linux_inactive(): + return { + 'dist': [ + 'Arch Linux latest minimal', + 'CentOS 7.9 minimal', + 'CentOS 8.4 minimal', + 'Debian 10.10 LAMP', + 'Debian 10.10 minimal', + 'Debian 11 base', + 'Ubuntu 18.04.5 LTS minimal', + 'Ubuntu 18.04.5 LTS Nextcloud', + 'Ubuntu 20.04.1 LTS minimal', + ], + 'arch': [64], + 'lang': ['en'], + 'active': False, + 'password': None, + 'authorized_key': [], + 'host_key': [], + } + + +def create_linux_active(dist='Arch Linux latest minimal', arch=64, lang='en', authorized_key=None, host_key=None): + return { + 'dist': dist, + 'arch': arch, + 'lang': lang, + 'active': True, + 'password': 'aBcDeFgHiJ1234', + 'authorized_key': authorized_key or [], + 'host_key': host_key or [], + } + + +def create_vnc_inactive(): + return { + 'dist': ['CentOS-7.9', 'CentOS-8.4', 'Fedora-33', 'openSUSE-15.2'], + 'arch': [64], + 'lang': ['de_DE', 'en_US', 'fr_FR', 'ru_RU'], + 'active': False, + 'password': None, + } + + +def _amend_boot(data=None): + if data is None: + data = {} + if 'rescue' not in data: + data['rescue'] = create_rescue_inactive() + if 'linux' not in data: + data['linux'] = create_linux_inactive() + if 'vnc' not in data: + data['vnc'] = create_vnc_inactive() + for section in ('windows', 'plesk', 'cpanel'): + if section not in data: + data[section] = None + return { + 'boot': data, + } + + +class TestHetznerBoot(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.boot.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + def test_idempotent_regular(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'server_number': 23, + 'regular_boot': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_linux_inactive(), + })) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['configuration_type'] == 'regular_boot' + assert result['password'] is None + + def test_rescue_idempotent(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'rescue': { + 'os': 'linux', + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_rescue_active(os='linux'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['configuration_type'] == 'rescue' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_rescue_idempotent_2(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'rescue': { + 'os': 'linux', + 'arch': 32, + 'authorized_keys': [ + 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0', + 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99', + '0f:1e:2d:3c:4b:5a:69:78:87:96:a5:b4:c3:d2:e1:f0', + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_rescue_active(os='linux', arch=32, authorized_key=[ + { + 'key': { + 'fingerprint': 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0', + 'name': 'baz', + 'size': 4096, + 'type': 'RSA', + }, + }, + { + 'key': { + 'fingerprint': 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99', + 'name': 'foo bar', + 'size': 2048, + 'type': 'RSA', + }, + }, + { + 'key': { + 'fingerprint': '0f:1e:2d:3c:4b:5a:69:78:87:96:a5:b4:c3:d2:e1:f0', + 'name': 'test', + 'size': 3072, + 'type': 'RSA', + }, + }, + ]), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['configuration_type'] == 'rescue' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_rescue_deactivate(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'regular_boot': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_rescue_active(os='linux'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_url('{0}/boot/23/rescue'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'regular_boot' + assert result['password'] is None + + def test_rescue_deactivate_check_mode(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'regular_boot': True, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_rescue_active(os='linux'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'regular_boot' + assert result['password'] is None + + def test_rescue_activate(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'rescue': { + 'os': 'linux', + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot()) + .expect_url('{0}/boot/23'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_form_value('os', 'linux') + .expect_form_value_absent('arch') + .expect_form_value_absent('authorized_key') + .result_json({ + 'rescue': create_rescue_active(os='linux'), + }) + .expect_url('{0}/boot/23/rescue'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'rescue' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_rescue_activate_check_mode(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'rescue': { + 'os': 'linux', + }, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot()) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'rescue' + assert result['password'] is None + + def test_rescue_reactivate(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'rescue': { + 'os': 'linuxold', + 'arch': 32, + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_rescue_active(os='linux'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_url('{0}/boot/23/rescue'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_form_value('os', 'linuxold') + .expect_form_value('arch', '32') + .expect_form_value_absent('authorized_key') + .result_json({ + 'rescue': create_rescue_active(os='linuxold', arch=32), + }) + .expect_url('{0}/boot/23/rescue'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'rescue' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_rescue_reactivate_check_mode(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'rescue': { + 'os': 'linuxold', + 'arch': 32, + }, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'rescue': create_rescue_active(os='linux'), + })) + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'rescue' + assert result['password'] is None + + def test_install_linux_idempotent(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'install_linux': { + 'dist': 'Arch Linux latest minimal', + 'lang': 'en', + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'linux': create_linux_active(dist='Arch Linux latest minimal', lang='en'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['configuration_type'] == 'install_linux' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_install_linux_idempotent_2(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'install_linux': { + 'dist': 'Arch Linux latest minimal', + 'arch': 32, + 'lang': 'de', + 'authorized_keys': [ + 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0', + '0f:1e:2d:3c:4b:5a:69:78:87:96:a5:b4:c3:d2:e1:f0', + 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99', + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'linux': create_linux_active(dist='Arch Linux latest minimal', arch=32, lang='de', authorized_key=[ + { + 'key': { + 'fingerprint': 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0', + 'name': 'abc', + 'size': 4096, + 'type': 'RSA', + }, + }, + { + 'key': { + 'fingerprint': 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99', + 'name': 'buzz', + 'size': 2048, + 'type': 'RSA', + }, + }, + { + 'key': { + 'fingerprint': '0f:1e:2d:3c:4b:5a:69:78:87:96:a5:b4:c3:d2:e1:f0', + 'name': 'afz', + 'size': 2048, + 'type': 'RSA', + }, + }, + ]), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['configuration_type'] == 'install_linux' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_install_linux_deactivate(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'regular_boot': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'linux': create_linux_active(dist='Arch Linux latest minimal'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_url('{0}/boot/23/linux'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'regular_boot' + assert result['password'] is None + + def test_install_linux_activate(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'install_linux': { + 'dist': 'Arch Linux latest minimal', + 'lang': 'en', + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot()) + .expect_url('{0}/boot/23'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_form_value('dist', 'Arch Linux latest minimal') + .expect_form_value_absent('arch') + .expect_form_value_absent('authorized_key') + .result_json({ + 'linux': create_linux_active(dist='Arch Linux latest minimal', lang='en'), + }) + .expect_url('{0}/boot/23/linux'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'install_linux' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_install_linux_reactivate(self, mocker): + result = self.run_module_success(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'install_linux': { + 'dist': 'Debian 11 base', + 'arch': 32, + 'lang': 'fr', + 'authorized_keys': [ + 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0', + 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99', + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json(_amend_boot({ + 'linux': create_linux_active(dist='Arch Linux latest minimal', lang='en'), + })) + .expect_url('{0}/boot/23'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_url('{0}/boot/23/linux'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_form_value('dist', 'Debian 11 base') + .expect_form_value('arch', '32') + .expect_form_value('lang', 'fr') + .expect_form_present('authorized_key') + # .expect_form_value('authorized_key', 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0') + # .expect_form_value('authorized_key', 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99') + .result_json({ + 'linux': create_linux_active(dist='Debian 11 base', lang='fr', arch=32, authorized_key=[ + { + 'key': { + 'fingerprint': 'aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99', + 'name': 'foo bar', + 'size': 4096, + 'type': 'RSA', + }, + }, + { + 'key': { + 'fingerprint': 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0', + 'name': 'bar', + 'size': 2048, + 'type': 'RSA', + }, + }, + ]), + }) + .expect_url('{0}/boot/23/linux'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['configuration_type'] == 'install_linux' + assert result['password'] == 'aBcDeFgHiJ1234' + + def test_server_not_found(self, mocker): + result = self.run_module_failed(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'regular_boot': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'Server not found', + }, + }) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'This server does not exist, or you do not have access rights for it' + + def test_invalid_input(self, mocker): + result = self.run_module_failed(mocker, boot, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'regular_boot': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'BOOT_NOT_AVAILABLE', + 'message': 'No boot configuration available for this server', + }, + }) + .expect_url('{0}/boot/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'There is no boot configuration available for this server' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip.py new file mode 100644 index 000000000..dcf27d249 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip.py @@ -0,0 +1,247 @@ +# Copyright (c) 2020 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import failover_ip + + +class TestHetznerFailoverIP(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.failover_ip.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + # Tests for state idempotence (routed and unrouted) + + def test_unrouted(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'failover_ip': '1.2.3.4', + 'state': 'unrouted', + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': None, + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['value'] is None + assert result['state'] == 'unrouted' + + def test_routed(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + 'state': 'routed', + 'value': '4.3.2.1', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '4.3.2.1', + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['value'] == '4.3.2.1' + assert result['state'] == 'routed' + + # Tests for changing state (unrouted to routed, vice versa) + + def test_unrouted_to_routed(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + 'state': 'routed', + 'value': '4.3.2.1', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': None, + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '4.3.2.1', + }, + }) + .expect_form_value('active_server_ip', '4.3.2.1') + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['value'] == '4.3.2.1' + assert result['state'] == 'routed' + + def test_unrouted_to_routed_check_mode(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + 'state': 'routed', + 'value': '4.3.2.1', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': None, + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['value'] == '4.3.2.1' + assert result['state'] == 'routed' + + def test_routed_to_unrouted(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + 'state': 'unrouted', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '4.3.2.1', + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': None, + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['value'] is None + assert result['state'] == 'unrouted' + + # Tests for re-routing + + def test_rerouting(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + 'state': 'routed', + 'value': '4.3.2.1', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '5.4.3.2', + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '4.3.2.1', + }, + }) + .expect_form_value('active_server_ip', '4.3.2.1') + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['value'] == '4.3.2.1' + assert result['state'] == 'routed' + + def test_rerouting_already_routed(self, mocker): + result = self.run_module_success(mocker, failover_ip, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + 'state': 'routed', + 'value': '4.3.2.1', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '5.4.3.2', + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 409) + .result_json({ + 'error': { + 'status': 409, + 'code': 'FAILOVER_ALREADY_ROUTED', + 'message': 'Failover already routed', + }, + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '4.3.2.1', + }, + }) + .expect_form_value('active_server_ip', '4.3.2.1') + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['value'] == '4.3.2.1' + assert result['state'] == 'routed' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip_info.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip_info.py new file mode 100644 index 000000000..fb6cbfcd3 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_failover_ip_info.py @@ -0,0 +1,74 @@ +# Copyright (c) 2020 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import failover_ip_info + + +class TestHetznerFailoverIPInfo(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.failover_ip_info.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + # Tests for state (routed and unrouted) + + def test_unrouted(self, mocker): + result = self.run_module_success(mocker, failover_ip_info, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'failover_ip': '1.2.3.4', + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': None, + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['value'] is None + assert result['state'] == 'unrouted' + assert result['failover_ip'] == '1.2.3.4' + assert result['server_ip'] == '2.3.4.5' + assert result['server_number'] == 2345 + + def test_routed(self, mocker): + result = self.run_module_success(mocker, failover_ip_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'failover_ip': '1.2.3.4', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'failover': { + 'ip': '1.2.3.4', + 'netmask': '255.255.255.255', + 'server_ip': '2.3.4.5', + 'server_number': 2345, + 'active_server_ip': '4.3.2.1', + }, + }) + .expect_url('{0}/failover/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['value'] == '4.3.2.1' + assert result['state'] == 'routed' + assert result['failover_ip'] == '1.2.3.4' + assert result['server_ip'] == '2.3.4.5' + assert result['server_number'] == 2345 diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall.py new file mode 100644 index 000000000..8908c5abb --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall.py @@ -0,0 +1,1865 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +import pytest + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import firewall + + +def create_params(parameter, *values): + assert len(values) > 1 + result = [] + for i in range(1, len(values)): + result.append((parameter, values[i - 1], values[i])) + return result + + +def flatten(list_of_lists): + result = [] + for l in list_of_lists: + result.extend(l) + return result + + +class TestHetznerFirewall(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.firewall.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + # Tests for state (absent and present) + + def test_absent_idempotency(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'server_ip': '1.2.3.4', + 'state': 'absent', + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'disabled' + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_absent_idempotency_no_rules(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'absent', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'disabled' + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert 'rules' in result['firewall'] + assert 'input' in result['firewall']['rules'] + assert len(result['firewall']['rules']['input']) == 0 + assert 'output' in result['firewall']['rules'] + assert len(result['firewall']['rules']['output']) == 0 + + def test_absent_changed(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 4321, + 'state': 'absent', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 4321, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/4321'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 4321, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/4321'.format(BASE_URL)) + .expect_form_value('status', 'disabled'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'disabled' + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 4321 + + def test_absent_changed_no_rules(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'absent', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'disabled'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 0 + assert len(result['diff']['before']['rules']['output']) == 0 + assert result['diff']['after']['status'] == 'disabled' + assert len(result['diff']['after']['rules']['input']) == 0 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 0 + + def test_present_idempotency(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_present_changed(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + # Tests for state (absent and present) with check mode + + def test_absent_idempotency_check(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'absent', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'disabled' + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_absent_changed_check(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'absent', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'disabled' + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_present_idempotency_check(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_present_changed_check(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + # Tests for port + + def test_port_idempotency(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'port': 'main', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['port'] == 'main' + assert result['diff']['after']['port'] == 'main' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert result['firewall']['port'] == 'main' + + def test_port_changed(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'port': 'main', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': True, + 'port': 'kvm', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('port', 'main'), + ]) + assert result['changed'] is True + assert result['diff']['before']['port'] == 'kvm' + assert result['diff']['after']['port'] == 'main' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert result['firewall']['port'] == 'main' + + # Tests for allowlist_hos + + def test_allowlist_hos_idempotency(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'allowlist_hos': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['allowlist_hos'] is True + assert result['diff']['before']['whitelist_hos'] is True + assert result['diff']['after']['allowlist_hos'] is True + assert result['diff']['after']['whitelist_hos'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert result['firewall']['allowlist_hos'] is True + assert result['firewall']['whitelist_hos'] is True + + def test_allowlist_hos_changed(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'allowlist_hos': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('whitelist_hos', 'true'), + ]) + assert result['changed'] is True + assert result['diff']['before']['allowlist_hos'] is False + assert result['diff']['before']['whitelist_hos'] is False + assert result['diff']['after']['allowlist_hos'] is True + assert result['diff']['after']['whitelist_hos'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert result['firewall']['allowlist_hos'] is True + assert result['firewall']['whitelist_hos'] is True + + # Tests for filter_ipv6 + + def test_filter_ipv6_idempotency(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'filter_ipv6': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['filter_ipv6'] is True + assert result['diff']['after']['filter_ipv6'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert result['firewall']['filter_ipv6'] is True + + def test_filter_ipv6_changed(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'filter_ipv6': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('filter_ipv6', 'true'), + ]) + assert result['changed'] is True + assert result['diff']['before']['filter_ipv6'] is False + assert result['diff']['after']['filter_ipv6'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert result['firewall']['filter_ipv6'] is True + + # Tests for wait_for_configured in getting status + + def test_wait_get(self, mocker): + mocker.patch('time.sleep', lambda duration: None) + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'wait_for_configured': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_wait_get_timeout(self, mocker): + mocker.patch('time.sleep', lambda duration: None) + result = self.run_module_failed(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'wait_for_configured': True, + 'timeout': 0, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['msg'] == 'Timeout while waiting for firewall to be configured.' + + def test_nowait_get(self, mocker): + result = self.run_module_failed(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'wait_for_configured': False, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['msg'] == 'Firewall configuration cannot be read as it is not configured.' + + # Tests for wait_for_configured in setting status + + def test_wait_update(self, mocker): + mocker.patch('time.sleep', lambda duration: None) + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'wait_for_configured': True, + 'state': 'present', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_wait_update_timeout(self, mocker): + mocker.patch('time.sleep', lambda duration: None) + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'wait_for_configured': True, + 'timeout': 0, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'in process' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert 'Timeout while waiting for firewall to be configured.' in result['warnings'] + + def test_nowait_update(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'wait_for_configured': False, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'disabled' + assert result['diff']['after']['status'] == 'active' + assert result['firewall']['status'] == 'in process' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + # Idempotency checks: different amount of input/output rules + + def test_input_rule_len_change_0_1(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'input': [ + { + 'ip_version': 'ipv4', + 'action': 'discard', + }, + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[input][0][name]') + .expect_form_value('rules[input][0][ip_version]', 'ipv4') + .expect_form_value_absent('rules[input][0][dst_ip]') + .expect_form_value_absent('rules[input][0][dst_port]') + .expect_form_value_absent('rules[input][0][src_ip]') + .expect_form_value_absent('rules[input][0][src_port]') + .expect_form_value_absent('rules[input][0][protocol]') + .expect_form_value_absent('rules[input][0][tcp_flags]') + .expect_form_value('rules[input][0][action]', 'discard') + .expect_form_value_absent('rules[input][1][action]') + .expect_form_value_absent('rules[output][0][action]'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 0 + assert len(result['diff']['before']['rules']['output']) == 0 + assert len(result['diff']['after']['rules']['input']) == 1 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 1 + assert len(result['firewall']['rules']['output']) == 0 + + def test_output_rule_len_change_0_1(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'output': [ + { + 'ip_version': 'ipv4', + 'action': 'discard', + }, + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'output': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + 'input': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[output][0][name]') + .expect_form_value('rules[output][0][ip_version]', 'ipv4') + .expect_form_value_absent('rules[output][0][dst_ip]') + .expect_form_value_absent('rules[output][0][dst_port]') + .expect_form_value_absent('rules[output][0][src_ip]') + .expect_form_value_absent('rules[output][0][src_port]') + .expect_form_value_absent('rules[output][0][protocol]') + .expect_form_value_absent('rules[output][0][tcp_flags]') + .expect_form_value('rules[output][0][action]', 'discard') + .expect_form_value_absent('rules[output][1][action]') + .expect_form_value_absent('rules[input][0][action]'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 0 + assert len(result['diff']['before']['rules']['output']) == 0 + assert len(result['diff']['after']['rules']['input']) == 0 + assert len(result['diff']['after']['rules']['output']) == 1 + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 1 + + def test_input_rule_len_change_1_0(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + }, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[input][0][action]') + .expect_form_value_absent('rules[output][0][action]'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 1 + assert len(result['diff']['before']['rules']['output']) == 0 + assert len(result['diff']['after']['rules']['input']) == 0 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 0 + + def test_output_rule_len_change_1_0(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + }, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[input][0][action]') + .expect_form_value_absent('rules[output][0][action]'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 0 + assert len(result['diff']['before']['rules']['output']) == 1 + assert len(result['diff']['after']['rules']['input']) == 0 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 0 + + def test_input_rule_len_change_1_2(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'input': [ + { + 'ip_version': 'ipv4', + 'dst_port': 80, + 'protocol': 'tcp', + 'action': 'accept', + }, + { + 'ip_version': 'ipv4', + 'action': 'discard', + }, + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': '80', + 'src_ip': None, + 'src_port': None, + 'protocol': 'tcp', + 'tcp_flags': None, + 'action': 'accept', + }, + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value('rules[input][0][action]', 'accept') + .expect_form_value('rules[input][1][action]', 'discard') + .expect_form_value_absent('rules[input][2][action]') + .expect_form_value_absent('rules[output][0][action]'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 1 + assert len(result['diff']['before']['rules']['output']) == 0 + assert len(result['diff']['after']['rules']['input']) == 2 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 2 + assert len(result['firewall']['rules']['output']) == 0 + + def test_output_rule_len_change_1_2(self, mocker): + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'input': [], + 'output': [ + { + 'ip_version': 'ipv4', + 'dst_port': 80, + 'protocol': 'tcp', + 'action': 'accept', + }, + { + 'ip_version': 'ipv4', + 'action': 'discard', + }, + ], + }, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [ + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': '80', + 'src_ip': None, + 'src_port': None, + 'protocol': 'tcp', + 'tcp_flags': None, + 'action': 'accept', + }, + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + }, + ], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value('rules[output][0][action]', 'accept') + .expect_form_value('rules[output][1][action]', 'discard') + .expect_form_value_absent('rules[output][2][action]') + .expect_form_value_absent('rules[input][0][action]'), + ]) + assert result['changed'] is True + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 0 + assert len(result['diff']['before']['rules']['output']) == 1 + assert len(result['diff']['after']['rules']['input']) == 0 + assert len(result['diff']['after']['rules']['output']) == 2 + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 2 + + # Idempotency checks: change one value + + @pytest.mark.parametrize("parameter, before, after", flatten([ + create_params('name', None, '', 'Test', 'Test', 'foo', '', None), + create_params('ip_version', 'ipv4', 'ipv4', 'ipv6', 'ipv6'), + create_params('dst_ip', None, '1.2.3.4/24', '1.2.3.4/32', '1.2.3.4/32', None), + create_params('dst_port', None, '80', '80-443', '80-443', None), + create_params('src_ip', None, '1.2.3.4/24', '1.2.3.4/32', '1.2.3.4/32', None), + create_params('src_port', None, '80', '80-443', '80-443', None), + create_params('protocol', None, 'tcp', 'tcp', 'udp', 'udp', None), + create_params('tcp_flags', None, 'syn', 'syn|fin', 'syn|fin', 'syn&fin', '', None), + create_params('action', 'accept', 'accept', 'discard', 'discard'), + ])) + def test_input_rule_value_change(self, mocker, parameter, before, after): + input_call = { + 'ip_version': 'ipv4', + 'action': 'discard', + } + input_before = { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + input_after = { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + if after is not None: + input_call[parameter] = after + input_before[parameter] = before + input_after[parameter] = after + + calls = [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [input_before], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ] + + changed = (before != after) + if changed: + after_call = ( + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [input_after], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[input][1][action]') + ) + if parameter != 'ip_version': + after_call.expect_form_value('rules[input][0][ip_version]', 'ipv4') + if parameter != 'action': + after_call.expect_form_value('rules[input][0][action]', 'discard') + if after is not None: + after_call.expect_form_value('rules[input][0][{0}]'.format(parameter), after) + else: + after_call.expect_form_value_absent('rules[input][0][{0}]'.format(parameter)) + calls.append(after_call) + + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'input': [input_call], + }, + }, calls) + assert result['changed'] == changed + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 1 + assert len(result['diff']['before']['rules']['output']) == 0 + assert len(result['diff']['after']['rules']['input']) == 1 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['diff']['before']['rules']['input'][0][parameter] == before + assert result['diff']['after']['rules']['input'][0][parameter] == after + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 1 + assert result['firewall']['rules']['input'][0][parameter] == after + assert len(result['firewall']['rules']['output']) == 0 + + @pytest.mark.parametrize("parameter, before, after", flatten([ + create_params('name', None, '', 'Test', 'Test', 'foo', '', None), + create_params('ip_version', 'ipv4', 'ipv4', 'ipv6', 'ipv6'), + create_params('dst_ip', None, '1.2.3.4/24', '1.2.3.4/32', '1.2.3.4/32', None), + create_params('dst_port', None, '80', '80-443', '80-443', None), + create_params('src_ip', None, '1.2.3.4/24', '1.2.3.4/32', '1.2.3.4/32', None), + create_params('src_port', None, '80', '80-443', '80-443', None), + create_params('protocol', None, 'tcp', 'tcp', 'udp', 'udp', None), + create_params('tcp_flags', None, 'syn', 'syn|fin', 'syn|fin', 'syn&fin', '', None), + create_params('action', 'accept', 'accept', 'discard', 'discard'), + ])) + def test_output_rule_value_change(self, mocker, parameter, before, after): + output_call = { + 'ip_version': 'ipv4', + 'action': 'discard', + } + output_before = { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + output_after = { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + if after is not None: + output_call[parameter] = after + output_before[parameter] = before + output_after[parameter] = after + + calls = [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'output': [output_before], + 'input': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ] + + changed = (before != after) + if changed: + after_call = ( + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'output': [output_after], + 'input': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[output][1][action]') + .expect_form_value_absent('rules[input][0][action]') + ) + if parameter != 'ip_version': + after_call.expect_form_value('rules[output][0][ip_version]', 'ipv4') + if parameter != 'action': + after_call.expect_form_value('rules[output][0][action]', 'discard') + if after is not None: + after_call.expect_form_value('rules[output][0][{0}]'.format(parameter), after) + else: + after_call.expect_form_value_absent('rules[output][0][{0}]'.format(parameter)) + calls.append(after_call) + + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'input': [], + 'output': [output_call], + }, + }, calls) + assert result['changed'] == changed + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 0 + assert len(result['diff']['before']['rules']['output']) == 1 + assert len(result['diff']['after']['rules']['input']) == 0 + assert len(result['diff']['after']['rules']['output']) == 1 + assert result['diff']['before']['rules']['output'][0][parameter] == before + assert result['diff']['after']['rules']['output'][0][parameter] == after + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 1 + assert result['firewall']['rules']['output'][0][parameter] == after + + # Idempotency checks: IP address normalization + + @pytest.mark.parametrize("ip_version, parameter, before_normalized, after_normalized, after", [ + ('ipv4', 'src_ip', '1.2.3.4/32', '1.2.3.4/32', '1.2.3.4'), + ('ipv6', 'src_ip', '1:2:3::4/128', '1:2:3::4/128', '1:2:3::4'), + ('ipv6', 'dst_ip', '1:2:3::4/128', '1:2:3::4/128', '1:2:3:0::4'), + ('ipv6', 'dst_ip', '::/0', '::/0', '0:0::0/0'), + ('ipv6', 'dst_ip', '::/0', '::1/0', '0:0::0:1/0'), + ('ipv6', 'dst_ip', '::/0', None, None), + ]) + def test_input_rule_ip_normalization(self, mocker, ip_version, parameter, before_normalized, after_normalized, after): + assert ip_version in ('ipv4', 'ipv6') + assert parameter in ('src_ip', 'dst_ip') + input_call = { + 'ip_version': ip_version, + 'action': 'discard', + } + input_before = { + 'name': None, + 'ip_version': ip_version, + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + input_after = { + 'name': None, + 'ip_version': ip_version, + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + if after is not None: + input_call[parameter] = after + input_before[parameter] = before_normalized + input_after[parameter] = after_normalized + + calls = [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [input_before], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ] + + changed = (before_normalized != after_normalized) + if changed: + after_call = ( + FetchUrlCall('POST', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [input_after], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)) + .expect_form_value('status', 'active') + .expect_form_value_absent('rules[input][1][action]') + ) + after_call.expect_form_value('rules[input][0][ip_version]', ip_version) + after_call.expect_form_value('rules[input][0][action]', 'discard') + if after_normalized is None: + after_call.expect_form_value_absent('rules[input][0][{0}]'.format(parameter)) + else: + after_call.expect_form_value('rules[input][0][{0}]'.format(parameter), after_normalized) + calls.append(after_call) + + result = self.run_module_success(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'rules': { + 'input': [input_call], + }, + }, calls) + assert result['changed'] == changed + assert result['diff']['before']['status'] == 'active' + assert result['diff']['after']['status'] == 'active' + assert len(result['diff']['before']['rules']['input']) == 1 + assert len(result['diff']['before']['rules']['output']) == 0 + assert len(result['diff']['after']['rules']['input']) == 1 + assert len(result['diff']['after']['rules']['output']) == 0 + assert result['diff']['before']['rules']['input'][0][parameter] == before_normalized + assert result['diff']['after']['rules']['input'][0][parameter] == after_normalized + assert result['firewall']['status'] == 'active' + assert len(result['firewall']['rules']['input']) == 1 + assert len(result['firewall']['rules']['output']) == 0 + assert result['firewall']['rules']['input'][0][parameter] == after_normalized + + # Missing requirements + + def test_fail_no_ipaddress(self, mocker): + try: + firewall.HAS_IPADDRESS = False + firewall.IPADDRESS_IMP_ERR = 'This is\na traceback' + result = self.run_module_failed(mocker, firewall, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'state': 'present', + 'wait_for_configured': True, + 'timeout': 0, + }, []) + assert result['msg'].startswith('Failed to import the required Python library (ipaddress) on') + assert result['exception'] == 'This is\na traceback' + finally: + firewall.HAS_IPADDRESS = True diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall_info.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall_info.py new file mode 100644 index 000000000..4e0bbdb3c --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_firewall_info.py @@ -0,0 +1,328 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import firewall_info + + +class TestHetznerFirewallInfo(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.firewall_info.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + # Tests for state (absent and present) + + def test_absent(self, mocker): + result = self.run_module_success(mocker, firewall_info, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'server_number': 1, + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['firewall']['filter_ipv6'] is False + assert result['firewall']['allowlist_hos'] is False + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + + def test_absent_no_rules(self, mocker): + result = self.run_module_success(mocker, firewall_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'disabled', + 'whitelist_hos': False, + 'port': 'main', + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['firewall']['filter_ipv6'] is False + assert result['firewall']['status'] == 'disabled' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert 'rules' in result['firewall'] + assert 'input' in result['firewall']['rules'] + assert len(result['firewall']['rules']['input']) == 0 + + def test_present(self, mocker): + result = self.run_module_success(mocker, firewall_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['firewall']['filter_ipv6'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert len(result['firewall']['rules']['input']) == 0 + assert len(result['firewall']['rules']['output']) == 0 + + def test_present_w_rules(self, mocker): + result = self.run_module_success(mocker, firewall_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [ + { + 'name': 'Accept HTTPS traffic', + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': '443', + 'src_ip': None, + 'src_port': None, + 'protocol': 'tcp', + 'tcp_flags': None, + 'action': 'accept', + }, + { + 'name': None, + 'ip_version': 'ipv4', + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'discard', + } + ], + 'output': [ + { + 'name': None, + 'ip_version': None, + 'dst_ip': None, + 'dst_port': None, + 'src_ip': None, + 'src_port': None, + 'protocol': None, + 'tcp_flags': None, + 'action': 'accept', + } + ], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['firewall']['filter_ipv6'] is True + assert result['firewall']['allowlist_hos'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 + assert len(result['firewall']['rules']['input']) == 2 + assert result['firewall']['rules']['input'][0]['name'] == 'Accept HTTPS traffic' + assert result['firewall']['rules']['input'][0]['dst_port'] == '443' + assert result['firewall']['rules']['input'][0]['action'] == 'accept' + assert result['firewall']['rules']['input'][1]['dst_port'] is None + assert result['firewall']['rules']['input'][1]['action'] == 'discard' + assert len(result['firewall']['rules']['output']) == 1 + assert result['firewall']['rules']['output'][0]['name'] is None + assert result['firewall']['rules']['output'][0]['ip_version'] is None + assert result['firewall']['rules']['output'][0]['action'] == 'accept' + + # Tests for wait_for_configured in getting status + + def test_wait_get(self, mocker): + mocker.patch('time.sleep', lambda duration: None) + result = self.run_module_success(mocker, firewall_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 123, + 'wait_for_configured': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 123, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/123'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 123, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/123'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': False, + 'server_ip': '1.2.3.4', + 'server_number': 123, + 'status': 'active', + 'whitelist_hos': True, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/123'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['firewall']['filter_ipv6'] is False + assert result['firewall']['whitelist_hos'] is True + assert result['firewall']['allowlist_hos'] is True + assert result['firewall']['status'] == 'active' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 123 + + def test_wait_get_timeout(self, mocker): + mocker.patch('time.sleep', lambda duration: None) + result = self.run_module_failed(mocker, firewall_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'wait_for_configured': True, + 'timeout': 0, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['msg'] == 'Timeout while waiting for firewall to be configured.' + + def test_nowait_get(self, mocker): + result = self.run_module_success(mocker, firewall_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_ip': '1.2.3.4', + 'wait_for_configured': False, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'firewall': { + 'filter_ipv6': True, + 'server_ip': '1.2.3.4', + 'server_number': 1, + 'status': 'in process', + 'whitelist_hos': False, + 'port': 'main', + 'rules': { + 'input': [], + 'output': [], + }, + }, + }) + .expect_url('{0}/firewall/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['firewall']['status'] == 'in process' + assert result['firewall']['server_ip'] == '1.2.3.4' + assert result['firewall']['server_number'] == 1 diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reset.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reset.py new file mode 100644 index 000000000..55bfdbbb4 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reset.py @@ -0,0 +1,237 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import reset + + +class TestHetznerReset(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.reset.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + def test_check_valid(self, mocker): + result = self.run_module_success(mocker, reset, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'server_number': 23, + 'reset_type': 'software', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json({ + 'reset': { + 'server_ip': '123.123.123.123', + 'server_ipv6_net': '2a01:4f8:111:4221::', + 'server_number': 23, + 'type': [ + 'sw', + 'hw', + 'man' + ], + 'operating_status': 'not supported', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['changed'] is True + + def test_valid(self, mocker): + result = self.run_module_success(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'manual', + }, [ + FetchUrlCall('POST', 200) + .expect_form_value('type', 'man') + .result_json({ + 'reset': { + 'server_ip': '123.123.123.123', + 'server_ipv6_net': '2a01:4f8:111:4221::', + 'server_number': 23, + 'type': 'man', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['changed'] is True + + # Errors + + def test_invalid(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + }, [ + FetchUrlCall('POST', 400) + .expect_form_value('type', 'power') + .result_json({ + 'error': { + 'status': 400, + 'code': 'INVALID_INPUT', + 'message': 'Invalid input parameters', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'The chosen reset method is not supported for this server' + + def test_check_invalid(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'reset': { + 'server_ip': '123.123.123.123', + 'server_ipv6_net': '2a01:4f8:111:4221::', + 'server_number': 23, + 'type': [ + 'sw', + 'hw', + 'man' + ], + 'operating_status': 'not supported', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'The chosen reset method is not supported for this server' + + def test_server_not_found(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + }, [ + FetchUrlCall('POST', 404) + .expect_form_value('type', 'power') + .result_json({ + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'Server not found', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'This server does not exist, or you do not have access rights for it' + + def test_check_server_not_found(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'Server not found', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'This server does not exist, or you do not have access rights for it' + + def test_reset_not_available(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + }, [ + FetchUrlCall('POST', 404) + .expect_form_value('type', 'power') + .result_json({ + 'error': { + 'status': 404, + 'code': 'RESET_NOT_AVAILABLE', + 'message': 'The server has no reset option', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'The server has no reset option available' + + def test_check_reset_not_available(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'RESET_NOT_AVAILABLE', + 'message': 'The server has no reset option', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'The server has no reset option available' + + def test_reset_manual_active(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + }, [ + FetchUrlCall('POST', 409) + .expect_form_value('type', 'power') + .result_json({ + 'error': { + 'status': 409, + 'code': 'RESET_MANUAL_ACTIVE', + 'message': 'There is already a running manual reset', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'A manual reset is already running' + + def test_reset_failed(self, mocker): + result = self.run_module_failed(mocker, reset, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'reset_type': 'power', + }, [ + FetchUrlCall('POST', 500) + .expect_form_value('type', 'power') + .result_json({ + 'error': { + 'status': 500, + 'code': 'RESET_FAILED', + 'message': 'Resetting failed due to an internal error', + }, + }) + .expect_url('{0}/reset/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'The reset failed due to an internal error at Hetzner' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reverse_dns.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reverse_dns.py new file mode 100644 index 000000000..44a3944a7 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_reverse_dns.py @@ -0,0 +1,165 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import reverse_dns + + +class TestHetznerReverseDNS(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.reverse_dns.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + def test_idempotent_present(self, mocker): + result = self.run_module_success(mocker, reverse_dns, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'ip': '1.2.3.4', + 'value': 'foo.example.com', + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json({ + 'rdns': { + 'ip': '1.2.3.4', + 'ptr': 'foo.example.com', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + + def test_idempotent_absent(self, mocker): + result = self.run_module_success(mocker, reverse_dns, { + 'hetzner_user': '', + 'hetzner_password': '', + 'ip': '1.2.3.4', + 'state': 'absent', + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'RDNS_NOT_FOUND', + 'message': 'The IP address 1.2.3.4 has no reverse DNS entry yet', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is False + + def test_set_check_mode(self, mocker): + result = self.run_module_success(mocker, reverse_dns, { + 'hetzner_user': '', + 'hetzner_password': '', + 'ip': '1.2.3.4', + 'value': 'foo.example.com', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'RDNS_NOT_FOUND', + 'message': 'The IP address 1.2.3.4 has no reverse DNS entry yet', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + + def test_set(self, mocker): + result = self.run_module_success(mocker, reverse_dns, { + 'hetzner_user': '', + 'hetzner_password': '', + 'ip': '1.2.3.4', + 'value': 'foo.example.com', + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'RDNS_NOT_FOUND', + 'message': 'The IP address 1.2.3.4 has no reverse DNS entry yet', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_form_value('ptr', 'foo.example.com') + .result_json({ + 'rdns': { + 'ip': '1.2.3.4', + 'ptr': 'foo.example.com', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + + def test_remove_check_mode(self, mocker): + result = self.run_module_success(mocker, reverse_dns, { + 'hetzner_user': '', + 'hetzner_password': '', + 'ip': '1.2.3.4', + 'state': 'absent', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'rdns': { + 'ip': '1.2.3.4', + 'ptr': 'foo.example.com', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + + def test_remove(self, mocker): + result = self.run_module_success(mocker, reverse_dns, { + 'hetzner_user': '', + 'hetzner_password': '', + 'ip': '1.2.3.4', + 'state': 'absent', + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'rdns': { + 'ip': '1.2.3.4', + 'ptr': 'foo.example.com', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['changed'] is True + + def test_bad_ip(self, mocker): + result = self.run_module_failed(mocker, reverse_dns, { + 'hetzner_user': '', + 'hetzner_password': '', + 'ip': '1.2.3.4', + 'value': 'foo.example.com', + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'IP_NOT_FOUND', + 'message': 'The IP address 1.2.3.4 was not found', + }, + }) + .expect_url('{0}/rdns/1.2.3.4'.format(BASE_URL)), + ]) + assert result['msg'] == 'The IP address was not found' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server.py new file mode 100644 index 000000000..b69d5d178 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server.py @@ -0,0 +1,160 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import server + + +def create_server_data(server_name): + return { + 'server': { + 'cancelled': False, + 'cpanel': False, + 'dc': 'NBG1-DC1', + 'hot_swap': True, + 'ip': [ + '1.2.3.4', + ], + 'linked_storagebox': None, + 'paid_until': '2021-12-31', + 'plesk': False, + 'product': 'EX41', + 'rescue': True, + 'reset': True, + 'server_ip': '1.2.3.4', + 'server_ipv6_net': '2a01:1:2:3::', + 'server_name': server_name, + 'server_number': 23, + 'status': 'ready', + 'subnet': [ + { + 'ip': '2a01:1:2:3::', + 'mask': '64', + }, + ], + 'traffic': 'unlimited', + 'vnc': True, + 'windows': False, + 'wol': True, + }, + } + + +class TestHetznerServer(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.server.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + def test_idempotent_not_specified(self, mocker): + result = self.run_module_success(mocker, server, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'server_number': 23, + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_server_data('foo')) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['server'] == create_server_data('foo')['server'] + + def test_idempotent(self, mocker): + result = self.run_module_success(mocker, server, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'server_name': 'foo', + }, [ + FetchUrlCall('GET', 200) + .result_json(create_server_data('foo')) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['server'] == create_server_data('foo')['server'] + + def test_change_check_mode(self, mocker): + result = self.run_module_success(mocker, server, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'server_name': 'bar', + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(create_server_data('foo')) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['server'] == create_server_data('bar')['server'] + + def test_change(self, mocker): + result = self.run_module_success(mocker, server, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'server_name': 'bar', + }, [ + FetchUrlCall('GET', 200) + .result_json(create_server_data('foo')) + .expect_url('{0}/server/23'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_form_value('server_name', 'bar') + .result_json(create_server_data('bar')) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['server'] == create_server_data('bar')['server'] + + # Errors + + def test_server_not_found(self, mocker): + result = self.run_module_failed(mocker, server, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'Server not found', + }, + }) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'This server does not exist, or you do not have access rights for it' + + def test_invalid_input(self, mocker): + result = self.run_module_failed(mocker, server, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'server_name': 'bar', + }, [ + FetchUrlCall('GET', 200) + .result_json(create_server_data('foo')) + .expect_url('{0}/server/23'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_form_value('server_name', 'bar') + .result_json({ + 'error': { + 'status': 400, + 'code': 'INVALID_INPUT', + 'message': 'Invalid input parameters', + }, + }) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['msg'] == 'The values to update were invalid ({"server_name": "bar"})' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server_info.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server_info.py new file mode 100644 index 000000000..9a9c715d0 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_server_info.py @@ -0,0 +1,297 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import server_info + + +SERVER_MINIMUM_DATA = [ + { + 'server': { + 'cancelled': False, + 'dc': 'NBG1-DC1', + 'ip': [ + '1.2.3.4', + ], + 'linked_storagebox': None, + 'paid_until': '2021-12-31', + 'product': 'EX41', + 'server_ip': '1.2.3.4', + 'server_ipv6_net': '2a01:1:2:3::', + 'server_name': 'foo', + 'server_number': 23, + 'status': 'ready', + 'subnet': [ + { + 'ip': '2a01:1:2:3::', + 'mask': '64', + }, + ], + 'traffic': 'unlimited', + }, + }, + { + 'server': { + 'cancelled': True, + 'dc': 'NBG1-DC2', + 'ip': [ + '1.2.3.5', + ], + 'linked_storagebox': 12345, + 'paid_until': '2021-11-30', + 'product': 'EX41', + 'server_ip': '1.2.3.5', + 'server_ipv6_net': '2a01:1:5:3::', + 'server_name': 'bar', + 'server_number': 42, + 'status': 'in process', + 'subnet': [ + { + 'ip': '2a01:1:5:3::', + 'mask': '64', + }, + ], + 'traffic': '1 TB', + }, + }, +] + + +SERVER_DETAIL_DATA = { + 23: { + 'server': { + 'cancelled': False, + 'cpanel': False, + 'dc': 'NBG1-DC1', + 'hot_swap': True, + 'ip': [ + '1.2.3.4', + ], + 'linked_storagebox': None, + 'paid_until': '2021-12-31', + 'plesk': False, + 'product': 'EX41', + 'rescue': True, + 'reset': True, + 'server_ip': '1.2.3.4', + 'server_ipv6_net': '2a01:1:2:3::', + 'server_name': 'foo', + 'server_number': 23, + 'status': 'ready', + 'subnet': [ + { + 'ip': '2a01:1:2:3::', + 'mask': '64', + }, + ], + 'traffic': 'unlimited', + 'vnc': True, + 'windows': False, + 'wol': True, + }, + }, + 42: { + 'server': { + 'cancelled': True, + 'cpanel': False, + 'dc': 'NBG1-DC2', + 'hot_swap': True, + 'ip': [ + '1.2.3.5', + ], + 'linked_storagebox': 12345, + 'paid_until': '2021-11-30', + 'plesk': False, + 'product': 'EX41', + 'rescue': False, + 'reset': False, + 'server_ip': '1.2.3.5', + 'server_ipv6_net': '2a01:1:5:3::', + 'server_name': 'bar', + 'server_number': 42, + 'status': 'in process', + 'subnet': [ + { + 'ip': '2a01:1:5:3::', + 'mask': '64', + }, + ], + 'traffic': '1 TB', + 'vnc': False, + 'windows': True, + 'wol': False, + }, + }, +} + + +class TestHetznerServerInfo(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.server_info.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + def test_server_number(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'server_number': 23, + }, [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(SERVER_DETAIL_DATA[23]) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 1 + assert result['servers'][0] == SERVER_DETAIL_DATA[23]['server'] + + def test_server_number_name_match(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'server_name': 'foo', + }, [ + FetchUrlCall('GET', 200) + .result_json(SERVER_DETAIL_DATA[23]) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 1 + assert result['servers'][0] == SERVER_DETAIL_DATA[23]['server'] + + def test_server_number_name_mismatch(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 23, + 'server_name': 'bar', + }, [ + FetchUrlCall('GET', 200) + .result_json(SERVER_DETAIL_DATA[23]) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 0 + + def test_server_number_unknown(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_number': 1, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'server not found', + }, + }) + .expect_url('{0}/server/1'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 0 + + def test_server_all(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + }, [ + FetchUrlCall('GET', 200) + .result_json(SERVER_MINIMUM_DATA) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 2 + assert result['servers'][0] == SERVER_MINIMUM_DATA[0]['server'] + assert result['servers'][1] == SERVER_MINIMUM_DATA[1]['server'] + + def test_server_name(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_name': 'foo', + }, [ + FetchUrlCall('GET', 200) + .result_json(SERVER_MINIMUM_DATA) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 1 + assert result['servers'][0] == SERVER_MINIMUM_DATA[0]['server'] + + def test_server_name_full_info(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_name': 'foo', + 'full_info': True, + }, [ + FetchUrlCall('GET', 200) + .result_json(SERVER_MINIMUM_DATA) + .expect_url('{0}/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .result_json(SERVER_DETAIL_DATA[23]) + .expect_url('{0}/server/23'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 1 + assert result['servers'][0] == SERVER_DETAIL_DATA[23]['server'] + + def test_server_name_unknown(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_name': 'baz', + }, [ + FetchUrlCall('GET', 200) + .result_json(SERVER_MINIMUM_DATA) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 0 + + def test_server_name_none(self, mocker): + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_name': 'foo', + }, [ + FetchUrlCall('GET', 200) + .result_json([]) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 0 + + def test_server_name_none_error(self, mocker): + # According to the API docs, when no server is found this API can return 404. + # I haven't seen that in RL though... + result = self.run_module_success(mocker, server_info, { + 'hetzner_user': '', + 'hetzner_password': '', + 'server_name': 'foo', + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'server not found', + }, + }) + .expect_url('{0}/server'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert len(result['servers']) == 0 diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key.py new file mode 100644 index 000000000..670323db5 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key.py @@ -0,0 +1,452 @@ +# Copyright (c) 2021 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +import pytest + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import ssh_key + + +# Key generated with `ssh-keygen -t rsa -b 4096 -f test`, fingerprint with `ssh-keygen -lf test.pub -E md5`` +PUBLIC_KEY_1 = ( + 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC7g+C+gXspRfsNRFXHSeEuQLrUEb+pSV9OUi3zz0DvdxzaXyP4I1vUErnwll5P5' + '8KFdkWp65haqiGteM53zuGJa251c+J41Y69jLEI0jX4mGj4BskB0Cud23lnVzYTktzjkwGz2tGlRjaSYzYdm9lR3Nf6rlWBP1iz6C' + 'QasBHVLGWUBuJF+DQ16ztHV9EWtifDprVoMHK5EaGW19W5OCW73sPJfvbdDjolTZC6QZ7lKOGcZjdFBM7nnIyfIHYfjnXPZh9eMnY' + '6KWEAKuhQpPO1SB82PrLvBPlYzNewO1BiOQWoJyJfJBr1vRBfhLzY9VAoNr5fDSUxtn3UmZ2OmcNCx+qb8iUrn+E3K3i4sRn5iYVA' + 'dO4pmsjx5SENXlfpj/Mmz6wu3bQGN5k1jYtq+sKxGuIRiX+9sxEQ1KBXIqMfM1zSzitxGQSGUrqEgWpxJKVmDscGnlZBGGTPvPRwX' + 'i3VLeiTH+AkGOnWrlVenKpBh/0IWPI8fN/d7GolWHT53Cyi0HQbb3nKMUlfXWFKukbdSb9mvJ0v1Pv8qlWb6+fDZCBi0hz/fmE+hx' + '/+uwnY9Vk8H5CzTDQOmXKx6Gj3Lff9RSWD/WePW8LyukWz0l18GOGWzv/HqNIVtljdfJMa5v2kckhZAFPxQvZBMUIX0wkRTmGJOcQ' + '+A8ZKOVaScMnXXQ==' +) +FINGERPRINT_1 = 'e4:47:42:71:81:62:bf:06:1c:23:fa:f3:8f:7b:6f:d0' +TYPE_1 = 'RSA' +SIZE_1 = 4096 + + +class TestHetznerSSHKey(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.ssh_key.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + # Absent with fingerprint + + def test_absent_fp(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'state': 'absent', + 'fingerprint': FINGERPRINT_1, + }, [ + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_absent_fp_idempotent(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'fingerprint': FINGERPRINT_1, + }, [ + FetchUrlCall('DELETE', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'Key not found', + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is False + assert result['fingerprint'] == FINGERPRINT_1 + + def test_absent_fp_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'fingerprint': FINGERPRINT_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'key': { + 'name': 'My Test Key', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_absent_fp_idempotent_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'fingerprint': FINGERPRINT_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'Key not found', + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is False + assert result['fingerprint'] == FINGERPRINT_1 + + # Absent with public key + + def test_absent_key(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'public_key': PUBLIC_KEY_1, + }, [ + FetchUrlCall('DELETE', 200) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_absent_key_idempotent(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'public_key': PUBLIC_KEY_1, + }, [ + FetchUrlCall('DELETE', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'Key not found', + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is False + assert result['fingerprint'] == FINGERPRINT_1 + + def test_absent_key_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'public_key': PUBLIC_KEY_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'key': { + 'name': 'My Test Key', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_absent_key_idempotent_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'absent', + 'public_key': PUBLIC_KEY_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'Key not found', + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is False + assert result['fingerprint'] == FINGERPRINT_1 + + # Present + + def test_present_create_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'foo', + 'public_key': PUBLIC_KEY_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'Key not found', + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_present_create(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'foo', + 'public_key': PUBLIC_KEY_1, + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'Key not found', + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + FetchUrlCall('POST', 200) + .expect_form_value('name', 'foo') + .expect_form_value('data', PUBLIC_KEY_1) + .result_json({ + 'key': { + 'name': 'foo', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key'.format(BASE_URL)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_present_idempotent_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'foo', + 'public_key': PUBLIC_KEY_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'key': { + 'name': 'foo', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is False + assert result['fingerprint'] == FINGERPRINT_1 + + def test_present_idempotent(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'foo', + 'public_key': PUBLIC_KEY_1, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'key': { + 'name': 'foo', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is False + assert result['fingerprint'] == FINGERPRINT_1 + + def test_present_change_check_mode(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'bar', + 'public_key': PUBLIC_KEY_1, + '_ansible_check_mode': True, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'key': { + 'name': 'foo', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + def test_present_change(self, mocker): + result = self.run_module_success(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'bar', + 'public_key': PUBLIC_KEY_1, + }, [ + FetchUrlCall('GET', 200) + .result_json({ + 'key': { + 'name': 'foo', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + FetchUrlCall('POST', 200) + .expect_form_value('name', 'bar') + .expect_form_value_absent('data') + .result_json({ + 'key': { + 'name': 'bar', + 'fingerprint': FINGERPRINT_1, + 'type': TYPE_1, + 'size': SIZE_1, + 'data': PUBLIC_KEY_1, + }, + }) + .expect_url('{0}/key/{1}'.format(BASE_URL, FINGERPRINT_1)), + ]) + assert result['changed'] is True + assert result['fingerprint'] == FINGERPRINT_1 + + # Error + + def test_invalid_public_key(self, mocker): + result = self.run_module_failed(mocker, ssh_key, { + 'hetzner_user': '', + 'hetzner_password': '', + 'state': 'present', + 'name': 'bar', + 'public_key': 'asdf', + }, []) + assert result['msg'] == 'Error while extracting fingerprint from public key data: cannot split public key into at least two parts' + + +def test_normalize_fingerprint(): + assert ssh_key.normalize_fingerprint(FINGERPRINT_1) == FINGERPRINT_1 + assert ssh_key.normalize_fingerprint('F5:7e:4f:d8:ab:20:b8:5B:8b:2f:7a:4:47:fd:96:73') == ( + 'f5:7e:4f:d8:ab:20:b8:5b:8b:2f:7a:04:47:fd:96:73' + ) + assert ssh_key.normalize_fingerprint('F57e4fd8ab20b85B8b2f7a0447fd9673') == ( + 'f5:7e:4f:d8:ab:20:b8:5b:8b:2f:7a:04:47:fd:96:73' + ) + assert ssh_key.normalize_fingerprint('Fe:F', size=2) == 'fe:0f' + + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.normalize_fingerprint('') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Fingerprint must consist of 16 8-bit hex numbers: got 0 8-bit hex numbers instead' + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.normalize_fingerprint('1:2:3') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Fingerprint must consist of 16 8-bit hex numbers: got 3 8-bit hex numbers instead' + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.normalize_fingerprint('01023') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Fingerprint must consist of 16 8-bit hex numbers: got 3 8-bit hex numbers instead' + + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.normalize_fingerprint('A:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Fingerprint must consist of 16 8-bit hex numbers: number 7 is invalid: "G"' + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.normalize_fingerprint('fee:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Fingerprint must consist of 16 8-bit hex numbers: number 1 is invalid: "fee"' + + +def test_extract_fingerprint(): + assert ssh_key.extract_fingerprint(PUBLIC_KEY_1) == FINGERPRINT_1 + assert ssh_key.extract_fingerprint(' %s foo@ bar ' % PUBLIC_KEY_1.replace(' ', ' ')) == FINGERPRINT_1 + + key = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGGdztn98LzAZkwHzSNa2HpTERPzBZdrdMt9u++0qQ+U' + assert ssh_key.extract_fingerprint(key) == 'f5:7e:4f:d8:ab:20:b8:5b:8b:2f:7a:04:47:fd:96:73' + print(ssh_key.extract_fingerprint(key, alg='sha256', size=32)) + assert ssh_key.extract_fingerprint(key, alg='sha256', size=32) == ( + '64:94:70:47:7a:bd:79:99:95:9f:3b:d3:37:8c:2c:fa:33:a7:d1:93:95:56:1b:f7:f6:52:31:34:0b:4a:fc:67' + ) + + key = ( + 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDEVarUR' + 'tu+DmCvn0OkHC+gCOQ6Bxkolfh9NvWr4f8SPfQJ/yOUO6RZ+m3RhvnDEWAvA1BG/lCNqui6/kuZiyVk=' + ) + assert ssh_key.extract_fingerprint(key) == 'f4:b7:43:14:fe:8b:43:4b:cc:b3:63:dc:cf:23:bb:cb' + print(ssh_key.extract_fingerprint(key, alg='sha256', size=32)) + assert ssh_key.extract_fingerprint(key, alg='sha256', size=32) == ( + '88:c2:a3:0f:2a:cf:60:73:7c:52:e0:41:40:25:c3:d4:5d:32:37:a9:46:48:3e:37:34:f1:aa:0d:4d:69:15:d7' + ) + + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.extract_fingerprint(' adsf ') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Error while extracting fingerprint from public key data: cannot split public key into at least two parts' + + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.extract_fingerprint('a b') + print(exc.value.args[0]) + assert exc.value.args[0] in ( + 'Error while extracting fingerprint from public key data: Invalid base64-encoded string:' + ' number of data characters (1) cannot be 1 more than a multiple of 4', + 'Error while extracting fingerprint from public key data: Incorrect padding', + ) + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.extract_fingerprint('a ab=f') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Error while extracting fingerprint from public key data: Incorrect padding' + with pytest.raises(ssh_key.FingerprintError) as exc: + ssh_key.extract_fingerprint('a ab==', alg='foo bar') + print(exc.value.args[0]) + assert exc.value.args[0] == 'Hash algorithm FOO BAR is not available. Possibly running in FIPS mode.' diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key_info.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key_info.py new file mode 100644 index 000000000..bc755502b --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_ssh_key_info.py @@ -0,0 +1,80 @@ +# Copyright (c) 2021 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import ssh_key_info + + +class TestHetznerSSHKeyInfo(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = 'ansible_collections.community.hrobot.plugins.modules.ssh_key_info.AnsibleModule' + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + + def test_no_keys(self, mocker): + result = self.run_module_success(mocker, ssh_key_info, { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + }, [ + FetchUrlCall('GET', 200) + .result_json([]) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_url('{0}/key'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['ssh_keys'] == [] + + def test_no_keys_404(self, mocker): + result = self.run_module_success(mocker, ssh_key_info, { + 'hetzner_user': '', + 'hetzner_password': '', + }, [ + FetchUrlCall('GET', 404) + .result_json({ + 'error': { + 'status': 404, + 'code': 'NOT_FOUND', + 'message': 'No keys found', + }, + }) + .expect_url('{0}/key'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['ssh_keys'] == [] + + def test_single_key(self, mocker): + result = self.run_module_success(mocker, ssh_key_info, { + 'hetzner_user': '', + 'hetzner_password': '', + }, [ + FetchUrlCall('GET', 200) + .result_json([ + { + 'key': { + 'name': 'key1', + 'fingerprint': '56:29:99:a4:5d:ed:ac:95:c1:f5:88:82:90:5d:dd:10', + 'type': 'ECDSA', + 'size': 521, + 'data': 'ecdsa-sha2-nistp521 AAAAE2VjZHNh ...' + }, + }, + ]) + .expect_url('{0}/key'.format(BASE_URL)), + ]) + assert result['changed'] is False + assert result['ssh_keys'] == [{ + 'name': 'key1', + 'fingerprint': '56:29:99:a4:5d:ed:ac:95:c1:f5:88:82:90:5d:dd:10', + 'type': 'ECDSA', + 'size': 521, + 'data': 'ecdsa-sha2-nistp521 AAAAE2VjZHNh ...' + }] diff --git a/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_v_switch.py b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_v_switch.py new file mode 100644 index 000000000..5cc3c0c4e --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/plugins/modules/test_v_switch.py @@ -0,0 +1,1123 @@ +# Copyright (c) 2019 Felix Fontein +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +from datetime import datetime + +from ansible_collections.community.internal_test_tools.tests.unit.utils.fetch_url_module_framework import ( + FetchUrlCall, + BaseTestModule, +) + +from ansible_collections.community.hrobot.plugins.module_utils.robot import BASE_URL +from ansible_collections.community.hrobot.plugins.modules import v_switch + + +# pylint: disable=dangerous-default-value +# we are not mutating this value +def create_v_switch_data(vlan, name, server=[]): + return { + 'id': 4321, + 'name': name, + 'vlan': vlan, + 'cancelled': False, + 'server': server, + 'subnet': [], + 'cloud_network': [], + } + + +def create_v_switches_data(vlan, name): + return [ + { + 'id': 4321, + 'name': name, + 'vlan': vlan, + 'cancelled': False, + } + ] + + +def create_server_data(ip, id_, status='ready'): + return { + 'server_ip': ip, + 'server_ipv6_net': '2a01:4f8:111:4221::', + 'server_number': id_, + 'status': status, + } + + +class TestHetznerVSwitch(BaseTestModule): + MOCK_ANSIBLE_MODULEUTILS_BASIC_ANSIBLEMODULE = ( + 'ansible_collections.community.hrobot.plugins.modules.v_switch.AnsibleModule' + ) + MOCK_ANSIBLE_MODULEUTILS_URLS_FETCH_URL = ( + 'ansible_collections.community.hrobot.plugins.module_utils.robot.fetch_url' + ) + + def test_idempotent(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + assert result['changed'] is False + assert result['v_switch'] == create_v_switch_data(4010, 'foo') + + def test_create(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json([]) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + ], + ) + assert result['changed'] is True + assert result['v_switch'] == create_v_switch_data(4010, 'foo') + + def test_v_switch_different_name(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'not_matching_name', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'not_matching_name')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + ], + ) + assert result['changed'] is True + assert result['v_switch'] == create_v_switch_data(4010, 'not_matching_name') + + def test_v_switch_unauthorized_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': '', + 'hetzner_password': '', + 'vlan': 4010, + 'name': 'foo', + }, + [ + FetchUrlCall('GET', 401) + .result_json( + { + 'error': { + 'status': 401, + 'code': 'UNAUTHORIZED', + 'message': 'Unauthorized', + }, + } + ) + .expect_url('{0}/vswitch'.format(BASE_URL)), + ], + ) + assert result['msg'] == 'Please check your current user and password configuration' + + def test_v_switch_limit_reached_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4000, + 'name': 'new vswitch', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('POST', 409) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + { + 'error': { + 'status': 409, + 'code': 'VSWITCH_LIMIT_REACHED', + 'message': 'The maximum count of vSwitches is reached', + }, + } + ) + .expect_url('{0}/vswitch'.format(BASE_URL)), + ], + ) + assert result['msg'] == 'The maximum count of vSwitches is reached' + + def test_v_switch_invalid_input_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 40100, + 'name': 'foo', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('POST', 400) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + { + 'error': { + 'status': 400, + 'code': 'INVALID_INPUT', + 'message': 'invalid input', + 'missing': None, + 'invalid': ['vlan'], + }, + } + ) + .expect_url('{0}/vswitch'.format(BASE_URL)), + ], + ) + assert result['msg'] == "vSwitch invalid parameter (['vlan'])" + + def test_delete(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'state': 'absent', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('cancellation_date', datetime.now().strftime('%y-%m-%d')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['changed'] is True + + def test_create_with_server(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json([]) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('POST', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321)], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['v_switch'] == create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + assert result['changed'] is True + + def test_is_all_servers_ready(self): + result = v_switch.is_all_servers_ready( + create_v_switch_data( + 4010, + 'foo', + server=[], + ), + None, + ) + assert result is True + + result = v_switch.is_all_servers_ready( + create_v_switch_data( + 4010, + 'foo', + server=[ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ], + ), + None, + ) + assert result is True + + result = v_switch.is_all_servers_ready( + create_v_switch_data( + 4010, + 'foo', + server=[ + create_server_data('123.123.123.123', 321, status='in process'), + create_server_data('123.123.123.124', 322), + ], + ), + None, + ) + assert result is False + + def test_get_servers_to_delete(self): + current_servers = [ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ] + desired_servers = ['321'] + result = v_switch.get_servers_to_delete(current_servers, desired_servers) + assert result == ['123.123.123.124'] + + current_servers = [ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ] + desired_servers = [] + result = v_switch.get_servers_to_delete(current_servers, desired_servers) + assert result == ['123.123.123.123', '123.123.123.124'] + + current_servers = [ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ] + desired_servers = ['123.123.123.123'] + result = v_switch.get_servers_to_delete(current_servers, desired_servers) + assert result == ['123.123.123.124'] + + current_servers = [ + create_server_data('check_default_ipv6', 321), + ] + desired_servers = ['2a01:4f8:111:4221::'] + result = v_switch.get_servers_to_delete(current_servers, desired_servers) + assert result == [] + + current_servers = [] + desired_servers = ['123.123.123.123'] + result = v_switch.get_servers_to_delete(current_servers, desired_servers) + assert result == [] + + def test_get_servers_to_add(self): + current_servers = [ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ] + desired_servers = ['321'] + result = v_switch.get_servers_to_add(current_servers, desired_servers) + assert result == [] + + current_servers = [ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ] + desired_servers = [] + result = v_switch.get_servers_to_add(current_servers, desired_servers) + assert result == [] + + current_servers = [ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ] + desired_servers = ['123.123.123.123'] + result = v_switch.get_servers_to_add(current_servers, desired_servers) + assert result == [] + + current_servers = [ + create_server_data('check_default_ipv6', 321), + ] + desired_servers = ['2a01:4f8:111:4221::'] + result = v_switch.get_servers_to_add(current_servers, desired_servers) + assert result == [] + + current_servers = [] + desired_servers = ['123.123.123.123'] + result = v_switch.get_servers_to_add(current_servers, desired_servers) + assert result == ['123.123.123.123'] + + current_servers = [create_server_data('123.123.123.123', 321)] + desired_servers = ['321', '322'] + result = v_switch.get_servers_to_add(current_servers, desired_servers) + assert result == ['322'] + + def test_add_server(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321)], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['v_switch'] == create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + assert result['changed'] is True + + def test_add_server_no_wait(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + 'wait': False, + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321, status='in process')], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['v_switch'] == create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321, status='in process')] + ) + assert result['changed'] is True + + def test_add_multiple_servers(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123', '123.123.123.124'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[0]', '123.123.123.123') + .expect_form_value('server[1]', '123.123.123.124') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['v_switch'] == create_v_switch_data( + 4010, + 'foo', + server=[ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ], + ) + assert result['changed'] is True + + def test_add_server_timeout_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + 'timeout': 0, + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321, status='in process')], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321, status='in process')], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['msg'] == "Timeout waiting vSwitch operation to finish" + + def test_add_server_idempotent(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + assert result['v_switch'] == create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + assert result['changed'] is False + + def test_add_server_server_not_found_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .result_json( + { + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'server "123.123.123.123" not found', + }, + } + ) + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + ], + ) + assert result['msg'] == 'server "123.123.123.123" not found' + + def test_add_server_vlan_not_unique_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .result_json( + { + 'error': { + 'status': 409, + 'code': 'VSWITCH_VLAN_NOT_UNIQUE', + 'message': 'vlan of vswitch is already in use at server EX62-NVMe (123.123.123.123) example.com, please change vlan', + }, + } + ) + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + ], + ) + assert ( + result['msg'] + == "vlan of vswitch is already in use at server EX62-NVMe (123.123.123.123) example.com, please change vlan" + ) + + def test_add_server_vswitch_in_process_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .result_json( + { + 'error': { + 'status': 409, + 'code': 'VSWITCH_IN_PROCESS', + 'message': 'There is a update running, therefore the vswitch can not be updated', + }, + } + ) + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + ], + ) + assert ( + result['msg'] == "There is a update running, therefore the vswitch can not be updated" + ) + + def test_add_server_server_limit_reached_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['123.123.123.123'], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switch_data(4010, 'foo')) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('POST', 201) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .result_json( + { + 'error': { + 'status': 409, + 'code': 'VSWITCH_SERVER_LIMIT_REACHED', + 'message': 'The maximum number of servers is reached for this vSwitch', + }, + } + ) + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + ], + ) + assert result['msg'] == "The maximum number of servers is reached for this vSwitch" + + def test_not_delete_if_servers_not_defined(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + assert result['v_switch'] == create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + assert result['changed'] is False + + def test_delete_server(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': [], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['v_switch'] == create_v_switch_data(4010, 'foo') + assert result['changed'] is True + + def test_delete_server_wait(self, mocker): + result = self.run_module_success( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': ['321'], + 'timeout': 0, + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322), + ], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.124') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[ + create_server_data('123.123.123.123', 321), + create_server_data('123.123.123.124', 322, status='in process'), + ], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + + assert result['v_switch'] == create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + assert result['changed'] is True + + def test_delete_server_timeout_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': [], + 'timeout': 0, + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321, status='in process')], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, + 'foo', + server=[create_server_data('123.123.123.123', 321, status='in process')], + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + ], + ) + assert result['msg'] == "Timeout waiting vSwitch operation to finish" + + def test_delete_server_server_not_found(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': [], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .result_json( + { + 'error': { + 'status': 404, + 'code': 'SERVER_NOT_FOUND', + 'message': 'server "123.123.123.123" not found', + }, + } + ) + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + ], + ) + assert result['msg'] == 'server "123.123.123.123" not found' + + def test_delete_server_in_process_error(self, mocker): + result = self.run_module_failed( + mocker, + v_switch, + { + 'hetzner_user': 'test', + 'hetzner_password': 'hunter2', + 'vlan': 4010, + 'name': 'foo', + 'servers': [], + }, + [ + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json(create_v_switches_data(4010, 'foo')) + .expect_url('{0}/vswitch'.format(BASE_URL)), + FetchUrlCall('GET', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .result_json( + create_v_switch_data( + 4010, 'foo', server=[create_server_data('123.123.123.123', 321)] + ) + ) + .expect_url('{0}/vswitch/4321'.format(BASE_URL)), + FetchUrlCall('DELETE', 200) + .expect_basic_auth('test', 'hunter2') + .expect_force_basic_auth(True) + .expect_form_value('server[]', '123.123.123.123') + .result_json( + { + 'error': { + 'status': 409, + 'code': 'VSWITCH_IN_PROCESS', + 'message': 'There is a update running, therefore the vswitch can not be updated', + }, + } + ) + .expect_url('{0}/vswitch/4321/server'.format(BASE_URL)), + ], + ) + assert ( + result['msg'] == "There is a update running, therefore the vswitch can not be updated" + ) diff --git a/ansible_collections/community/hrobot/tests/unit/requirements.txt b/ansible_collections/community/hrobot/tests/unit/requirements.txt new file mode 100644 index 000000000..34f5b5023 --- /dev/null +++ b/ansible_collections/community/hrobot/tests/unit/requirements.txt @@ -0,0 +1,9 @@ +# Copyright (c) Ansible Project +# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) +# SPDX-License-Identifier: GPL-3.0-or-later + +unittest2 ; python_version < '2.7' +importlib ; python_version < '2.7' + +# firewall module +ipaddress ; python_version < '3.3' -- cgit v1.2.3