diff options
Diffstat (limited to 'ansible_collections/community/zabbix')
255 files changed, 17770 insertions, 21132 deletions
diff --git a/ansible_collections/community/zabbix/.github/workflows/agent.yml b/ansible_collections/community/zabbix/.github/workflows/agent.yml index 86e377eaf..ca04f5843 100644 --- a/ansible_collections/community/zabbix/.github/workflows/agent.yml +++ b/ansible_collections/community/zabbix/.github/workflows/agent.yml @@ -15,46 +15,38 @@ on: - ".github/workflows/agent.yml" jobs: molecule: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: - molecule_distro: - - container: centos8 - image: geerlingguy/docker-rockylinux8-ansible:latest - - container: centos7 - image: geerlingguy/docker-centos7-ansible:latest - - container: fedora32 - image: geerlingguy/docker-fedora32-ansible:latest - - container: ubuntu2004 - image: geerlingguy/docker-ubuntu2004-ansible - - container: pgsql-ubuntu1804 - image: geerlingguy/docker-ubuntu1804-ansible - - container: debian11 - image: geerlingguy/docker-debian11-ansible - - container: debian10 - image: geerlingguy/docker-debian10-ansible - - container: debian9 - image: geerlingguy/docker-debian9-ansible + container: + - rockylinux9 + - rockylinux8 + - ubuntu2204 + - ubuntu2004 + - ubuntu1804 + - debian12 + - debian11 + - debian10 + version: + - v64 + - v62 + - v60 scenario_name: - default - autopsk - agent2 - agent2autopsk - exclude: # zabbix-agent2 is not supported on debian8 - - molecule_distro: - container: debian8 - scenario_name: agent2 - - molecule_distro: - container: debian8 - scenario_name: agent2autopsk + exclude: + - container: debian12 + version: v62 steps: - name: Check out code - uses: actions/checkout@v1 + uses: actions/checkout@v4 - name: Set up Python 3.9 - uses: actions/setup-python@v1 + uses: actions/setup-python@v4 with: python-version: 3.9 @@ -77,7 +69,8 @@ jobs: - name: Run role tests working-directory: molecule/zabbix_agent_tests run: >- - MY_MOLECULE_CONTAINER=${{ matrix.molecule_distro.container }} - MY_MOLECULE_IMAGE=${{ matrix.molecule_distro.image }} - MY_MOLECULE_DOCKER_COMMAND=${{ matrix.molecule_distro.command }} - molecule -c common/molecule.yml test -s ${{ matrix.scenario_name }} + MY_MOLECULE_CONTAINER=${{ matrix.container }} + MY_MOLECULE_IMAGE=${{ matrix.container }} + MY_MOLECULE_VERSION=${{ matrix.version }} + MY_MOLECULE_DOCKER_COMMAND=${{ matrix.command }} + molecule -c common/molecule.yml test -s ${{ matrix.scenario_name }}
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/.github/workflows/javagateway.yml b/ansible_collections/community/zabbix/.github/workflows/javagateway.yml index 2c84dcf1f..bd6885ef7 100644 --- a/ansible_collections/community/zabbix/.github/workflows/javagateway.yml +++ b/ansible_collections/community/zabbix/.github/workflows/javagateway.yml @@ -3,37 +3,51 @@ name: "community.zabbix.zabbix_javagateway" on: push: paths: - - 'roles/zabbix_javagateway/**' - - 'molecule/zabbix_javagateway/**' - - 'molecule/requirements.txt' - - '.github/workflows/javagateway.yml' + - "roles/zabbix_javagateway/**" + - "molecule/zabbix_javagateway/**" + - "molecule/requirements.txt" + - ".github/workflows/javagateway.yml" pull_request: paths: - - 'roles/zabbix_javagateway/**' - - 'molecule/zabbix_javagateway/**' - - 'molecule/requirements.txt' - - '.github/workflows/javagateway.yml' + - "roles/zabbix_javagateway/**" + - "molecule/zabbix_javagateway/**" + - "molecule/requirements.txt" + - ".github/workflows/javagateway.yml" jobs: molecule: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: - molecule_distro: - - container: centos - image: geerlingguy/docker-centos8-ansible:latest - - container: ubuntu - image: geerlingguy/docker-ubuntu2004-ansible - - container: debian - image: geerlingguy/docker-debian10-ansible + container: + - rockylinux9 + - rockylinux8 + - centos7 + - ubuntu2204 + - ubuntu2004 + - ubuntu1804 + - debian12 + - debian11 + - debian10 + version: + - v64 + - v62 + - v60 + include: + - interpreter: python3 + - interpreter: python + container: centos7 + exclude: + - container: debian12 + version: v62 collection_role: - zabbix_javagateway steps: - name: Check out code - uses: actions/checkout@v1 + uses: actions/checkout@v4 - name: Set up Python 3.9 - uses: actions/setup-python@v1 + uses: actions/setup-python@v4 with: python-version: 3.9 @@ -50,10 +64,11 @@ jobs: - name: Install the collection run: ansible-galaxy collection install $COLLECTION_FILE - - name: Run role tests + - name: Run server role tests run: >- - MY_MOLECULE_CONTAINER=${{ matrix.molecule_distro.container }} - MY_MOLECULE_IMAGE=${{ matrix.molecule_distro.image }} - MY_MOLECULE_GROUP=${{ matrix.molecule_distro.group }} - MY_MOLECULE_DOCKER_COMMAND=${{ matrix.molecule_distro.command }} + MY_MOLECULE_CONTAINER=${{ matrix.container }} + MY_MOLECULE_IMAGE=${{ matrix.container }} + MY_MOLECULE_VERSION=${{ matrix.version }} + MY_MOLECULE_DOCKER_COMMAND=${{ matrix.command }} + MY_MOLECULE_INTERPRETER=${{ matrix.interpreter }} molecule test -s ${{ matrix.collection_role }} diff --git a/ansible_collections/community/zabbix/.github/workflows/plugins-integration.yml b/ansible_collections/community/zabbix/.github/workflows/plugins-integration.yml index 4e4dd0a30..f23071a1b 100644 --- a/ansible_collections/community/zabbix/.github/workflows/plugins-integration.yml +++ b/ansible_collections/community/zabbix/.github/workflows/plugins-integration.yml @@ -20,9 +20,6 @@ jobs: fail-fast: false matrix: zabbix_container: - - version: "4.0" - - version: "5.0" - # - version: "5.4" # only activate after basic compatibility - version: "6.0" - version: "6.2" - version: "6.4" @@ -31,37 +28,37 @@ jobs: - stable-2.12 - stable-2.13 - stable-2.14 + - stable-2.15 + - stable-2.16 - devel python: - - 3.9 + - '3.10' steps: - name: Check out code - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: path: ansible_collections/community/zabbix - name: Set up Python ${{ matrix.python }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} - name: Install ansible-base (${{ matrix.ansible }}) run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible }}.tar.gz --disable-pip-version-check - - name: Install dependencies - run: pip install docker-compose zabbix-api - - name: Install ansible.netcommon collection - run: ansible-galaxy collection install ansible.netcommon -p /home/runner/work/community.zabbix/community.zabbix + run: ansible-galaxy collection install ansible.netcommon -p $GITHUB_WORKSPACE working-directory: ./ansible_collections/community/zabbix # For Zabbix integration tests we need to test against different versions of # the Zabbix server. To do this we spin up a Docker container using the `matrix` # of version and ports specified earlier. - name: Zabbix container server provisioning - run: docker-compose up -d - working-directory: ./ansible_collections/community/zabbix + uses: isbang/compose-action@v1.5.0 + with: + compose-file: "./ansible_collections/community/zabbix/docker-compose.yml" env: zabbix_version: ${{ matrix.zabbix_container.version }} @@ -78,6 +75,6 @@ jobs: working-directory: ./ansible_collections/community/zabbix # See the repots at https://codecov.io/gh/ansible-collections/community.zabbix - - uses: codecov/codecov-action@v1 + - uses: codecov/codecov-action@v3 with: fail_ci_if_error: false diff --git a/ansible_collections/community/zabbix/.github/workflows/proxy.yml b/ansible_collections/community/zabbix/.github/workflows/proxy.yml index c13634afc..985bb8ceb 100644 --- a/ansible_collections/community/zabbix/.github/workflows/proxy.yml +++ b/ansible_collections/community/zabbix/.github/workflows/proxy.yml @@ -15,48 +15,43 @@ on: - ".github/workflows/proxy.yml" jobs: molecule: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: - molecule_distro: - - container: mysql-centos - image: geerlingguy/docker-rockylinux8-ansible:latest - group: mysql - - container: pgsql-centos - image: geerlingguy/docker-rockylinux8-ansible:latest - group: postgresql - - container: sqlite-centos - image: geerlingguy/docker-rockylinux8-ansible:latest - group: sqlite3 - - container: mysql-ubuntu - image: geerlingguy/docker-ubuntu2004-ansible - group: mysql - - container: pgsql-ubuntu - image: geerlingguy/docker-ubuntu2004-ansible - group: postgresql - command: /sbin/init - - container: sqlite-ubuntu - image: geerlingguy/docker-ubuntu2004-ansible - group: sqlite3 - command: /sbin/init - - container: mysql-debian - image: geerlingguy/docker-debian11-ansible - group: mysql - - container: pgsql-debian - image: geerlingguy/docker-debian11-ansible - group: postgresql - - container: sqlite-debian - image: geerlingguy/docker-debian11-ansible - group: sqlite3 + container: + - rockylinux9 + - rockylinux8 + - centos7 + - ubuntu2204 + - ubuntu2004 + - ubuntu1804 + - debian12 + - debian11 + - debian10 collection_role: - zabbix_proxy + database: + - mysql + - pgsql + - sqlite3 + version: + - v64 + - v62 + - v60 + include: + - interpreter: python3 + - interpreter: python + container: centos7 + exclude: + - container: debian12 + version: v62 steps: - name: Check out code - uses: actions/checkout@v1 + uses: actions/checkout@v4 - name: Set up Python 3.9 - uses: actions/setup-python@v1 + uses: actions/setup-python@v4 with: python-version: 3.9 @@ -75,8 +70,10 @@ jobs: - name: Run role tests run: >- - MY_MOLECULE_CONTAINER=${{ matrix.molecule_distro.container }} - MY_MOLECULE_IMAGE=${{ matrix.molecule_distro.image }} - MY_MOLECULE_GROUP=${{ matrix.molecule_distro.group }} - MY_MOLECULE_DOCKER_COMMAND=${{ matrix.molecule_distro.command }} + MY_MOLECULE_CONTAINER=${{ matrix.container }} + MY_MOLECULE_IMAGE=${{ matrix.container }} + MY_MOLECULE_VERSION=${{ matrix.version }} + MY_MOLECULE_DATABASE=${{ matrix.database }} + MY_MOLECULE_INTERPRETER=${{ matrix.interpreter }} + MY_MOLECULE_DOCKER_COMMAND=${{ matrix.command }} molecule test -s ${{ matrix.collection_role }} diff --git a/ansible_collections/community/zabbix/.github/workflows/repo-sanity.yml b/ansible_collections/community/zabbix/.github/workflows/repo-sanity.yml index 98954a82f..499d2f1ae 100644 --- a/ansible_collections/community/zabbix/.github/workflows/repo-sanity.yml +++ b/ansible_collections/community/zabbix/.github/workflows/repo-sanity.yml @@ -10,16 +10,16 @@ jobs: strategy: matrix: python: - - 3.9 + - '3.10' runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: path: ansible_collections/community/zabbix - name: Set up Python ${{ matrix.python }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} @@ -29,7 +29,6 @@ jobs: - name: Run lint test for py3 run: tox -elinters-py3 -vv working-directory: ./ansible_collections/community/zabbix - if: matrix.python != '2.7' sanity: name: Sanity (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }}) @@ -43,21 +42,23 @@ jobs: - stable-2.12 - stable-2.13 - stable-2.14 + - stable-2.15 + - stable-2.16 - devel python: - - 3.9 + - '3.10' runs-on: ubuntu-latest steps: # ansible-test requires the collection to be in a directory in the form # .../ansible_collections/NAMESPACE/COLLECTION_NAME/ - name: Check out code - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: path: ansible_collections/community/zabbix - name: Set up Python ${{ matrix.ansible }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} diff --git a/ansible_collections/community/zabbix/.github/workflows/server.yml b/ansible_collections/community/zabbix/.github/workflows/server.yml index 8a8930e02..b169aa9f1 100644 --- a/ansible_collections/community/zabbix/.github/workflows/server.yml +++ b/ansible_collections/community/zabbix/.github/workflows/server.yml @@ -15,38 +15,47 @@ on: - ".github/workflows/server.yml" jobs: molecule: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: - molecule_distro: - - container: mysql-centos - image: geerlingguy/docker-rockylinux8-ansible:latest - group: mysql - - container: pgsql-centos - image: geerlingguy/docker-rockylinux8-ansible:latest - group: postgresql - - container: mysql-ubuntu - image: geerlingguy/docker-ubuntu2004-ansible - group: mysql - - container: pgsql-ubuntu - image: geerlingguy/docker-ubuntu2004-ansible - group: postgresql - command: /sbin/init - - container: mysql-debian - image: geerlingguy/docker-debian11-ansible - group: mysql - - container: pgsql-debian - image: geerlingguy/docker-debian11-ansible - group: postgresql + container: + - rockylinux9 + - rockylinux8 + - ubuntu2204 + - ubuntu2004 + - ubuntu1804 + - debian12 + - debian11 + - debian10 collection_role: - zabbix_server + database: + - mysql + - pgsql + version: + - v64 + - v62 + - v60 + include: + - interpreter: python3 + exclude: + - container: debian12 + version: v62 + - container: debian10 + version: v62 + - container: ubuntu1804 + version: v62 + - container: ubuntu1804 + version: v64 + - container: debian10 + version: v64 steps: - name: Check out code - uses: actions/checkout@v1 + uses: actions/checkout@v4 - name: Set up Python 3.9 - uses: actions/setup-python@v1 + uses: actions/setup-python@v4 with: python-version: 3.9 @@ -63,10 +72,12 @@ jobs: - name: Install the collection run: ansible-galaxy collection install $COLLECTION_FILE - - name: Run role tests + - name: Run server role tests run: >- - MY_MOLECULE_CONTAINER=${{ matrix.molecule_distro.container }} - MY_MOLECULE_IMAGE=${{ matrix.molecule_distro.image }} - MY_MOLECULE_GROUP=${{ matrix.molecule_distro.group }} - MY_MOLECULE_DOCKER_COMMAND=${{ matrix.molecule_distro.command }} + MY_MOLECULE_CONTAINER=${{ matrix.container }} + MY_MOLECULE_IMAGE=${{ matrix.container }} + MY_MOLECULE_VERSION=${{ matrix.version }} + MY_MOLECULE_DATABASE=${{ matrix.database }} + MY_MOLECULE_INTERPRETER=${{ matrix.interpreter }} + MY_MOLECULE_DOCKER_COMMAND=${{ matrix.command }} molecule test -s ${{ matrix.collection_role }} diff --git a/ansible_collections/community/zabbix/.github/workflows/web.yml b/ansible_collections/community/zabbix/.github/workflows/web.yml index 81c506082..79b7beb11 100644 --- a/ansible_collections/community/zabbix/.github/workflows/web.yml +++ b/ansible_collections/community/zabbix/.github/workflows/web.yml @@ -15,37 +15,49 @@ on: - ".github/workflows/web.yml" jobs: molecule: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: - molecule_distro: - - container: mysql-centos8 - image: geerlingguy/docker-rockylinux8-ansible:latest - group: mysql - - container: pgsql-centos8 - image: geerlingguy/docker-rockylinux8-ansible:latest - group: postgresql - - container: mysql-ubuntu18 - image: geerlingguy/docker-ubuntu1804-ansible - group: mysql - - container: pgsql-ubuntu20 - image: geerlingguy/docker-ubuntu2004-ansible - group: postgresql - - container: mysql-debian - image: geerlingguy/docker-debian11-ansible - group: mysql - - container: pgsql-debian - image: geerlingguy/docker-debian11-ansible - group: postgresql + container: + - rockylinux9 + - rockylinux8 + - ubuntu2204 + - ubuntu2004 + - ubuntu1804 + - debian12 + - debian11 + - debian10 collection_role: - zabbix_web + database: + - mysql + - pgsql + web_server: + - nginx + version: + - v64 + - v62 + - v60 + include: + - interpreter: python3 + exclude: + - container: debian10 + version: v62 + - container: ubuntu1804 + version: v62 + - container: debian10 + version: v64 + - container: ubuntu1804 + version: v64 + - container: debian12 + version: v62 steps: - name: Check out code - uses: actions/checkout@v1 + uses: actions/checkout@v4 - name: Set up Python 3.9 - uses: actions/setup-python@v1 + uses: actions/setup-python@v4 with: python-version: 3.9 @@ -64,8 +76,11 @@ jobs: - name: Run role tests run: >- - MY_MOLECULE_CONTAINER=${{ matrix.molecule_distro.container }} - MY_MOLECULE_IMAGE=${{ matrix.molecule_distro.image }} - MY_MOLECULE_GROUP=${{ matrix.molecule_distro.group }} - MY_MOLECULE_DOCKER_COMMAND=${{ matrix.molecule_distro.command }} + MY_MOLECULE_CONTAINER=${{ matrix.container }} + MY_MOLECULE_IMAGE=${{ matrix.container }} + MY_MOLECULE_VERSION=${{ matrix.version }} + MY_MOLECULE_DATABASE=${{ matrix.database }} + MY_MOLECULE_WEB_SERVER=${{ matrix.web_server }} + MY_MOLECULE_INTERPRETER=${{ matrix.interpreter }} + MY_MOLECULE_DOCKER_COMMAND=${{ matrix.command }} molecule test -s ${{ matrix.collection_role }} diff --git a/ansible_collections/community/zabbix/.gitignore b/ansible_collections/community/zabbix/.gitignore index a27e8241a..43399c126 100644 --- a/ansible_collections/community/zabbix/.gitignore +++ b/ansible_collections/community/zabbix/.gitignore @@ -20,3 +20,4 @@ venv.bak/ # ignore dev stuff .devcontainer local_play.yml +antsibull-env diff --git a/ansible_collections/community/zabbix/CHANGELOG.rst b/ansible_collections/community/zabbix/CHANGELOG.rst index cf83e116c..e6b53e476 100644 --- a/ansible_collections/community/zabbix/CHANGELOG.rst +++ b/ansible_collections/community/zabbix/CHANGELOG.rst @@ -5,6 +5,163 @@ community.zabbix Release Notes .. contents:: Topics +v2.3.1 +====== + +Bugfixes +-------- + +- Avoid to update user-directory configuration in dry run. + +v2.3.0 +====== + +Minor Changes +------------- + +- api_requests - Handled error from depricated CertificateError class +- multiple roles - Removed unneeded Apt Clean commands. +- proxy role - Updated MariaDB version for Centos 7 to 10.11 +- zabbix web - Allowed the independent configuration of php-fpm without creating vhost. +- zabbix_host_info - added ability to get all the hosts configured in Zabbix +- zabbix_proxy role - Add variable zabbix_proxy_dbpassword_hash_method to control whether you want postgresql user password to be hashed with md5 or want to use db default. When zabbix_proxy_dbpassword_hash_method is set to anything other than md5 then do not hash the password with md5 so you could use postgresql scram-sha-256 hashing method. +- zabbix_server role - Add variable zabbix_server_dbpassword_hash_method to control whether you want postgresql user password to be hashed with md5 or want to use db default. When zabbix_server_dbpassword_hash_method is set to anything other than md5 then do not hash the password with md5 so you could use postgresql scram-sha-256 hashing method. +- zabbix_templategroup module added + +Bugfixes +-------- + +- api module - Fixed certificiate errors +- proxy and server roles - Defaulted location of fping and fping6 based on OS. +- proxy role - Removed requirement for mysql group definition. +- server role - typo in configuration var StasAllowedIP to StatsAllowedIP +- zabbix-{agent, javagateway, proxy, server, web} - support raspberry pi without repository url specification + +v2.2.0 +====== + +Minor Changes +------------- + +- Added zabbix_group_events_info module +- action module - Added notify_if_canceled property +- agent and proxy roles - Set default `zabbix_api_server_port` to 80 or 443 based on `zabbix_api_use_ssl` +- agent role - Removed duplicative Windows agent task +- agent role - Standardized default yum priority to 99 +- all roles - Re-added ability to override Debian repo source +- all roles - Updated Debian repository format to 822 standard +- various - updated testing modules +- various - updated to fully qualified module names +- zabbix agent - Added capability to add additional configuration includes +- zabbix_api_info module added +- zabbix_user module - add current_passwd optional parameter to enable password updating of the currently logged in user (https://www.zabbix.com/documentation/6.4/en/manual/api/reference/user/update) + +Bugfixes +-------- + +- zabbix_inventory - fixed handeling of add_zabbix_groups option +- zabbix_template - fix template export when template's content has "error" word +- zabbix_web role - fix variable naming issues (undefined) to zabbix_web_version and zabbix_web_apt_repository + +v2.1.0 +====== + +Minor Changes +------------- + +- Multiple Roles - Replaced depricated 'include' statements with 'include_tasks' +- Update action_groups variable in runtime.yml +- all roles - Added support for Debian 12 (Bookworm) +- all roles - Delete gpg ids variable. +- all roles - Modified to allow a non-root user to run the role. +- all roles - Updated testing to account for the correct version of Zabbix +- zabbix_hostmacro module - Add description property for Host macro creation/update. Allow to set/update description of Zabbix host macros. +- zabbix_proxy - Added installation of PyMySQL pip package +- zabbix_proxy - Modified installation of Centos 7 MySQL client +- zabbix_proxy - Standardized MySQL client installed on Debian and Ubuntu +- zabbix_regexp module added +- zabbix_settings module added +- zabbix_token module added + +Bugfixes +-------- + +- agent role - Added missing become statement to allow run to role as nonroot +- zabbix_host module - fix updating hosts that were discovered via LLD +- zabbix_proxy role - failed at version validation. Fix adds cast of zabbix_proxy_version to float, similarly to the other roles. +- zabbix_proxy role - undefined vars at updating proxy definition. Fix adds null defaults for zabbix_proxy_tlsaccept and zabbix_proxy_tlsconnect. +- zabbix_web role - removed 'ssl on;' nginx configuration, which is no longer supported since nginx version 1.25.1. + +New Modules +----------- + +- community.zabbix.zabbix_regexp - Create/update/delete Zabbix regular expression +- community.zabbix.zabbix_settings - Update Zabbix global settings. +- community.zabbix.zabbix_token - Create/Update/Generate/Delete Zabbix token. + +v2.0.1 +====== + +Bugfixes +-------- + +- Proxy and Agent Roles - Added `zabbix_api_use_ssl` variable to allow secure API connections +- Web Role - Added defaults and documentation for `zabbix_apache_custom_includes` +- agent - Handled undefined variable error for Windows default versions +- all roles - Added option to selectively disable a repo on Redhat installs + +v2.0.0 +====== + +Minor Changes +------------- + +- Replaced usage of deprecated apt key management in Debian based distros - See https://wiki.debian.org/DebianRepository/UseThirdParty +- Standardized tags across all roles. +- Updated all roles to default to version 6.4 for install. +- all roles - removed unused variables from defaults +- all roles - standardized testing matrix to check all supported versions and operating systems. +- all roles - temporarily disable epel repo on zabbix installation tasks +- all roles - updated documentation. +- inventory plugin - switched from using zabbix-api to custom implementation adding authentication with tokens +- inventory script - re-coded to stop using zabbix-api. API tokens support added. +- web role - removed support for htpasswd + +Breaking Changes / Porting Guide +-------------------------------- + +- agent role - removed support for Darwin, Amazon, Fedora, XCP-ng, Suse, Mint, and Sangoma operating systems +- agent role - removed support for zabbix_create_host and replaced it with zabbix_agent_host_state +- agent role - removed support for zabbix_create_hostgroup and replaced it with zabbix_agent_hostgroups_state +- agent role - removed support for zabbix_http_password, zabbix_api_http_password, zabbix_api_pass, and zabbix_api_login_pass and replaced it with zabbix_api_login_pass +- agent role - removed support for zabbix_http_user, zabbix_api_http_user, zabbix_api_user, and zabbix_api_login_user and replaced it with zabbix_api_login_user +- agent role - removed support for zabbix_inventory_mode and replaced it with zabbix_agent_inventory_mode +- agent role - removed support for zabbix_link_templates adn replaced it with zabbix_agent_link_templates +- agent role - removed support for zabbix_macros and replaced it with zabbix_agent_macros +- agent role - removed support for zabbix_proxy and replaced it with zabbix_agent_proxy +- agent role - removed support for zabbix_update_host and replaced it with zabbix_agent_host_update +- all modules - dropped support of Zabbix versions < 6.0 +- all roles - removed support for the zabbix_version variable. +- all roles - removed support for all versions of Zabbix < 6.0. +- all roles - removed support for installation from epel and non-standard repositories +- dropped support of zabbix-api to make REST API calls to Zabbix +- proxy role - removed support for zabbix_database_creation and replaced it with zabbix_proxy_database_creation +- proxy role - removed support for zabbix_database_sqlload and replaced it with zabbix_proxy_database_sqlload +- proxy role - removed support for zabbix_selinux and replaced it with zabbix_proxy_selinux +- server role - removed support for zabbix_server_mysql_login_password and replaced with zabbix_server_dbpassword +- server role - removed support for zabbix_server_mysql_login_user and replaced with zabbix_server_dbuser +- stopped supporting Ansible < 2.12 +- stopped supporting Python < 3.9 +- zabbix_action - message parameter renamed to op_message +- zabbix_group_facts module - removed in favour of zabbix_group_info +- zabbix_host_facts module - removed in favour of zabbix_host_info + +Removed Features (previously deprecated) +---------------------------------------- + +- agent role - removed support to configure firewall +- web role - removed installation of apache, debian, and php + v1.9.3 ====== diff --git a/ansible_collections/community/zabbix/CONTRIBUTING.md b/ansible_collections/community/zabbix/CONTRIBUTING.md index df591ef1c..b11725793 100644 --- a/ansible_collections/community/zabbix/CONTRIBUTING.md +++ b/ansible_collections/community/zabbix/CONTRIBUTING.md @@ -59,7 +59,6 @@ These rules are required for any contributions proposing a new Zabbix module or * In `DOCUMENTATION` block via `extends_documentation_fragment` keyword. * In module `argument_spec` as a set of module parameters. * Implement proper logout mechanism as other modules do. -* Use the same version of `zabbix-api` library as defined in collection requirements. * Comply with [Ansible module best practices](https://docs.ansible.com/ansible/devel/dev_guide/developing_modules_best_practices.html). ## Testing and Development diff --git a/ansible_collections/community/zabbix/FILES.json b/ansible_collections/community/zabbix/FILES.json index 80415b832..d8e8b2611 100644 --- a/ansible_collections/community/zabbix/FILES.json +++ b/ansible_collections/community/zabbix/FILES.json @@ -46,49 +46,49 @@ "name": ".github/workflows/agent.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "7f6609467d2f142f82e08d9a3675286695188b1f96eae451c5a92f9fc92ad880", + "chksum_sha256": "1f4eaa1cf578bb1ac84173e292873c14483a3e9b0218badf5f99b949b1d19f75", "format": 1 }, { "name": ".github/workflows/javagateway.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "4768caf2de9e672c21e17389ed2e8ae19009198270cd37fc73f3b2ee745da85f", + "chksum_sha256": "282c567de319fd40b888e0bea2b8340418acaf3e1360b1f4cd2fcec845580c4d", "format": 1 }, { "name": ".github/workflows/plugins-integration.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c15c0360234358038f7f2d9835eedfc2f90aaf5fec5fccc95d0ac8c99c0c453a", + "chksum_sha256": "c8ab5f2a2482938905571a63bc80edb9bc421a7356526adff54978f158c998be", "format": 1 }, { "name": ".github/workflows/proxy.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "9d6b75380b849fb9e88a2484c599cf52206242f7caf1bb964e1a3431836be0c0", + "chksum_sha256": "0b93f36762cb804aa12a46d2e15ec2b0cf4ec61198db451fb5e8d60601c4e2c7", "format": 1 }, { "name": ".github/workflows/repo-sanity.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "547ff5f443f05cba80f3a80180f7418b1df7e015701ebb8125b1fb6151a9cb77", + "chksum_sha256": "7df59ea87533f81dea79e8869b8a4074e0caafa171b62d07d24fc53ae4447af2", "format": 1 }, { "name": ".github/workflows/server.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "db95b5b85610665607a70cfc1dd50eed1224ededa3c3513b56601385964d9c9a", + "chksum_sha256": "20f9e0d9de9e0b5fba678c672628e0bf2900794a61e7a9b4414e16dd10eda3b3", "format": 1 }, { "name": ".github/workflows/web.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "1530135054b317b5605a4fbe8680faa74e87007080ae0f59f111ba1fa4e2a5b0", + "chksum_sha256": "c5e042f11aeabebedb326853b6a5712c3ef02fbc884329b26c4b38d3d942861a", "format": 1 }, { @@ -116,14 +116,14 @@ "name": "changelogs/.plugin-cache.yaml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "0b56a72dcc4aae26837ecd516b88b5889b0fbf0085367125e47a1eb0d79fe4cc", + "chksum_sha256": "d64872f24dbd6423bc177cc30e44f48f8f2c008fb83d98320c86507e52bc4fd2", "format": 1 }, { "name": "changelogs/changelog.yaml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "4c0e5e697fb8f013a1a392689a23d91da029b6b9b321c49b218b6cb69d51dec0", + "chksum_sha256": "7ec8214d899a562092105e8650db5a80d38065ac6f21e8eba77ce6b31c1be9b9", "format": 1 }, { @@ -134,13 +134,6 @@ "format": 1 }, { - "name": "changelogs/roles_zabbix64.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "f4d624707b0cf06c6b382891d2c759289219e03ea633da90622623082c1bafb6", - "format": 1 - }, - { "name": "docs", "ftype": "dir", "chksum_type": null, @@ -151,7 +144,7 @@ "name": "docs/PUBLISHING_TO_GALAXY.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "df53d35672848c736b9cf780b968936413631d41c9abbad1c3da9d7782d7955d", + "chksum_sha256": "53c357be0c9e0bda0ef2a04dad6c85df28ea33b20c7c4b33aa4ce0ad30171eaf", "format": 1 }, { @@ -162,45 +155,38 @@ "format": 1 }, { - "name": "docs/UPGRADE.md", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "e4e1d4fa54395501c71f8c70b369c16aa4b4edf15b5a65a1746cb727d98f51f0", - "format": 1 - }, - { "name": "docs/ZABBIX_AGENT_ROLE.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ee2a165aac204d9df3bca010af9f662e99b3442bc10da941d00d87285d51bbca", + "chksum_sha256": "426cdb2833f6b41fae8e6d3eceb45e5d7e53bb64fda20238a4843e1f23ce6bc5", "format": 1 }, { "name": "docs/ZABBIX_JAVAGATEWAY_ROLE.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b4182c4262079bb61943eabdd08dce46e0240d30dc3b61494fe1fdba11dca828", + "chksum_sha256": "950880306b5d99f842830620bcb03e3a67d487ab62b60c650421027b620824c9", "format": 1 }, { "name": "docs/ZABBIX_PROXY_ROLE.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ac111a4c75c45c1c320381b8f1032e52be9822bf1b7c5713591f8077d3223b56", + "chksum_sha256": "137aa537b0643a8aba1e3b94965bd33d91a53a780a8873a398e07620a1c64ec4", "format": 1 }, { "name": "docs/ZABBIX_SERVER_ROLE.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "d9e5f1ebef97ef13cd79fa70e4d2e1fbbd48090e239a13be019edd2a179f45d0", + "chksum_sha256": "434d9e12ff1d20c7f2e1891e2518628eea9f8497502a5032a7f83ea488477665", "format": 1 }, { "name": "docs/ZABBIX_WEB_ROLE.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5aad816040102389cc79090e613ff22231337424f20bfe9626d022b153023ac5", + "chksum_sha256": "228030e059e30b229a82e7c31b609d5d122d710338557ebd74ee151eda79c0fb", "format": 1 }, { @@ -214,7 +200,7 @@ "name": "meta/runtime.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "50679314811f43a872bd27d00dcdce7ae167a1612307c3bd16dc63aa17dddb42", + "chksum_sha256": "ae56876a44f1225a766a414ae93397720a4df40db4ab38ba6c32e0373c2ffe38", "format": 1 }, { @@ -256,7 +242,7 @@ "name": "molecule/zabbix_agent_tests/common/playbooks/prepare.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5ae566f4f24a278f50574ebff1b64c60dfb7aae0a587ec54e8ad35a75a7e6ea3", + "chksum_sha256": "eebc4f8c272317fba0f96c482780a2850b9474b2b992b3a80d2f3d59c3db9a52", "format": 1 }, { @@ -305,7 +291,7 @@ "name": "molecule/zabbix_agent_tests/common/tests/common/test_agent.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "047aa3486e4c15a37be84128d3072a8c25c2488f8755141d686e29611483cb9a", + "chksum_sha256": "6e7673ac6c547d5f6f8c3958037fef7c3e0be5596909f50c6b17c1da86e0c735", "format": 1 }, { @@ -333,7 +319,7 @@ "name": "molecule/zabbix_agent_tests/common/molecule.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2e9bf77259593522020af1a6b70b85ecd0d1f02b0c8807801b4bb63ab2f886ef", + "chksum_sha256": "9ce9330c02c7d06dca39d7b31e1683ffd552bb341f35603fbb42659e3915a0ac", "format": 1 }, { @@ -557,14 +543,14 @@ "name": "molecule/zabbix_javagateway/molecule.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "403c27814ef8c997cd3c483c48337f5e2ce6384a799bb1cdab54c3ac01b1016c", + "chksum_sha256": "8e5003cb9d8bcd490b46fe8358affc9cc4c7f60b582c2f42a4713c7fd001768a", "format": 1 }, { "name": "molecule/zabbix_javagateway/prepare.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "1b6c9f53dce0f4a63df8d386fc1aa264335af706dd00943f8ff66dd735250e22", + "chksum_sha256": "5c2130a175978fd0ae2cdf25dd7fb4247f04fce7d9610435d5047a5fa963009f", "format": 1 }, { @@ -585,7 +571,7 @@ "name": "molecule/zabbix_proxy/tests/test_default.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "48e48563e12a400b8e24268456f3534f0887217baf48e5fae587c5ec9f59ba39", + "chksum_sha256": "057875f1f4a9953622125fd03d150886b763f8ed4b7776fbf30cc4ac0e462713", "format": 1 }, { @@ -606,14 +592,14 @@ "name": "molecule/zabbix_proxy/molecule.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "780d05e996542297e40e112566587ba18cbea58becb58c298a94a6c65a7c2c18", + "chksum_sha256": "59ff07c357b6c9d01f0337b6c6b5878c90efb396132faec46b37628680bce34d", "format": 1 }, { "name": "molecule/zabbix_proxy/prepare.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "37c3e8879e3a5fb94115a8745f19e4fdd6eca693b852d048ad881c2de3e13f9d", + "chksum_sha256": "d3fde6e25ce3b39d5c70324f7db1ac9aed31e0a3106c51dc77c3be7293f55a19", "format": 1 }, { @@ -634,7 +620,7 @@ "name": "molecule/zabbix_server/tests/test_default.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "23f62965273df247d7ae99c4a171ef2f22b352d63e7af18eb617b3aebf0a1840", + "chksum_sha256": "32f8fe869c639ee0fdaab4f8a82a1726ac3a28ac91e1a3095f9b970ad4455894", "format": 1 }, { @@ -655,14 +641,14 @@ "name": "molecule/zabbix_server/molecule.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "25b8acf6faf7dffa24083bae88ae7b9b4044741e8cd85083ce48cdd5c6a1b39c", + "chksum_sha256": "eb8ff715881d9046a2aa6d4b0ec64f68c59e7cf48bff7644236e44399570bb53", "format": 1 }, { "name": "molecule/zabbix_server/prepare.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "01f51c7913635ba28f9fc720a540a2b59c7b71123c51e3b9e6bd4493b2bb5de8", + "chksum_sha256": "34346df48a4e44910398adcea6030e76735f03464ea0b0415160b2c8b86297d7", "format": 1 }, { @@ -683,7 +669,7 @@ "name": "molecule/zabbix_web/tests/test_default.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "81f986130198995bbaeb722b7659e214830e1cc91e00313e87b3e6cbca38b6c1", + "chksum_sha256": "d078bd5d704618add6913f1bcd75aa8b4ebf6b71e46b43299d58dbef4a6c21de", "format": 1 }, { @@ -704,14 +690,14 @@ "name": "molecule/zabbix_web/molecule.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "cec08cba46b8c5f66fe3b9f018014a7c506fa145ca90a02472942f955c4c2910", + "chksum_sha256": "160ca8984b2f48f84e64e2d928ef1ab8a807f5cfb6c36d1c37d7920ca284efca", "format": 1 }, { "name": "molecule/zabbix_web/prepare.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e42cb66ee3a4f8a6149adc9d85538e73d66d7fd43f9b5af95335ca4d186a0c20", + "chksum_sha256": "46f227d436fbf62c6a18677746e4b3b2f6854473ea58ea889781d60a5d86acaa", "format": 1 }, { @@ -725,7 +711,7 @@ "name": "molecule/requirements.txt", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5da70582c0669065d3948183fd74a508a2ecb80f683e4499050b39415931858b", + "chksum_sha256": "274a2a68c3bac9fefa051ff068179fce63df05424461ff973dd44473c890382b", "format": 1 }, { @@ -743,17 +729,10 @@ "format": 1 }, { - "name": "plugins/doc_fragments/connection_persistent.py", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "b3d6dc35fc7752bd61b55722c5ae88ae02170b93fb85960b7b1430c2bb7146df", - "format": 1 - }, - { "name": "plugins/doc_fragments/zabbix.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "64d6a3931787f894153e068ae4e91fddfe8127ed7e61ea903a45a60269b1406b", + "chksum_sha256": "2f57fd09f9be79cba82c211dcab2e423a54d27228bc2afd57b578a4a6b95dfbb", "format": 1 }, { @@ -767,7 +746,7 @@ "name": "plugins/httpapi/zabbix.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "65146ad205a7cc5d5d5d08b5f4172582878ceb8a9c01f26b36447f18fac996ce", + "chksum_sha256": "bef450e3b5700be1a1cc35981b229a53522a35a0e1d13f1ba715922f3ee79d2c", "format": 1 }, { @@ -781,7 +760,7 @@ "name": "plugins/inventory/zabbix_inventory.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "bc0ec92bd5b83af4f840d8dfc0c6ec1da5f88093a75a57ad0456cc3fc7690959", + "chksum_sha256": "5bf212295bcf22a955fbc9c8b2ffd2395ba948e68ace593098ffbe2391247c3a", "format": 1 }, { @@ -809,28 +788,21 @@ "name": "plugins/module_utils/api_request.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "a1a0b0b8fc8189a3dc6facd77621cb14e99511319a0b082a7803fb0976d8d080", + "chksum_sha256": "add8f4adc48b8104914edb4c5a6200d78c89e02d3a6c01fa54c3142954ae3498", "format": 1 }, { "name": "plugins/module_utils/base.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "54657e0efada7dc5e77dca6546721031478f8bdd298f690509076b17e15e9af4", + "chksum_sha256": "d2437b6f8ce0f700c801869ca310b2a70589046a1994ad06962ba70b2f448d30", "format": 1 }, { "name": "plugins/module_utils/helpers.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2eaf8c62644252eb35908db596c4226df48ba3340bfadc95bf6102aeabf851f5", - "format": 1 - }, - { - "name": "plugins/module_utils/wrappers.py", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "b592fdc7a1a516f00d256702a24530507bb9e63acee9469f78776a6066429b55", + "chksum_sha256": "42ec390b1f0ee4fa92aa19c33b84963267d994c221d74e7ea2fce1635f951fc9", "format": 1 }, { @@ -841,220 +813,241 @@ "format": 1 }, { - "name": "plugins/modules/zabbix_group_facts.py", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "72829e189f762da9a094b5a2d6d79783abb09311fef0ca321e4bc6ca8cf6f308", - "format": 1 - }, - { - "name": "plugins/modules/zabbix_host_facts.py", + "name": "plugins/modules/__init__.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "9d0341ced4e1d0c2d36276d1d0fe7271a530b89b5f751541a5cf7a32012f6847", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "format": 1 }, { - "name": "plugins/modules/__init__.py", + "name": "plugins/modules/zabbix_action.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "chksum_sha256": "a3dace3d7ea72cf09dde768f2896094335a3c7e11f6bfc8507a288530ae9401f", "format": 1 }, { - "name": "plugins/modules/zabbix_action.py", + "name": "plugins/modules/zabbix_api_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "f2eeb69c809b3aba15df826b79233b43209a6de279d8bbd3b5e09cd7cd016aa1", + "chksum_sha256": "c9b579e945d2c5029acbd05006f18a97fa4ec8324128693a4712c7a05ee804bf", "format": 1 }, { "name": "plugins/modules/zabbix_authentication.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "04357311ce1b7345a774bb630ab4b76f8a2fa02e766e9053cf92777bedac0659", + "chksum_sha256": "1afb95c8c1e4921ed4397da4fd3c978863e909c99c0de087720480d4d616ff68", "format": 1 }, { "name": "plugins/modules/zabbix_autoregister.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "a21144832a5d33b502beea5c30eef7117822ebdb2e2829b541151c5deee6d65a", + "chksum_sha256": "8ef9941a5854ecf03895cace6e59b1c19aed74f8c13d385a68c1d2231a39f8ac", "format": 1 }, { "name": "plugins/modules/zabbix_discovery_rule.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ed9c604f7ed63e7f9021a6fcfe5a42998e27bcc59ef118593d7bd32810be0adf", + "chksum_sha256": "49277e61440825a7feb15162ffb6c38e40a81a021abdbecf9bd7db748bb4730d", "format": 1 }, { "name": "plugins/modules/zabbix_globalmacro.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "93a2dff2fdec0e4c9270951f851a6b705fd83097579c6dfa224da75a70c9fd3d", + "chksum_sha256": "b7f5f0f0b9abe2d49246945e70555bd63490659526ff4013677c420b0b3b4d2c", "format": 1 }, { "name": "plugins/modules/zabbix_group.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "8c4997b0b63820066e3804edaf37e6c595566e1bdcb747e2a2b4ac7d8329e0cd", + "chksum_sha256": "2f2d7202edcd8d02e353eeb45292a9076abcdc520c86585ae7d849f4a0919a26", + "format": 1 + }, + { + "name": "plugins/modules/zabbix_group_events_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c0af2025b1df634ed14b1ffbee3947e7ec438b4e4d9e8cfe41a4da54c614e384", "format": 1 }, { "name": "plugins/modules/zabbix_group_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "72829e189f762da9a094b5a2d6d79783abb09311fef0ca321e4bc6ca8cf6f308", + "chksum_sha256": "1880c246619a51b3603ff55b4ad71a79c23198a9e3b823f30c1d1078c73b649d", "format": 1 }, { "name": "plugins/modules/zabbix_host.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "f73e0a24b2fdfe72d83a0a2453431a847aec7bde7dd544ad214322bbb60599ce", + "chksum_sha256": "ce0879953bfeaac236d6329b08fd19f7573a9a172ef4fa777489d6f9f1fd6609", "format": 1 }, { "name": "plugins/modules/zabbix_host_events_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "488889c8ca3f4b6e9acbb27c9c26b92d8180de9a600c0b676996bb4797208813", + "chksum_sha256": "4d8d7767314f3dfc8c32f1cb3aa4c056fc9c81023e09b121db99018c06533660", "format": 1 }, { "name": "plugins/modules/zabbix_host_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "9d0341ced4e1d0c2d36276d1d0fe7271a530b89b5f751541a5cf7a32012f6847", + "chksum_sha256": "91b4a19126c54b4142b60f309e9fda96daa4d5b5974292eff07ddec4c0a86ef8", "format": 1 }, { "name": "plugins/modules/zabbix_hostmacro.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "9f477dc001793c78a94dbd141e700d56423e56fed515035080647829b7c7e4a3", + "chksum_sha256": "c55f33c57e6c8401d5588c469c714869ba79631b401df40838e9566b37a9a274", "format": 1 }, { "name": "plugins/modules/zabbix_housekeeping.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c4b26c8caa59756d48ba0e5b95776829982502f3d8870d71c93cea9107315d8d", + "chksum_sha256": "e0313bb629d34231bd549ad8fe2170be157f38ca5d14563a1eb7008c27a961af", "format": 1 }, { "name": "plugins/modules/zabbix_maintenance.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "364f6004001d05fa7750e254de4732674978abb28fb2e1cc11172275be9c84d5", + "chksum_sha256": "baa73f10a75adbfc09a93d5624492aa9b2e174bf089641cfbd37e329865fe313", "format": 1 }, { "name": "plugins/modules/zabbix_map.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "d5dc24b8b8ef92874326de6fdab300bdeb2f6a71545fea10ee64a0a1d9ab18d4", + "chksum_sha256": "16f772207be532d4c79c219bb14b9b927d356a45bd467271956560e33da58c7a", "format": 1 }, { "name": "plugins/modules/zabbix_mediatype.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "6a0b555e69e815d00fbdb7e37041e0f216a6c621a1abd7b67b228b14d7294821", + "chksum_sha256": "555d924fcf31e673c17917fc5f7abf1d6d8f1de17d87386f5a2626549cdab7f3", "format": 1 }, { "name": "plugins/modules/zabbix_proxy.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "f442459b52bab35073f9366dfe0bc16afd219ad505d91b6b681734f563884ae4", + "chksum_sha256": "97e129e170b7e0208c5b8b48160f1853da0b47f491c83b70ee4a0d06b47e37d1", "format": 1 }, { "name": "plugins/modules/zabbix_proxy_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e02f116191199752c9087cd867cc4ad0bacd19338a36978c740f408548e2c312", + "chksum_sha256": "599e78d0839a31712f21dedf223aec64502be89188a71ea725a83827fbd1f70e", "format": 1 }, { - "name": "plugins/modules/zabbix_screen.py", + "name": "plugins/modules/zabbix_regexp.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "1f74721c60d1db5e8aa8031876db2d88e2192aee39851c9bf1a6e219fad99fee", + "chksum_sha256": "0e9fd757dbdc521abbc9bbdf90144486f0f1b61d4d5412923ea4839d099a10cd", "format": 1 }, { "name": "plugins/modules/zabbix_script.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "a4dc1c9b646b8586121a5d89d382c4e8162c0ee9072d659e5cb68e7c895d9ea3", + "chksum_sha256": "3fd732f7f929a0dbe91dbaa4ce1d2c7fcd86b0c5199ee9ca5d9db8e3f471b613", "format": 1 }, { "name": "plugins/modules/zabbix_service.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "07c6a4604e5d780165daaa43cf304bbc858fee747c30dc7561ddc00643db23f8", + "chksum_sha256": "24ea8aa83ee4a248bbd58c9bb06808233bd416e7cee835453b39e161b0f3733a", + "format": 1 + }, + { + "name": "plugins/modules/zabbix_settings.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ace8dc0e8c72c74a086b72749865531a95bfd04a6efcdf76eec7045ae9a1cdf5", "format": 1 }, { "name": "plugins/modules/zabbix_template.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b57132f5e62c804acc1828b459a2e70efa49945201ceedbcf71951b4594f50ef", + "chksum_sha256": "d08d3ff4e10193b5a69e3bb515c1ee00157526ab702dc4ffadca8b4adb1c2b1c", "format": 1 }, { "name": "plugins/modules/zabbix_template_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "910e1b679b257e0b64d807d4162e85d29fb6d6b8f05c2fb9ec9f0d51eb85fc8e", + "chksum_sha256": "9a81416d70353d40edf7917a65076a580cf89885f24313e4192cfa794fe4ac46", + "format": 1 + }, + { + "name": "plugins/modules/zabbix_templategroup.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9c8ca31207e2894422502cf15cf3e3774ce2f944e4bc403c87ab5978f360b236", + "format": 1 + }, + { + "name": "plugins/modules/zabbix_token.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "87cfdee6888e77b0a0032f9ed7fb203cb2f94dd6d302367001bfaa874d5be197", "format": 1 }, { "name": "plugins/modules/zabbix_user.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2397b8173b49107a3238de5ecaf0509bcd1842c55e1329fe765f2f6d902caaa2", + "chksum_sha256": "f980a6933f2fa41e09f5d7103d0aff75b1aeb51ca244d49eba80743a0713b175", "format": 1 }, { "name": "plugins/modules/zabbix_user_directory.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "821641cedc3d4a5cfa669f063b434dc0b07b4fb5b128392d96c4c24c25e5d126", + "chksum_sha256": "6a5692e2db9ea9dff204b36dea634478aa9eeff7c8b9c18c419b1db35cd53f09", "format": 1 }, { "name": "plugins/modules/zabbix_user_info.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5073676377f2089d55e17f23c86bfe5b4a7c5014b2aa52a05242b7d49251a65d", + "chksum_sha256": "eb5041f792858b49d48d52f7d50107e0dc0dd49e905370a6b4d6fdb5e46975b3", "format": 1 }, { "name": "plugins/modules/zabbix_user_role.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b5cc955ca1ac15ba0d15b2159387facb6e12590865e63c9d9b2061f603ee37ac", + "chksum_sha256": "b3355345e85e6ab21c3afdc882f400d584c45fe581b6e065b9051e43ecd84994", "format": 1 }, { "name": "plugins/modules/zabbix_usergroup.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "a7f908ac23ad94f1f3f5916e8fa48cb864e5401d00126532a4668c14681e605b", + "chksum_sha256": "aef8772084635607bc5b371f4d5425029bce045156b7415e4ea6205ddf99afe8", "format": 1 }, { "name": "plugins/modules/zabbix_valuemap.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "285b6b71d55ac7d8844f79a6d8c100bd899279aaa7ee35bea78d10ea810615e6", + "chksum_sha256": "3540592c87e41e55de5f3acd2e13585cb18c11d8615c98c63dc9ffadd59a8935", "format": 1 }, { @@ -1075,7 +1068,7 @@ "name": "roles/zabbix_agent/README.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ee2a165aac204d9df3bca010af9f662e99b3442bc10da941d00d87285d51bbca", + "chksum_sha256": "426cdb2833f6b41fae8e6d3eceb45e5d7e53bb64fda20238a4843e1f23ce6bc5", "format": 1 }, { @@ -1089,7 +1082,7 @@ "name": "roles/zabbix_agent/defaults/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "12b9fc863285e0cdd2d5be2f81bfbd62e68d8ebe11dbb66b18a5ed50347b9a21", + "chksum_sha256": "e86a6de88e4fb31fd47d9268557e10f71e42988e4dca09a6228497be99c1c225", "format": 1 }, { @@ -1131,7 +1124,7 @@ "name": "roles/zabbix_agent/handlers/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "acad5ae4f8591346fcea52d1682ab85ffbd5b9f43595da6f68003755eddf81c5", + "chksum_sha256": "261c79c8d62b86e2ad0cefc77641fe9c1794e3a8ccf81e3c6db75a5fa4c56f88", "format": 1 }, { @@ -1201,21 +1194,21 @@ "name": "roles/zabbix_agent/molecule/with-server/molecule.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "3c886d4bca694a6b19e3d15909f5738b771e6ef9eab31987ef6e63eb480d62e5", + "chksum_sha256": "9ffbe5738cb02c6327a778b585a6e931f9cc12a2ec7c271fb340d2e683e12ac2", "format": 1 }, { "name": "roles/zabbix_agent/molecule/with-server/playbook.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "7acb20ce65dd661f2a8f2ff1492cd385a7d603d7e946f2331e3be0f64f7c2c60", + "chksum_sha256": "e92cdcacf5dfc00fc317fc870f231e9ee0ba924298e2878c74338191e6d6b435", "format": 1 }, { "name": "roles/zabbix_agent/molecule/with-server/prepare.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "03966cfb5f1589ae0177403025b7cf62bb94bc8e4a551e14fbb87c2a73f8c208", + "chksum_sha256": "091c8043ef580658ab2b4c93020888562cd5b3ca5a32d78f7c43892696e0f118", "format": 1 }, { @@ -1233,164 +1226,143 @@ "format": 1 }, { - "name": "roles/zabbix_agent/tasks/Darwin.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "1761047e511995d4aeda5eeda1db4133b2f6f3e18193027a4351bfeee6bada76", - "format": 1 - }, - { "name": "roles/zabbix_agent/tasks/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "cacac2625d62892a4da290bc4ac8e36ca7f83c84f5ddf4145cf17a73dfbd70f9", + "chksum_sha256": "6d5e5886e18c5774d89567b311e2fbd2dc4aad0b1950af22bb88fafe152a3b78", "format": 1 }, { "name": "roles/zabbix_agent/tasks/Docker.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "7406219975281823e907acb14e0cfebef02496bc5b85e89380b0c446f9e95ec4", + "chksum_sha256": "3be4cf14a566fe855c2c54a126db5b0b33ad3beca3490339351e5d4c03e62f0e", "format": 1 }, { "name": "roles/zabbix_agent/tasks/Linux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "95bcf03c9ac71b4825684bedf69d4069d549c18a13c5943b1f6f89775acf495e", + "chksum_sha256": "4cbe916769cde150073a71e1ac8b5e9a3a531ba6a17782944e4e758433877ff8", "format": 1 }, { "name": "roles/zabbix_agent/tasks/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5cb57a73eed1d8f5152b3b1ad8cb15c8cd0297158b96c27ee42e7629c52aeeda", - "format": 1 - }, - { - "name": "roles/zabbix_agent/tasks/Suse.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "71a60660c5dc62b42d22a8798464af1533f364ed28a2fa0bd14cf8fc33f0c66c", + "chksum_sha256": "00589dec36032603720fe426db2ed7b5a165037e9d129e42e5679689c89a2009", "format": 1 }, { "name": "roles/zabbix_agent/tasks/Windows.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "aa1070768c380a56084c56b4b786be3d5319d8758f0315d41f9bb2ec1a37d760", + "chksum_sha256": "709a0466886c5bf5ed5f560b987cf68d268fff906a6dd26b667c25654d37fe81", "format": 1 }, { "name": "roles/zabbix_agent/tasks/Windows_conf.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "9b90e2b63ab6910636900c305044e67c540ddf2fa3a359a0744f5d73ecf35b3f", + "chksum_sha256": "ba0da2675127cf58cfa66ba4e977f15f2f856654fb7583826865276fa10c6262", "format": 1 }, { "name": "roles/zabbix_agent/tasks/api.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "7ebe1e547cd1ee30e82ebdf6927c050d61733e938955abb28284542e5ceca8da", - "format": 1 - }, - { - "name": "roles/zabbix_agent/tasks/firewall.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "8b74b8d9c33d31c6bd972f96187a8ebe407ed7b4e8d4f56c32563ad9a88f5e03", + "chksum_sha256": "8201b0dc1b00dd86383f272dd81f06e792f8bab1951aee62c03a46791ca5b4bb", "format": 1 }, { "name": "roles/zabbix_agent/tasks/macOS.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "07214cf9e01f2d1b382dee5fa8af5a592f91b64a327d10379c5f50e977bf771b", + "chksum_sha256": "519abb365aaf15c992a9a16615ab397e7d08f7f7b3b908557a178ee42d49cf4f", "format": 1 }, { "name": "roles/zabbix_agent/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "cf4a07124914b3173aa8f2cfa25aa3b575dd0bd6e8ab15ddc4377699b980bbf9", + "chksum_sha256": "978ae5731bb64fc79a4c404185da1f915480550e0a79ab8cdcc94475dc0ff86e", "format": 1 }, { "name": "roles/zabbix_agent/tasks/remove.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "1a19cc7cd1fca702c9d88b573bf8ecdf062396aaf45ad6f6abd4fe4bb1a57d9a", + "chksum_sha256": "a61614e0f51ef087ef82eb2319b8546f213c22aff785afdf56f007c442b6cb2c", "format": 1 }, { "name": "roles/zabbix_agent/tasks/selinux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "a22d30b558ddcbf9251868fe7accd96208bb813a9fe3878536184f68be55cd19", + "chksum_sha256": "5b48575676d826c5e6321daddab3713fbbd76ba575400f29eeafc277017b9fe2", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "107052aaa9b9e206e09a0991f160996b2b390101f71e06ab3f3a8ba7afee5dea", + "chksum_sha256": "bcf8266fdd6b7d01d5a6bb97a3f4c1982ca7dc099dedcaa407390c69bbeaa7e6", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_agent2.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "db9d50614a7bc0247fd8aeefb53cc94fb083f4af5780c9b349acd05b0a9d7ae7", + "chksum_sha256": "1d0eafd6fefb287832c5b42c80c37c2b2e049b937aa50f44d7040ce56d81db86", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_agent2_common.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "89a391fe07d61221c3d1fad2b217c3ce917d929d0c93a6872febb4b38fc9ed16", + "chksum_sha256": "3f194c4720b68b5eb4003effe148b6c379a650f91d5325147d3e43485d37ba7b", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_agent2_linux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "6887ed6b41bbb92b719848be16779655fee4a6bcd4b09d6acca293c25801e24a", + "chksum_sha256": "3d651d820f7be9fd52d0b752f6ad07fc3e41a7ba52f178ae1221e1e2419980d9", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_agent2_windows.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c2d7c59ef98c62873349927d0ca6856375bab84f3b80f5c77365d8599a64d4e3", + "chksum_sha256": "416c701d66781d97032e1104e5c25abe4157740f517fdcc5ffea5f5bb14fc9cf", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_common.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "4f214f550557b61a8dd48d05a10a6b507e6ad66b6f40665d6eee762929e7e1d3", + "chksum_sha256": "4be3dadd8bfa5cc2aae3de2b975040f6352fee46127b7ccba2b746f11cfdd39a", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_linux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "238105b3e8d92db2f70ed8a724c8e317e943138b52c1d98e169614589563ec0d", + "chksum_sha256": "1b494062174c84263883f71ed50842255bc270246afbe12f8573bc2e81ea10a9", "format": 1 }, { "name": "roles/zabbix_agent/tasks/tlspsk_auto_windows.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "d6ef817e770cc8b55b174aa9f02196f68084856945d2bbf9edc79fb4adaa98d8", + "chksum_sha256": "bf3c3976e28fb3846de16e0a0e01eae0184d2cf57b79da0a342a5d5b35b187d8", "format": 1 }, { "name": "roles/zabbix_agent/tasks/userparameter.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "eb96d45277305e0ce2e5b3bfe264614791ffd4ff9fbaa61f88bc780ac18ea86a", + "chksum_sha256": "5248b27e7d45f14a3abdd5d93bf80e416f6e6f084f54f1cceeeba0f1ab08b9dd", "format": 1 }, { @@ -1425,14 +1397,14 @@ "name": "roles/zabbix_agent/templates/zabbix_agent2.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "313aa178efad06ed5e47570ad86b65a1fe434131afe275bb7c2515ffa09f211f", + "chksum_sha256": "123866b68a1511d56e14a523035583e6a3adcf8d234abd086f4b7ba0e322df4b", "format": 1 }, { "name": "roles/zabbix_agent/templates/zabbix_agentd.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c724b3b877eaf83a2c083bb69aca3e946be294ff4308f0abaf5294e29164cf36", + "chksum_sha256": "d3c56ebbe34908eaa981e1838ee17ab90729814dce584c1b3e66ab2455ac6f0f", "format": 1 }, { @@ -1443,45 +1415,24 @@ "format": 1 }, { - "name": "roles/zabbix_agent/vars/Darwin.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "db7f6b6b2dd80ddaf2e8d281c78f350a4849b74deda63ef63338b7699527fa20", - "format": 1 - }, - { "name": "roles/zabbix_agent/vars/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "37e4c7f331e4c1e92a79fa3d17ec2e4adc06b83d23a3e644f0ac74e294437217", + "chksum_sha256": "a5da93f0d2b1f52521b40c0434ebbb78c7c13dfd63b1948689e104e86fc81a6c", "format": 1 }, { "name": "roles/zabbix_agent/vars/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "0f9fb95f6406336aa72a9736463d118362cde397991129391db58038c1897ab0", - "format": 1 - }, - { - "name": "roles/zabbix_agent/vars/Sangoma.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "6b0b76e02ac840a2cb89b691d4ae0e6a55e441fa81bd0cc6a9487b0f1bc02019", - "format": 1 - }, - { - "name": "roles/zabbix_agent/vars/Suse.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "a0cc3ac65514ccdbd0f6035eb823aa916d7ea8dda1d0b3d9c4a7f783529bc290", + "chksum_sha256": "587c2d75417faa8978fdcc729a4b940b4530c5a02df59a049985ab684742e90c", "format": 1 }, { "name": "roles/zabbix_agent/vars/Windows.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "af541365edb39dd0d046a3ae36770b01f6f7881001587f68c707e2d171662f6b", + "chksum_sha256": "90fd4ff9797beb10be3a9649da827ccb76b83633da33116fc014d6d4984a5f6f", "format": 1 }, { @@ -1492,13 +1443,6 @@ "format": 1 }, { - "name": "roles/zabbix_agent/vars/zabbix.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "2f18e3250d44f4cba423e73e08e1bfff9be95645e559837588901f3e137e5886", - "format": 1 - }, - { "name": "roles/zabbix_javagateway", "ftype": "dir", "chksum_type": null, @@ -1509,7 +1453,7 @@ "name": "roles/zabbix_javagateway/README.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b4182c4262079bb61943eabdd08dce46e0240d30dc3b61494fe1fdba11dca828", + "chksum_sha256": "950880306b5d99f842830620bcb03e3a67d487ab62b60c650421027b620824c9", "format": 1 }, { @@ -1523,7 +1467,7 @@ "name": "roles/zabbix_javagateway/defaults/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "87b1aed24ee0aca58a4c4c97bef77b339bb9810816476187310d0ff93e118833", + "chksum_sha256": "72237d44a0cfac809b0432db46974f2bb48d1a61260d80491d1c7bde73f1bf47", "format": 1 }, { @@ -1551,7 +1495,7 @@ "name": "roles/zabbix_javagateway/handlers/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "9ad072b7d35f1d0e200857c59e5cc8b3c6417427c313bbbdff78fedd95354310", + "chksum_sha256": "cca5cb24d36359ed053c7baee07f0fb17f15a93a7ebb8a8b25cf0f150171851b", "format": 1 }, { @@ -1579,21 +1523,21 @@ "name": "roles/zabbix_javagateway/tasks/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "cf47a37619f9b6665ee00315c0855d6a1ec9b5840caf651808f66d6c9bf3a099", + "chksum_sha256": "1cf7aeabb650158552dcc993e72c3aee3dd54c9d160d95ac4e603eec39d3c763", "format": 1 }, { "name": "roles/zabbix_javagateway/tasks/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2146cb8284148aa9d5397cbd34d42b8ecb726c53468923fb38e9a4c7328d9d63", + "chksum_sha256": "a07992953e92b787c8011a629e5525c8c0e3c3c91b7ff910da3835488e4f23eb", "format": 1 }, { "name": "roles/zabbix_javagateway/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "944ef7efad86d6facb498db0ef23de2524ba271973b2f7c3f5e89b1f6aa630ac", + "chksum_sha256": "67e5a9cd03529caca8af75622431ec4fe54bc256b14ad7568bedaedfd0f9206a", "format": 1 }, { @@ -1607,7 +1551,7 @@ "name": "roles/zabbix_javagateway/templates/zabbix_java_gateway.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "7d2324bdb590456ae36fe2efd638307dd1e9b22279fdeb8483689a5316842875", + "chksum_sha256": "66ff3664fd8264f4d3d6cfa11ddf0f1d571dbeba776b2c7f08ca34a53e1deaee", "format": 1 }, { @@ -1621,14 +1565,14 @@ "name": "roles/zabbix_javagateway/vars/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "f4eb8a4a848b0eae37caae62c36ae4d1e35dabe5aab2357203f1427b5ad55491", + "chksum_sha256": "f6a87b8863fc8b0cf5dec159ecbe788b8cb1963c11d3dfcfddb6f64d3dfce77e", "format": 1 }, { "name": "roles/zabbix_javagateway/vars/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ee454bd3e000b6cb6bf752ecbd4a29f6a10a2773a148f945220ea91076450493", + "chksum_sha256": "15190bbcec0481429596bf843003ba1f7c3267e997f502a988304b757e3c9b55", "format": 1 }, { @@ -1639,13 +1583,6 @@ "format": 1 }, { - "name": "roles/zabbix_javagateway/vars/zabbix.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "2257dcb583cc09be9a13c17c9966b63aa7e14d39cd39d8557eccc0734ff0e9ae", - "format": 1 - }, - { "name": "roles/zabbix_proxy", "ftype": "dir", "chksum_type": null, @@ -1656,7 +1593,7 @@ "name": "roles/zabbix_proxy/README.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ac111a4c75c45c1c320381b8f1032e52be9822bf1b7c5713591f8077d3223b56", + "chksum_sha256": "137aa537b0643a8aba1e3b94965bd33d91a53a780a8873a398e07620a1c64ec4", "format": 1 }, { @@ -1670,7 +1607,7 @@ "name": "roles/zabbix_proxy/defaults/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c16dd23a720096fd637c8657a49d8081e2b50f86ed22d0b2b3557991ff23e086", + "chksum_sha256": "f3cc7cde32ae9908078b20eb97d7f25baaccbbd2f0ea4678296ae36a3fb10087", "format": 1 }, { @@ -1698,7 +1635,7 @@ "name": "roles/zabbix_proxy/handlers/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "02effc86ecae774f9c4e208da774604bc32a1aa263225d77b817a501d2d3df7d", + "chksum_sha256": "6768668411203f0cd315b10510ef61515960d0dcde185c22e03d7e9f1937ec25", "format": 1 }, { @@ -1726,49 +1663,49 @@ "name": "roles/zabbix_proxy/tasks/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "8a35de709c48c4224dece469ca5f45bf81671482294251194c17ffd7a4c488c5", + "chksum_sha256": "62d366a97ff9d7a6b6f5ec20bde13cb22b447b0271f7e2e432dcad6c9b771712", "format": 1 }, { "name": "roles/zabbix_proxy/tasks/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b770f37ceb3ae2f48a8fe8b21b3d305f973c07574ad9079e28a7685179b47978", + "chksum_sha256": "4b521fd4998782a7fd2e5e8c4bea84d5436dd9e63b0732a0590034181e5c6329", "format": 1 }, { "name": "roles/zabbix_proxy/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "12a3f45c5eb455cb937e1b48f524991a3eacfd53461cb5f71358a3a79ba75afb", + "chksum_sha256": "45ee561d3bf7df8a5067ccb625a15546b2572e202f75614b57af7143766cf63a", "format": 1 }, { "name": "roles/zabbix_proxy/tasks/mysql.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "3f3d72cc83e4c5cbe9cedd034359ead81c09567126b75240e4ebe284c45d44a4", + "chksum_sha256": "ea5c5f6380e122e9b658d4acd5e8a382fa6c564673ec37c947a92f95f0b24ec5", "format": 1 }, { "name": "roles/zabbix_proxy/tasks/postgresql.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "0e29dc6547af5aab28881b169743a468447a8a2e43f81e93f039b72f12a1c724", + "chksum_sha256": "1b97ce83bb12d6f435c0363e4f39888c87d0be53db6561168771add354fdd41f", "format": 1 }, { "name": "roles/zabbix_proxy/tasks/selinux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "09b879efd086b9b6b85323dfcc9880366001e6766a376ffe0a3d7debf74dcd8b", + "chksum_sha256": "5fcaf2583198e89e108cc2b2a7b777fa6e2dac1a2a1efd88a6c44308d79a6362", "format": 1 }, { "name": "roles/zabbix_proxy/tasks/sqlite3.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "62e88f189a7a692fffcfc5fe245d725c6c5685778e7b83155abaae89727ce737", + "chksum_sha256": "4c3b276cddc6afa88a48224fa274ca8ea7b7b59d74655197bddec0545a38309d", "format": 1 }, { @@ -1782,7 +1719,7 @@ "name": "roles/zabbix_proxy/templates/zabbix_proxy.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e47e91ec1f3da19270f6d5091b18b6b04af7a43761052f10582a151fa973be99", + "chksum_sha256": "8133d6ef95a09b0e435324b3005c524745eb0e194cfa591cb3d6f4c36a312590", "format": 1 }, { @@ -1793,38 +1730,24 @@ "format": 1 }, { - "name": "roles/zabbix_proxy/vars/Amazon.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "7d87cd61d18e6d90032bfe0a42d18cb1bf651001280e06ac60a7850e7be5e733", - "format": 1 - }, - { "name": "roles/zabbix_proxy/vars/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "0b725e04160bcf663d6d88baa8b99d90500e2026def7a5b157fa6d582c5836a6", + "chksum_sha256": "66a3826d949a04140ff1fda9f008f8ef657050cb854677b4cf5c07c69a546346", "format": 1 }, { "name": "roles/zabbix_proxy/vars/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "262daf894cef6d121f54caf8b14dc627f1c2a438c28448235c7fa8d288e59f9d", + "chksum_sha256": "50f4bb5b1ab62a8f1128dde98e820349b164ef4c1583e6f78d61279d19e56c48", "format": 1 }, { "name": "roles/zabbix_proxy/vars/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2a54870b52848a1bdf2dcbcd7e86f46509f868c02c51ca4f315457282b5a9c78", - "format": 1 - }, - { - "name": "roles/zabbix_proxy/vars/zabbix.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "52df6b43e568fd07f963c088f523b2ffcc903da18bc1037fed1952e7dc86f384", + "chksum_sha256": "599afb847ce1287ea279d2f5864a6fc6eb240323ef2b92a408e11c8472b08189", "format": 1 }, { @@ -1845,7 +1768,7 @@ "name": "roles/zabbix_server/README.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "d9e5f1ebef97ef13cd79fa70e4d2e1fbbd48090e239a13be019edd2a179f45d0", + "chksum_sha256": "434d9e12ff1d20c7f2e1891e2518628eea9f8497502a5032a7f83ea488477665", "format": 1 }, { @@ -1859,7 +1782,7 @@ "name": "roles/zabbix_server/defaults/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "95107b5a298c2a5733353856c52973332cc89945cbabf376f6b5e62265cfb244", + "chksum_sha256": "024b79ba5eb85cb58403e606c0914e5e606a26e085795e7e7bccbf4f57d8ff66", "format": 1 }, { @@ -1887,7 +1810,7 @@ "name": "roles/zabbix_server/handlers/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ffb85ad6d8b0d9e5b40d855e11940f1b1907ed58c8345f1d8121d02f4472a70a", + "chksum_sha256": "d93e81e28cda85d6a15c386ce28a05c359a1191fe7dfca79bdfbe9e4dd725f0d", "format": 1 }, { @@ -1915,49 +1838,49 @@ "name": "roles/zabbix_server/tasks/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "99fc338cab1bee724ad370677868d5ca78cf401697698fe99862218d138eefd9", + "chksum_sha256": "c174231cd483409e026d4b82e987ce3f2e2b30405b71ab15dab333b7c37e2f7c", "format": 1 }, { "name": "roles/zabbix_server/tasks/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "6c15f6cd24f0bcee1131194568127733889d3ed546d68f4f4bef4dfa0575a2cd", + "chksum_sha256": "99bc6623e1018b3c5565d97670385a0ff3b205d3b9dccc5da0d3082f05f6f305", "format": 1 }, { "name": "roles/zabbix_server/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c6a7a3b01e6eea7d6bf89126d2157e9dca2d7fa0ca0ba24f1defbc0e38364d04", + "chksum_sha256": "a56f05203c959669058d2172d90f11dca5bd024c85651a75ecde52db2148f991", "format": 1 }, { "name": "roles/zabbix_server/tasks/mysql.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ea1cf201defad2ed9e7e5e8b28e178a762ff283e6c3ef22a7bd59fa6ba7ecd9c", + "chksum_sha256": "aa11fd9cfc1662112ed5f321bd06ccde126f65ee7531267c4357f6e82cab540e", "format": 1 }, { "name": "roles/zabbix_server/tasks/postgresql.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "21872ed7e12aabd0ea72bca9c68fa1247c370302ea7c4a702f3b102058dae41d", + "chksum_sha256": "44146c8e7329cb92aa907a64d7c646700b8125b93dbcbbeb50716ad01f434c53", "format": 1 }, { "name": "roles/zabbix_server/tasks/scripts.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ae57630fcbe0bbb4c702a2a173bc0e8f746c5d2ab5ff107074ee86c8329b56d2", + "chksum_sha256": "8981bf214f6fddf8fc7a3d771baadeff8a028231fac0eb23c848ed5c2a83152f", "format": 1 }, { "name": "roles/zabbix_server/tasks/selinux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "f2fc0f9f1a0c932873d0095d4ebaeb90cdc7160c7789949c0c1f4e1199e7d2c9", + "chksum_sha256": "b2d30030efe386cfb08fc3f45cd4a4c1efc17c41df031f31deaf9d683f4d6a27", "format": 1 }, { @@ -1971,7 +1894,7 @@ "name": "roles/zabbix_server/templates/zabbix_server.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "aedb97e7c1166029b2f0078cf1aabc90b2932c658a2b08ad4b14eafcab2a411d", + "chksum_sha256": "7f1d839829f4ac53b994c691efbcbcb98615f7dba76af7793248636e209a131b", "format": 1 }, { @@ -1985,14 +1908,14 @@ "name": "roles/zabbix_server/vars/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b2d7348d3930df0cefb747be395295f54adb0ed5920df21f174fadc786b1168a", + "chksum_sha256": "67cb0847a5e96afd2b05a9e4db7f8383d6d0376cc4f93db206dc80c7778310eb", "format": 1 }, { "name": "roles/zabbix_server/vars/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ec10a5fd9114e8c195f4f11344b6e48241fa1a98eb3bff9da0219185d424b9c0", + "chksum_sha256": "c27f0472596d51fd438b8d6f1c9b3bb788d7865b0c818d58c1b1456b3ec62185", "format": 1 }, { @@ -2003,13 +1926,6 @@ "format": 1 }, { - "name": "roles/zabbix_server/vars/zabbix.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "78d5ef518d81987451e5e05ba5465a90bfb3471aff4f6ababe8dbbd3e0d8d132", - "format": 1 - }, - { "name": "roles/zabbix_server/requirements.yml", "ftype": "file", "chksum_type": "sha256", @@ -2027,7 +1943,7 @@ "name": "roles/zabbix_web/README.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5aad816040102389cc79090e613ff22231337424f20bfe9626d022b153023ac5", + "chksum_sha256": "228030e059e30b229a82e7c31b609d5d122d710338557ebd74ee151eda79c0fb", "format": 1 }, { @@ -2041,7 +1957,7 @@ "name": "roles/zabbix_web/defaults/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "646af635c64aa409be510450ea21b66fac15f000193b2675cb8bba34dc7add9b", + "chksum_sha256": "136689b650ad54e8046ca7f1f7f24cc8d528dfcde385b1027f2aa7b64ca3c26c", "format": 1 }, { @@ -2055,7 +1971,7 @@ "name": "roles/zabbix_web/handlers/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "17914993fcbae9e8c40f256e0ab37de2f9f858161d578d5aea092fa655491581", + "chksum_sha256": "2f4d778c7db1d00c48dc43e5ea74d78746f6669e57b1337d3a784324606f9e6e", "format": 1 }, { @@ -2083,70 +1999,42 @@ "name": "roles/zabbix_web/tasks/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "32b9873fb6312b16ba6af8332db19144f5c02e1f7e8c997302d10fe241f3aa57", + "chksum_sha256": "7c7426b9d16b6868f72eea3aa28c390217c51f5ba9aaa9afcf41caffb8072808", "format": 1 }, { "name": "roles/zabbix_web/tasks/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "8abf1ccc3ba445542f0318f1e7473c3d7d82aaab16d1502cdf78def689ed716b", - "format": 1 - }, - { - "name": "roles/zabbix_web/tasks/access.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "7949a75447930d99585497abe2dd063b8b309bd1d1215d95458fd8fe7842d491", + "chksum_sha256": "b2a875ae0deaf4facd16416db665771c03395e90879c3691e2430cf24e2f7331", "format": 1 }, { "name": "roles/zabbix_web/tasks/apache.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "8d7c2f668004c83b3244f819a9fe152d2f76cc232719f4b2dc0ab8ba0ae22c2d", - "format": 1 - }, - { - "name": "roles/zabbix_web/tasks/apache_Debian.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "fb94333d3a7055e24d6bf7fb9da89dbc294160e8025e7ec902c7168be47b3346", - "format": 1 - }, - { - "name": "roles/zabbix_web/tasks/apache_RedHat.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "dae8aa03b819ae47f82db8805c1c4e47c29db5e8f2dba1aead94e74899e231c6", + "chksum_sha256": "81ce423aa0f4cd24876a81f452eefac27a1a3a20ea6e56082a3c5bb5e7615864", "format": 1 }, { "name": "roles/zabbix_web/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b7ce3a35777bffe7fe7ee0564307b2d6d5c5842c6b8e1e9d4a01d5933b90c83c", + "chksum_sha256": "9961406bcd8733eb9a504a8a4d2766148fdcb43ca2d5e27d007e2c041cccc4a5", "format": 1 }, { "name": "roles/zabbix_web/tasks/nginx.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b7de6c00cae54176d63d8d21dab85070b22a95cb919dcca711a3588a733054d6", - "format": 1 - }, - { - "name": "roles/zabbix_web/tasks/php_Debian.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "135f474e5db359bc75a288ac4fcc76b79af1c804b3b2b8e34ae758c06f395bb9", + "chksum_sha256": "0e6cda68ac6b8d16c64770477575119f248aa5933a91b206f8a1468b529459aa", "format": 1 }, { "name": "roles/zabbix_web/tasks/selinux.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "cc983ba894c3b7e9759722a13dc20ffa6814306d69a8f8f53003aa87496e5f64", + "chksum_sha256": "5b696169bbd552cba7f54fb7bc9f8fba7b885e0d2048cd4c56f2de57a3c560cd", "format": 1 }, { @@ -2160,28 +2048,28 @@ "name": "roles/zabbix_web/templates/apache_vhost.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "04ed070405b18a24cd9b8788d1e7ad6c11b6c3f28033056bf4d38d3dc36906f4", + "chksum_sha256": "d907bae4235f286ce0f5cf5cb4e0f3fc619741bcc0dc38ec3f6825086eaf5739", "format": 1 }, { "name": "roles/zabbix_web/templates/nginx_vhost.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "bc02f95677b2d1fce3f74bf8bd778a73a2702256743595551976711333ab0c3e", + "chksum_sha256": "4b66f5e157d4d15419a4d3e5e8580b2f50d5413ed092f026902ebed50bb431f4", "format": 1 }, { "name": "roles/zabbix_web/templates/php-fpm.conf.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "908ec55fb71d004f7745b4cd1788e005a32c96b0f46cb8295ad8bfa4eb247cc3", + "chksum_sha256": "d81d68fe5d62c8199e5d360be16bf1b1f27d72c4a3926d1e45abe720bb458cb8", "format": 1 }, { "name": "roles/zabbix_web/templates/zabbix.conf.php.j2", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5cf7a3042220dd33ebc0593d0a2a55d035419768db41fc33b02b0f4226f62715", + "chksum_sha256": "75abd8891071e4270a973c4b3fb72323046d577d84d277c41630dafeb06db9a2", "format": 1 }, { @@ -2192,94 +2080,17 @@ "format": 1 }, { - "name": "roles/zabbix_web/vars/Debian-10.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "b22f4fb2ddd44a45a5196bfdc2eb488aa0f20fc50182dad5801fcb7d9100373b", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/Debian-11.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "a80f687d7a145445cc9d3ece5f075047ad0b8419c162dee68d4d7e1d64c97b7c", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/Debian-8.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "329443560941bda266833e38ba4139ac070b477db817db61728ed18817b8131d", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/Debian-9.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "a80f687d7a145445cc9d3ece5f075047ad0b8419c162dee68d4d7e1d64c97b7c", - "format": 1 - }, - { "name": "roles/zabbix_web/vars/Debian.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "62372051217390f4891cb03268c9d8e4588e13bed6877a8cc0b88231f6e9ef8a", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/RedHat-7.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "a0083ec5ca4323c00334ef0591d67d036630bc3cbdc6e0301bc8c351eda6e2d0", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/RedHat-8.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "3aab6d6cccbefb155a14f035b05e558dbe9b76a620a15d467351d94c61c8483c", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/RedHat-9.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "f0dc3ae984a19e65ec9b7fbf9b9cdd6236aa15d34997dade35bcb79057807b78", + "chksum_sha256": "61d4c2a23a9261eeeb511a5ba6e3e9d2d46856c69a390a4ff9f8fbfaad57ec50", "format": 1 }, { "name": "roles/zabbix_web/vars/RedHat.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "fbf732fe22f313440135a050db0d865f18fa43dd457b6723eb8e4c116849e5b0", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/Ubuntu-18.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "b22f4fb2ddd44a45a5196bfdc2eb488aa0f20fc50182dad5801fcb7d9100373b", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/Ubuntu-20.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "a80f687d7a145445cc9d3ece5f075047ad0b8419c162dee68d4d7e1d64c97b7c", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/Ubuntu-22.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "0c50f32893fb2fcdec448107ddee75b0c5f600771df5c3e1299d28a705f736c7", - "format": 1 - }, - { - "name": "roles/zabbix_web/vars/zabbix.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "a853c154c0da014fc883ed968e2f13c8e6792ffcd104d5e7a41bebc9f8519288", + "chksum_sha256": "610b148857b38209584b0810afa2e801a540699be35d46a0ca1cb347fcecf844", "format": 1 }, { @@ -2300,14 +2111,14 @@ "name": "scripts/inventory/zabbix.ini", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "be08243c8bdc7c88f8fef16108e10face4d04d03764cb569718a241c181c5515", + "chksum_sha256": "f8be31ca0869d4833a65704df06b1f36256203544e19a9507f864280f2d8f2a7", "format": 1 }, { "name": "scripts/inventory/zabbix.py", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "dd78405dee6d2fb6c7280691c6feb0b2b26e89987cf58f8ec3c2acc0598a15bb", + "chksum_sha256": "7a180e1f289e5762abcfe3f4cd8fc36001d5a96b4a218fdffa0b649c7bde338f", "format": 1 }, { @@ -2363,7 +2174,7 @@ "name": "tests/integration/targets/setup_zabbix/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "eaf72c686373517bd17032b53d62728d24f16590591f88d3092d13ef3585ee1b", + "chksum_sha256": "0cbad8e6269bc7e51b8907ad540ad42b105a5eb3721d111f04bbc16d78ed3f8a", "format": 1 }, { @@ -2398,7 +2209,42 @@ "name": "tests/integration/targets/test_zabbix_action/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ebd7a2249b07d828e4da440a2524c02c8765f424a921e905ead81ef771cd2327", + "chksum_sha256": "f32f82c954cda026edf42d5ad382323c5ad47573f2c29346276985217419dace", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_api_info", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_api_info/meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_api_info/meta/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_api_info/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_api_info/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ea19033eb14256ef8712af58d65d41d65cc68222dcbfb760accb11a417936b05", "format": 1 }, { @@ -2433,14 +2279,14 @@ "name": "tests/integration/targets/test_zabbix_authentication/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "a66e69e3d84f449a4be7d1d5f4eaaa92897b1b85a48f97287bcd09f7dd645395", + "chksum_sha256": "87eeea307fd5844bfd04f91bce4987875a874adfed431dd2ab38e866edea44ae", "format": 1 }, { "name": "tests/integration/targets/test_zabbix_authentication/tasks/zabbix_authentication_tests.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "60cac0799f832fea3d3ce6dee90ecb51227d4faf9420df902d2a2d033aac850c", + "chksum_sha256": "78351492a6846efd7a338e9642687a5cafbd16ea8a14eab665072c2e0c2d89ba", "format": 1 }, { @@ -2475,7 +2321,7 @@ "name": "tests/integration/targets/test_zabbix_autoregister/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "27a337939722af1c7eeacad529d54bf69af98fff68d52675e465c353716d166a", + "chksum_sha256": "6841293c9119357ac71dc59c70a9fd44efa6dd421ebe94b42ac5f9638da65e96", "format": 1 }, { @@ -2510,7 +2356,7 @@ "name": "tests/integration/targets/test_zabbix_discovery_rule/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "32f946e351919a3759ad3b2c32f5b8a1f5fff35ce8591c18eef78dfd9296a3a1", + "chksum_sha256": "8d727c86332b13746bb8b77cdd1f01ed882731efd7ab694c9ceb8197200ef2ce", "format": 1 }, { @@ -2545,7 +2391,7 @@ "name": "tests/integration/targets/test_zabbix_globalmacro/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "437c3e9253e968a944d82dab70bb0495dff0724c74d5ee2322f2d816d50cf4ea", + "chksum_sha256": "000a00d1991875483136e3ae1b25f4e950f5a753a517ba83885ac177a464ac00", "format": 1 }, { @@ -2580,7 +2426,56 @@ "name": "tests/integration/targets/test_zabbix_group/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e2712df59c9db85ad1fd37e6a2c7af620d38d06c755d5064db8143c76a1fc870", + "chksum_sha256": "5f06ea6c2bce11d9455d97b126705539c5d6bc72e92a9c76ce8f89d08d69ccca", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info/files", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info/files/trigger_testing.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "47c19f92b8b79701c2cfdfc0ea58244cde2098f2dc2241285f828c51b39b37c8", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info/meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info/meta/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_group_events_info/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "516670cd486261337e04d2278d6cac450b49ed02333df3f439d489a20207914b", "format": 1 }, { @@ -2615,7 +2510,7 @@ "name": "tests/integration/targets/test_zabbix_group_info/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "0782df463b5143e4882d0381761bf73248007f49d22fbf3699e4d046d8903a58", + "chksum_sha256": "dea03a83f03e91c687d3872d826b3ea711f43495c821679b40bd3b728405c49b", "format": 1 }, { @@ -2650,35 +2545,35 @@ "name": "tests/integration/targets/test_zabbix_host/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2d4ee657d0794ad05e89d7f25cd3ff21e29d4dbc183db05e448d3bb65bfb2145", + "chksum_sha256": "de37bc2fb49c071c211dcca967c123f96a29738fa17be9cffd645500e779d335", "format": 1 }, { "name": "tests/integration/targets/test_zabbix_host/tasks/zabbix_host_doc.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "6bb205e8b50e693df53d03542b086d9072b9bf32b552e57a3fc148593b304e3e", + "chksum_sha256": "cc7e8a293774e6588f7d73b88456442f11f19be4c8be0c08c4edddab319eb542", "format": 1 }, { "name": "tests/integration/targets/test_zabbix_host/tasks/zabbix_host_setup.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c86cd33bccf27eef9fdf7521774a375d01b59d3faa610c9f5aa7f382aa85fb62", + "chksum_sha256": "4923b09121222416ea70a65cd1cafdbc07907bf34da6de98d2547737cd4d54dc", "format": 1 }, { "name": "tests/integration/targets/test_zabbix_host/tasks/zabbix_host_teardown.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "46d1b84b5802e4489b5093335da4b04900665b987c6d7c2990918af8cf550dd3", + "chksum_sha256": "1be60e6469bed7b8c3dec775d91120b9a8c5257085c89fc6b50e9887fd0af136", "format": 1 }, { "name": "tests/integration/targets/test_zabbix_host/tasks/zabbix_host_tests.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "5aaf98c089043b50e8c57cfc965bc059682ab2e12c032c100b2fb40fba0dba43", + "chksum_sha256": "10fdc4850cbc5a8c135b6010af276b1f5384d617f746ee3ef001e2f34b3cf289", "format": 1 }, { @@ -2713,7 +2608,7 @@ "name": "tests/integration/targets/test_zabbix_host_info/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "2f47878f8a650cb631f463d86b7cd9fcd34b8c3b00980157929047102d43a0d9", + "chksum_sha256": "4cf9e484bf6c13686b1bef5e8c0aed88f5d0216ccc0e5ba4c9914e68f38dc648", "format": 1 }, { @@ -2748,7 +2643,7 @@ "name": "tests/integration/targets/test_zabbix_hostmacro/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "836f37cd9c40daee414510261d881e43f31187b2a84c101f03f3e5e045fb4a9b", + "chksum_sha256": "f9fdc04e680cdd72015b0e1940926443f7ffcc55731e1b897bf4c99da56ef8b3", "format": 1 }, { @@ -2783,7 +2678,7 @@ "name": "tests/integration/targets/test_zabbix_housekeeping/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "bca231a73ba8b7b845c263b641f3deadbc059d35aa5a56ace74a7ca51d438a71", + "chksum_sha256": "c2a203ee87bffecd4ec3492c023e8ca9650fe9876019508682d6e802be5efb2b", "format": 1 }, { @@ -2818,7 +2713,7 @@ "name": "tests/integration/targets/test_zabbix_maintenance/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "59b1762e359119c49345f90512cf419f12d6108ce81672005620b54848897585", + "chksum_sha256": "1e3c539311dc4f4c55b85931338f0693121ff1814cbc4d199fe02a689c5d298b", "format": 1 }, { @@ -2853,7 +2748,7 @@ "name": "tests/integration/targets/test_zabbix_mediatype/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "56ea6ef6bc6ed6ad2d03ea203999b1faa60745c20d1a359434c7b564a138620b", + "chksum_sha256": "c7a4f5cecfef03f695f94a47e7c663a3acb582757df2951e8af77279b2a2e797", "format": 1 }, { @@ -2888,7 +2783,7 @@ "name": "tests/integration/targets/test_zabbix_module_defaults_group/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "d00ba227df2acf39ebabd71a7126ab8ccb8344f0b200cd0938a3aaad944f06dc", + "chksum_sha256": "1d0c912b6630f73d38bba77d03f5967a7cc8bdc8c512f98d75aa2b88e76ccfb1", "format": 1 }, { @@ -2923,7 +2818,7 @@ "name": "tests/integration/targets/test_zabbix_proxy/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "d3fc86b4ac8240ea44fdb3225d5c97b4b45dc55603fe3116a490717fb78b2c95", + "chksum_sha256": "e3996b91dc22e9c5178211f3a5767686b6a14e706531c9bf0b1346ef202d2b69", "format": 1 }, { @@ -2958,42 +2853,42 @@ "name": "tests/integration/targets/test_zabbix_proxy_info/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "c0069278d407546960e2fbabb73aba0481ec28c0353a6218c3c3c12a3cbc9d61", + "chksum_sha256": "efc13acdf9c15fd62232c8880d48a43349469338176fcbee18ff71c2c0bafbfe", "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_screen", + "name": "tests/integration/targets/test_zabbix_regexp", "ftype": "dir", "chksum_type": null, "chksum_sha256": null, "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_screen/meta", + "name": "tests/integration/targets/test_zabbix_regexp/meta", "ftype": "dir", "chksum_type": null, "chksum_sha256": null, "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_screen/meta/main.yml", + "name": "tests/integration/targets/test_zabbix_regexp/meta/main.yml", "ftype": "file", "chksum_type": "sha256", "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_screen/tasks", + "name": "tests/integration/targets/test_zabbix_regexp/tasks", "ftype": "dir", "chksum_type": null, "chksum_sha256": null, "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_screen/tasks/main.yml", + "name": "tests/integration/targets/test_zabbix_regexp/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "67b46ec9773624ff4840804a82a4e39cc039e22c7e52186e5c24d82845b5d8f4", + "chksum_sha256": "940deab9a2f7dde970db42566da1c543d1873bfe0c38449d3add7cf10b331119", "format": 1 }, { @@ -3028,7 +2923,7 @@ "name": "tests/integration/targets/test_zabbix_script/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "88ce48d121b448cc5d7104eb887fc5ce437409b29d8bbf66e0423355af8a9e73", + "chksum_sha256": "093d0f5afd1351f69e87e65474f6ab1742faa58d0c09a14d97b45a7e572027f7", "format": 1 }, { @@ -3077,7 +2972,42 @@ "name": "tests/integration/targets/test_zabbix_service/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "b8c83f814b46f17b42353ad57c506249df2f0f9a84d5050efca3bc83e754df4b", + "chksum_sha256": "6fc45d5e053c66aae6ac99624189d0350535dd689519cf4da65401ce99d4fd1c", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_settings", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_settings/meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_settings/meta/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_settings/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_settings/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3beca76d07dbe9c59e1b4ab8bf3758adca1a79dc7b2a8b1d1de01882255f701c", "format": 1 }, { @@ -3130,13 +3060,6 @@ "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_template/files/template2_50_lower.xml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "3f17ebb04e5f380f8486ca6444bfe7269fb70275c7aa5e1110724e8f37289b5a", - "format": 1 - }, - { "name": "tests/integration/targets/test_zabbix_template/files/template3-changed_54_higher.json", "ftype": "file", "chksum_type": "sha256", @@ -3179,24 +3102,10 @@ "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_template/tasks/import_54_higher.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "b022be250062c840f5f6bc6b60d90d52c08d3b4f85a34f0f6f48153300e04b80", - "format": 1 - }, - { - "name": "tests/integration/targets/test_zabbix_template/tasks/import_54_lower.yml", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "da7627d6dfe9cbc0230ee0609493b9783198a7df59208ededec1831db8476e26", - "format": 1 - }, - { "name": "tests/integration/targets/test_zabbix_template/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ecd0bb5df803e40f683226ae38126faf7f64cb140e792283c658854a166fc211", + "chksum_sha256": "235eb7982d8a11e0e6fd68b53693d49daa89db486f91230e74497f75a0f8d2dc", "format": 1 }, { @@ -3245,56 +3154,112 @@ "name": "tests/integration/targets/test_zabbix_template_info/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "fcbb64754d966c9d86a7d87260231caa3c53e2a55901f3b3bde72aca5cd751a2", + "chksum_sha256": "5ba11ff3f667dfff0cd0bcf40fab0798d220bdf124d4d32ecaa361d8e148ad6f", "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_user", + "name": "tests/integration/targets/test_zabbix_templategroup", "ftype": "dir", "chksum_type": null, "chksum_sha256": null, "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_user/meta", + "name": "tests/integration/targets/test_zabbix_templategroup/meta", "ftype": "dir", "chksum_type": null, "chksum_sha256": null, "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_user/meta/main.yml", + "name": "tests/integration/targets/test_zabbix_templategroup/meta/main.yml", "ftype": "file", "chksum_type": "sha256", "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_user/tasks", + "name": "tests/integration/targets/test_zabbix_templategroup/tasks", "ftype": "dir", "chksum_type": null, "chksum_sha256": null, "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_user/tasks/for_zabbix_50_lower.yml", + "name": "tests/integration/targets/test_zabbix_templategroup/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "960a32c864695d7b54d7ca3ebbd6362f75f68f743814c807daa6c3a25d6ac1f3", + "chksum_sha256": "662a2a5ceb86492f24dcc84b4a1574458f7dc91d6fccce89a5332e10b598c357", "format": 1 }, { - "name": "tests/integration/targets/test_zabbix_user/tasks/for_zabbix_54_higher.yml", + "name": "tests/integration/targets/test_zabbix_token", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_token/meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_token/meta/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "8429bc7fe7d6eb2c2995bf0ba11f86a5a372b8f69d85e2c6e201c3fb7e89ef2d", + "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_token/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_token/tasks/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2e599a1030312d0e3f6d1ee00d11f7ab37d01e027d72920af79217d850ef5d62", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_user", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_user/meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_user/meta/main.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "63ae23343a8854777c0e014be5fdd33db6a6b78f96d22a889ad78556dc0ffa81", + "format": 1 + }, + { + "name": "tests/integration/targets/test_zabbix_user/tasks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, "format": 1 }, { "name": "tests/integration/targets/test_zabbix_user/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "4d358b1fcd45a8d856b9cc09907e6b9067be79fd28b06d0b5f405858b8d50432", + "chksum_sha256": "6498f5e2a9997a379df9ea0cffd014d0ffe641c97e100d8131caa212bf17357a", "format": 1 }, { @@ -3329,14 +3294,14 @@ "name": "tests/integration/targets/test_zabbix_user_directory/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "afa7e354768d1130b16aed9d20fa8d0a380862b09aeb8d2b2a1dfe26da7c459b", + "chksum_sha256": "c21b05f92bd9124c347dda31aba1c1d3fa83bb913d143b5f9559bc21dfdad659", "format": 1 }, { "name": "tests/integration/targets/test_zabbix_user_directory/tasks/zabbix_user_directory_tests.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "59b6b651e26c5446ee51ca5d8a13303e984f3e07cb48c1582191c60c3fbf42ca", + "chksum_sha256": "4e00e6a07ca59e6c3069ee133736fa73349ceb15e7068fa0f309ed98683ab05c", "format": 1 }, { @@ -3371,7 +3336,7 @@ "name": "tests/integration/targets/test_zabbix_user_info/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "6ee6a2f0426d77871f9ca6050be5199982f6207777f29d978802ea308d52d32a", + "chksum_sha256": "4ed2dfa6079ec2bb75e8dae4428fa9782e712c334669b3d7d590b7495e77513e", "format": 1 }, { @@ -3406,7 +3371,7 @@ "name": "tests/integration/targets/test_zabbix_user_role/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "291ef542c12c0fc5733ed61244f28fd19de5c5243afb3f3e8633a0311d93cbf9", + "chksum_sha256": "a62abe29a82864a1553a383c0be1df01739da70fc3818ca5ad005eed733a5dc3", "format": 1 }, { @@ -3441,63 +3406,7 @@ "name": "tests/integration/targets/test_zabbix_usergroup/tasks/main.yml", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "701e889a652a7969c946234c571539d820bcd13fc7011650e858e42bcb0e8f09", - "format": 1 - }, - { - "name": "tests/sanity", - "ftype": "dir", - "chksum_type": null, - "chksum_sha256": null, - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.10.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "3fc63c84b6cef2e284d1e5aaa1c4f564e6b27d7ed7961626cbbb8495bdc105b3", - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.11.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "3fc63c84b6cef2e284d1e5aaa1c4f564e6b27d7ed7961626cbbb8495bdc105b3", - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.12.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "4ba3e638c5c97cf697071ccf1c64d3e1f44ca092e9c3a25f85e9af032edd679d", - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.13.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "4ba3e638c5c97cf697071ccf1c64d3e1f44ca092e9c3a25f85e9af032edd679d", - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.14.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "4ba3e638c5c97cf697071ccf1c64d3e1f44ca092e9c3a25f85e9af032edd679d", - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.15.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "4ba3e638c5c97cf697071ccf1c64d3e1f44ca092e9c3a25f85e9af032edd679d", - "format": 1 - }, - { - "name": "tests/sanity/ignore-2.9.txt", - "ftype": "file", - "chksum_type": "sha256", - "chksum_sha256": "b4e32eab851387385a480a7d46bf2d81335209f52cf1c671b2ea98a452a4f3d2", + "chksum_sha256": "2a5b4a1177a9dee238d5a1996912340563a30a4ebfc347e86572cfa4dde31170", "format": 1 }, { @@ -3511,7 +3420,7 @@ "name": ".gitignore", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "1a10d9ab655f99e50b057fe85f896dae304c1bcb8e59c793cc88c61321e2713f", + "chksum_sha256": "d59ffed224790089369e13daac9f696d47de6e02428ee81f01c491ad4ace9d82", "format": 1 }, { @@ -3525,7 +3434,7 @@ "name": "CHANGELOG.rst", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "ec873a72b857853deae0579634953269e2ebe7b8ff95522446a8b4172ecf7123", + "chksum_sha256": "f963b76b08f69f8aac6b8daf732d95ce00e1670316f7e8f7bcb674f8d2e3aa6c", "format": 1 }, { @@ -3539,7 +3448,7 @@ "name": "CONTRIBUTING.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "51891b42027e0b07b423a132022fb03a93a696bc00f1347af29754fb545a8a72", + "chksum_sha256": "c2b1b3f7d408b098332b41c93a6a57bbd3ab05cad66b0f94b5245a908af1e155", "format": 1 }, { @@ -3567,7 +3476,7 @@ "name": "README.md", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e59ef9030664aba9bfff75bee58c59a9f33e9154b988508b7a1d1a4542d4d0fa", + "chksum_sha256": "e47ca851f19b23497aa052424107b157400ef0d16cc745b1151fcff933ca2b86", "format": 1 }, { diff --git a/ansible_collections/community/zabbix/MANIFEST.json b/ansible_collections/community/zabbix/MANIFEST.json index a54e80845..37c48a609 100644 --- a/ansible_collections/community/zabbix/MANIFEST.json +++ b/ansible_collections/community/zabbix/MANIFEST.json @@ -2,11 +2,13 @@ "collection_info": { "namespace": "community", "name": "zabbix", - "version": "1.9.3", + "version": "2.3.1", "authors": [ "Dusan Matejka (@D3DeFi)", "sky-joker (@sky-joker)", - "Werner Dijkerman (@dj-wasabi)" + "Werner Dijkerman (@dj-wasabi)", + "Troy Ward (@pyrodie18)", + "Evgeny Yurchenko (@BGmot)" ], "readme": "README.md", "tags": [ @@ -18,7 +20,7 @@ "license_file": "LICENSE", "dependencies": { "ansible.windows": "*", - "ansible.netcommon": "*", + "ansible.netcommon": ">=3.1.1", "ansible.posix": "*", "community.general": "*", "community.mysql": "*", @@ -33,7 +35,7 @@ "name": "FILES.json", "ftype": "file", "chksum_type": "sha256", - "chksum_sha256": "e476cd027a2477b8d6417c251a409f4c2b040c9ee9a78ce6facf099912452868", + "chksum_sha256": "ed1fe1d72e38eb5978be766233f7389e444c2dcaded74877d323c41ac9712a46", "format": 1 }, "format": 1 diff --git a/ansible_collections/community/zabbix/README.md b/ansible_collections/community/zabbix/README.md index ca0f79717..be268fc4a 100644 --- a/ansible_collections/community/zabbix/README.md +++ b/ansible_collections/community/zabbix/README.md @@ -43,6 +43,7 @@ Click on the name of a plugin or module to view that content's documentation: - [zabbix_discovery_rule](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_discovery_rule_module.html) - [zabbix_globalmacro](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_globalmacro_module.html) - [zabbix_group_info](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_group_info_module.html) + - [zabbix_group_events_info](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_group_events_info_module.html) - [zabbix_group](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_group_module.html) - [zabbix_host_events_info](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_host_events_info_module.html) - [zabbix_host_info](https://docs.ansible.com/ansible/latest/collections/community/zabbix/zabbix_host_info_module.html) @@ -80,9 +81,6 @@ This is especially important for some of the Zabbix roles that require you to ** For the majority of modules, however, you can get away with just: -```bash -pip install zabbix-api -``` #### Ansible 2.10 and higher With the release of Ansible 2.10, modules have been moved into collections. With the exception of ansible.builtin modules, this means additonal collections must be installed in order to use modules such as seboolean (now ansible.posix.seboolean). The following collections are now frequently required: `ansible.posix` and `community.general`. Installing the collections: @@ -106,7 +104,7 @@ You can also include it in a `requirements.yml` file along with other required c --- collections: - name: community.zabbix - version: 1.9.3 + version: 2.3.1 - name: ansible.posix version: 1.3.0 - name: community.general @@ -133,7 +131,7 @@ To use a module or role from this collection, reference them with their Fully Qu ... - name: If Zabbix WebUI runs on non-default (zabbix) path, e.g. http://<FQDN>/zabbixeu - set_fact: + ansible.builtin.set_fact: ansible_zabbix_url_path: 'zabbixeu' - name: Using Zabbix collection to manage Zabbix Server's elements with username/password @@ -206,7 +204,7 @@ Or you include collection name `community.zabbix` in the playbook's `collections ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 tasks: - name: Ensure host is monitored by Zabbix - zabbix_host: + community.zabbix.zabbix_host: ... ``` @@ -220,8 +218,6 @@ zabbix_api_http_password: "password" Main priority is to support Zabbix releases which have official full support from Zabbix LLC. Please checkout the versions at [Zabbix Life Cycle & Release Policy](https://www.zabbix.com/life_cycle_and_release_policy) page. -> We aim to cover at least two LTS releases. For example, currently we support LTS 4.0 + 5.0 and with LTS 6.0 we will drop 4.0. But we do our best to also include the latest point releases - for example currently this is 5.4 which should be supperseeded by 6.2 then. - Support for Zabbix LTS versions will be dropped with Major releases of the collection and mostly affect modules. Each role is following its unique support matrix. You should always consult documentation of roles in *docs/* directory. If you find any inconsistencies with the version of Zabbix you are using, feel free to open a pull request or an issue and we will try to address it as soon as possible. In case of pull requests, please make sure that your changes will not break any existing functionality for currently supported Zabbix releases. diff --git a/ansible_collections/community/zabbix/changelogs/.plugin-cache.yaml b/ansible_collections/community/zabbix/changelogs/.plugin-cache.yaml index afdd4fd6c..9ea52adc2 100644 --- a/ansible_collections/community/zabbix/changelogs/.plugin-cache.yaml +++ b/ansible_collections/community/zabbix/changelogs/.plugin-cache.yaml @@ -1,10 +1,12 @@ -objects: {} +objects: + role: {} plugins: become: {} cache: {} callback: {} cliconf: {} connection: {} + filter: {} httpapi: zabbix: description: HttpApi Plugin for Zabbix @@ -22,6 +24,11 @@ plugins: name: zabbix_action namespace: '' version_added: null + zabbix_api_info: + description: Retrieve Zabbix API info + name: zabbix_api_info + namespace: '' + version_added: 2.1.0 zabbix_authentication: description: Update Zabbix authentication name: zabbix_authentication @@ -47,6 +54,11 @@ plugins: name: zabbix_group namespace: '' version_added: null + zabbix_group_events_info: + description: Get all triggers about a Zabbix group + name: zabbix_group_events_info + namespace: '' + version_added: null zabbix_group_info: description: Gather information about Zabbix hostgroup name: zabbix_group_info @@ -102,11 +114,11 @@ plugins: name: zabbix_proxy_info namespace: '' version_added: 1.5.0 - zabbix_screen: - description: Create/update/delete Zabbix screens - name: zabbix_screen + zabbix_regexp: + description: Create/update/delete Zabbix regular expression + name: zabbix_regexp namespace: '' - version_added: null + version_added: 2.1.0 zabbix_script: description: Create/update/delete Zabbix scripts name: zabbix_script @@ -117,8 +129,13 @@ plugins: name: zabbix_service namespace: '' version_added: null + zabbix_settings: + description: Update Zabbix global settings. + name: zabbix_settings + namespace: '' + version_added: 2.1.0 zabbix_template: - description: Create/update/delete/dump Zabbix template + description: Create/update/delete Zabbix template name: zabbix_template namespace: '' version_added: null @@ -127,6 +144,16 @@ plugins: name: zabbix_template_info namespace: '' version_added: null + zabbix_templategroup: + description: Create/delete Zabbix template groups + name: zabbix_templategroup + namespace: '' + version_added: null + zabbix_token: + description: Create/Update/Generate/Delete Zabbix token. + name: zabbix_token + namespace: '' + version_added: 2.1.0 zabbix_user: description: Create/update/delete Zabbix users name: zabbix_user @@ -160,5 +187,6 @@ plugins: netconf: {} shell: {} strategy: {} + test: {} vars: {} -version: 1.9.3 +version: 2.3.1 diff --git a/ansible_collections/community/zabbix/changelogs/changelog.yaml b/ansible_collections/community/zabbix/changelogs/changelog.yaml index dc62a39eb..600e0ab78 100644 --- a/ansible_collections/community/zabbix/changelogs/changelog.yaml +++ b/ansible_collections/community/zabbix/changelogs/changelog.yaml @@ -876,3 +876,219 @@ releases: - zabbix_user_media_mailto.yml - zabbix_user_sendto.yaml release_date: '2023-04-03' + 2.0.0: + changes: + breaking_changes: + - agent role - removed support for Darwin, Amazon, Fedora, XCP-ng, Suse, Mint, + and Sangoma operating systems + - agent role - removed support for zabbix_create_host and replaced it with zabbix_agent_host_state + - agent role - removed support for zabbix_create_hostgroup and replaced it with + zabbix_agent_hostgroups_state + - agent role - removed support for zabbix_http_password, zabbix_api_http_password, + zabbix_api_pass, and zabbix_api_login_pass and replaced it with zabbix_api_login_pass + - agent role - removed support for zabbix_http_user, zabbix_api_http_user, zabbix_api_user, + and zabbix_api_login_user and replaced it with zabbix_api_login_user + - agent role - removed support for zabbix_inventory_mode and replaced it with + zabbix_agent_inventory_mode + - agent role - removed support for zabbix_link_templates adn replaced it with + zabbix_agent_link_templates + - agent role - removed support for zabbix_macros and replaced it with zabbix_agent_macros + - agent role - removed support for zabbix_proxy and replaced it with zabbix_agent_proxy + - agent role - removed support for zabbix_update_host and replaced it with zabbix_agent_host_update + - all modules - dropped support of Zabbix versions < 6.0 + - all roles - removed support for the zabbix_version variable. + - all roles - removed support for all versions of Zabbix < 6.0. + - all roles - removed support for installation from epel and non-standard repositories + - dropped support of zabbix-api to make REST API calls to Zabbix + - proxy role - removed support for zabbix_database_creation and replaced it + with zabbix_proxy_database_creation + - proxy role - removed support for zabbix_database_sqlload and replaced it + with zabbix_proxy_database_sqlload + - proxy role - removed support for zabbix_selinux and replaced it with zabbix_proxy_selinux + - server role - removed support for zabbix_server_mysql_login_password and replaced + with zabbix_server_dbpassword + - server role - removed support for zabbix_server_mysql_login_user and replaced + with zabbix_server_dbuser + - stopped supporting Ansible < 2.12 + - stopped supporting Python < 3.9 + - zabbix_action - message parameter renamed to op_message + - zabbix_group_facts module - removed in favour of zabbix_group_info + - zabbix_host_facts module - removed in favour of zabbix_host_info + minor_changes: + - Replaced usage of deprecated apt key management in Debian based distros - + See https://wiki.debian.org/DebianRepository/UseThirdParty + - Standardized tags across all roles. + - Updated all roles to default to version 6.4 for install. + - all roles - removed unused variables from defaults + - all roles - standardized testing matrix to check all supported versions and + operating systems. + - all roles - temporarily disable epel repo on zabbix installation tasks + - all roles - updated documentation. + - inventory plugin - switched from using zabbix-api to custom implementation + adding authentication with tokens + - inventory script - re-coded to stop using zabbix-api. API tokens support added. + - web role - removed support for htpasswd + removed_features: + - agent role - removed support to configure firewall + - web role - removed installation of apache, debian, and php + fragments: + - 2_0_update.yml + - 941_github_runner.yml + - 963-drop-zabbix-api.yml + - 964_tag_cleanup.yml + - 969_replace_apt_key.yml + - 976_old_zabbix_versions_removal.yml + - default_ver.yml + - inventory_script.yml + - python-ansible.yml + release_date: '2023-05-04' + 2.0.1: + changes: + bugfixes: + - Proxy and Agent Roles - Added `zabbix_api_use_ssl` variable to allow secure + API connections + - Web Role - Added defaults and documentation for `zabbix_apache_custom_includes` + - agent - Handled undefined variable error for Windows default versions + - all roles - Added option to selectively disable a repo on Redhat installs + fragments: + - 986.yml + - 990.yml + - api_ssl.yml + - disable_repo.yml + release_date: '2023-05-26' + 2.1.0: + changes: + bugfixes: + - agent role - Added missing become statement to allow run to role as nonroot + - zabbix_host module - fix updating hosts that were discovered via LLD + - zabbix_proxy role - failed at version validation. Fix adds cast of zabbix_proxy_version + to float, similarly to the other roles. + - zabbix_proxy role - undefined vars at updating proxy definition. Fix adds + null defaults for zabbix_proxy_tlsaccept and zabbix_proxy_tlsconnect. + - zabbix_web role - removed 'ssl on;' nginx configuration, which is no longer + supported since nginx version 1.25.1. + minor_changes: + - Multiple Roles - Replaced depricated 'include' statements with 'include_tasks' + - Update action_groups variable in runtime.yml + - all roles - Added support for Debian 12 (Bookworm) + - all roles - Delete gpg ids variable. + - all roles - Modified to allow a non-root user to run the role. + - all roles - Updated testing to account for the correct version of Zabbix + - zabbix_hostmacro module - Add description property for Host macro creation/update. + Allow to set/update description of Zabbix host macros. + - zabbix_proxy - Added installation of PyMySQL pip package + - zabbix_proxy - Modified installation of Centos 7 MySQL client + - zabbix_proxy - Standardized MySQL client installed on Debian and Ubuntu + - zabbix_regexp module added + - zabbix_settings module added + - zabbix_token module added + fragments: + - 1025-delete_vars_zabbix.yml + - 1029-update_action_groups.yml + - 732-zabbix-regexp.yml + - 991-zabbix-token.yml + - 993-zabbix-settings.yml + - agent_become.yml + - debian12.yml + - discovered_hosts_update.yml + - hostmacro_modules.yml + - include_tasks.yml + - missing.yml + - nginx_ssl_fix.yml + - non_root.yml + - proxy_role_fix.yml + modules: + - description: Create/update/delete Zabbix regular expression + name: zabbix_regexp + namespace: '' + - description: Update Zabbix global settings. + name: zabbix_settings + namespace: '' + - description: Create/Update/Generate/Delete Zabbix token. + name: zabbix_token + namespace: '' + release_date: '2023-06-01' + 2.2.0: + changes: + bugfixes: + - zabbix_inventory - fixed handeling of add_zabbix_groups option + - zabbix_template - fix template export when template's content has "error" + word + - zabbix_web role - fix variable naming issues (undefined) to zabbix_web_version + and zabbix_web_apt_repository + minor_changes: + - Added zabbix_group_events_info module + - action module - Added notify_if_canceled property + - agent and proxy roles - Set default `zabbix_api_server_port` to 80 or 443 + based on `zabbix_api_use_ssl` + - agent role - Removed duplicative Windows agent task + - agent role - Standardized default yum priority to 99 + - all roles - Re-added ability to override Debian repo source + - all roles - Updated Debian repository format to 822 standard + - various - updated testing modules + - various - updated to fully qualified module names + - zabbix agent - Added capability to add additional configuration includes + - zabbix_api_info module added + - zabbix_user module - add current_passwd optional parameter to enable password + updating of the currently logged in user (https://www.zabbix.com/documentation/6.4/en/manual/api/reference/user/update) + fragments: + - 1058-zabbix_template_corner_case.yml + - 1081_fqmn.yml + - 733-zabbix-api_info.yml + - 921-action_notify_if_cancled.yml + - additional_includes.yml + - api-port.yml + - current_passwd_user_module.yml + - deb822.yml + - duplicate-windows-agent.yml + - module_group_events_info.yml + - web_role_vars_fix.yml + - yum-priority.yml + release_date: '2023-10-06' + 2.3.0: + changes: + bugfixes: + - api module - Fixed certificiate errors + - proxy and server roles - Defaulted location of fping and fping6 based on OS. + - proxy role - Removed requirement for mysql group definition. + - server role - typo in configuration var StasAllowedIP to StatsAllowedIP + - zabbix-{agent, javagateway, proxy, server, web} - support raspberry pi without + repository url specification + minor_changes: + - api_requests - Handled error from depricated CertificateError class + - multiple roles - Removed unneeded Apt Clean commands. + - proxy role - Updated MariaDB version for Centos 7 to 10.11 + - zabbix web - Allowed the independent configuration of php-fpm without creating + vhost. + - zabbix_host_info - added ability to get all the hosts configured in Zabbix + - zabbix_proxy role - Add variable zabbix_proxy_dbpassword_hash_method to control + whether you want postgresql user password to be hashed with md5 or want to + use db default. When zabbix_proxy_dbpassword_hash_method is set to anything + other than md5 then do not hash the password with md5 so you could use postgresql + scram-sha-256 hashing method. + - zabbix_server role - Add variable zabbix_server_dbpassword_hash_method to + control whether you want postgresql user password to be hashed with md5 or + want to use db default. When zabbix_server_dbpassword_hash_method is set to + anything other than md5 then do not hash the password with md5 so you could + use postgresql scram-sha-256 hashing method. + - zabbix_templategroup module added + fragments: + - 1134.yml + - 1136.yml + - 1142.yml + - fping.yml + - host_info_all_hosts.yml + - php_fpm_config.yml + - pr_1104.yml + - pr_647.yml + - proxy_mysql.yml + - pymysql.yml + - raspberrypi.yml + release_date: '2024-01-02' + 2.3.1: + changes: + bugfixes: + - Avoid to update user-directory configuration in dry run. + fragments: + - 1156-bugfix_zabbix_user_directory_dryrun.yml + release_date: '2024-01-10' diff --git a/ansible_collections/community/zabbix/changelogs/roles_zabbix64.yml b/ansible_collections/community/zabbix/changelogs/roles_zabbix64.yml deleted file mode 100644 index d9b8eb397..000000000 --- a/ansible_collections/community/zabbix/changelogs/roles_zabbix64.yml +++ /dev/null @@ -1,2 +0,0 @@ -minor_changes: - - all roles - updated to support Zabbix 6.4. diff --git a/ansible_collections/community/zabbix/docs/PUBLISHING_TO_GALAXY.md b/ansible_collections/community/zabbix/docs/PUBLISHING_TO_GALAXY.md index 7258bf6c8..7272f1006 100644 --- a/ansible_collections/community/zabbix/docs/PUBLISHING_TO_GALAXY.md +++ b/ansible_collections/community/zabbix/docs/PUBLISHING_TO_GALAXY.md @@ -26,16 +26,19 @@ git push origin X.Y.Z ``` -2. Create new Release pointing to new X.Y.Z tag https://github.com/ansible-collections/community.zabbix/releases +2. All community.* collections are usually published by Zuul, which works by you having to push a tag, and Zuul will build the collection from that tag (with the version in galaxy.yml set to the tag's version) and publish it. It's usually a good idea to take a look at [Zuul](https://ansible.softwarefactory-project.io/zuul/status) when pushing a tag and watch the release process to see whether it succeeds or not (and afterwards check on [Galaxy](https://galaxy.ansible.com/community/zabbix) whether the newest version shows up - note that it can make a few seconds after publishing finished until it actually shows up; that's new with the new Galaxy). -Additional manual steps are required when automatic publish to Ansible Galaxy is not enabled in the repository. This -requires a user who has access to the `community.zabbix` namespace on Ansible Galaxy to publish the build artifact. + If there is an error in building and it seems to be on Zuul side, the best thing is to re-push the tag to trigger the publish step another time. For that, assuming the remote for github.com/ansible-collections/community.zabbix is called upstream, you can do -3. Run the following commands to build and release the new version on Galaxy: - ``` - ansible-galaxy collection build - ansible-galaxy collection publish ./community-zabbix-$VERSION_HERE.tar.gz - ``` + ``` + git push upstream :2.3.0 # to delete the tag + git push --tags upstream # to re-push all tags + ``` + That should delete and re-create the tag, and thus trigger Zuul again to publish the collection. + +3. If still having problems in step 2. then create a post in "Get Help" section of [Ansible forum](https://forum.ansible.com/c/help/6/none) so somebody from admins can take a look and see/fix why new version has not been published to Galaxy (e.g. https://forum.ansible.com/t/access-to-collection/2295/4). + +4. Create new Release pointing to new X.Y.Z tag https://github.com/ansible-collections/community.zabbix/releases + -After the version is published, verify it exists on the [Zabbix Collection Galaxy page](https://galaxy.ansible.com/community/zabbix). diff --git a/ansible_collections/community/zabbix/docs/UPGRADE.md b/ansible_collections/community/zabbix/docs/UPGRADE.md deleted file mode 100644 index 7784f5842..000000000 --- a/ansible_collections/community/zabbix/docs/UPGRADE.md +++ /dev/null @@ -1,194 +0,0 @@ -__Upgrade__ - -Table of content - -- [1.0.0](#100) - * [Roles](#roles) - + [Proxy](#proxy) - + [Java Gateway](#java-gateway) -- [0.2.0](#020) - * [Roles](#roles-1) - + [Agent](#agent) - + [Server](#server) - + [Proxy](#proxy-1) - + [Web](#web) - + [Java Gateway](#java-gateway-1) - -This document provides an overview of all the changes that are needed to be applied to have a correctly working environment per version. If a version is not part of this document, then there are no changes needed to apply. - -## 1.5.0 - -### Roles - -#### Agent - -The following properties are added in the `zabbix_agent` role. - -* `zabbix_api_timeout = 30` -* `zabbix_agent_tls_subject = "{{ zabbix_agent_tlsservercertsubject }}"` -* `zabbix_agent2_server = "{{ zabbix_agent_server }}"` -* `zabbix_agent2_serveractive = "{{ zabbix_agent_serveractive }}"` -* `zabbix_agent2_allow_key = "{{ zabbix_agent_allow_key }}"` -* `zabbix_agent2_deny_key = "{{ zabbix_agent_deny_key }}"` -* `zabbix_agent2_tls_subject = "{{ zabbix_agent2_tlsservercertsubject }}"` - -NOTE: The original properties can still be used but it's suggested to update to -use the new ones. - -The following properties are renamed in the `zabbix_agent` role. - -| From | To | -|-------------------------------|-------------------------------| -| zabbix_url | zabbix_api_server_url | -| zabbix_agent_server_url | zabbix_api_server_url | -| zabbix_http_user | zabbix_api_http_user | -| zabbix_http_password | zabbix_api_http_password | -| zabbix_api_user | zabbix_api_login_user | -| zabbix_api_pass | zabbix_api_login_pass | -| zabbix_validate_certs | zabbix_api_validate_certs | -| zabbix_create_hostgroup | zabbix_agent_hostgroups_state | -| zabbix_macros | zabbix_agent_macros | -| zabbix_inventory_mode | zabbix_agent_inventory_mode | -| zabbix_link_templates | zabbix_agent_link_templates | -| zabbix_proxy | zabbix_agent_proxy | -| zabbix_update_host | zabbix_agent_host_update | -| zabbix_create_host | zabbix_agent_host_state | -| zabbix_visible_hostname | zabbix_agent_visible_hostname | - -NOTE: the old parameters are still valid but it's suggested to update to use the -new ones. - -#### Proxy - -The following properties are added in the `zabbix_proxy` role. - -* `zabbix_api_timeout = 30` -* `zabbix_proxy_tls_subject = "{{ zabbix_proxy_tlsservercertsubject }}"` - -The following properties are renamed in the `zabbix_proxy` role. - -| From | To | -|----------------------------|---------------------------------| -| zabbix_server_host | zabbix_proxy_server | -| zabbix_server_port | zabbix_proxy_serverport | -| zabbix_proxy_localbuffer | zabbix_proxy_proxylocalbuffer | -| zabbix_proxy_offlinebuffer | zabbix_proxy_proxyofflinebuffer | -| zabbix_create_proxy | zabbix_proxy_state | -| zabbix_url | zabbix_api_server_url | -| zabbix_http_user | zabbix_api_http_user | -| zabbix_http_password | zabbix_api_http_password | -| zabbix_api_user | zabbix_api_login_user | -| zabbix_api_pass | zabbix_api_login_pass | -| zabbix_validate_certs | zabbix_api_validate_certs | - -NOTE: the old parameters are still valid but it's suggested to update to use the -new ones. - -## 1.0.0 - -### Roles - -#### Proxy - -The following property is renamed in the `zabbix_proxy` role. - -|From|To| -|----|--| -|`zabbix_version`|`zabbix_proxy_version`| - -NOTE: The `zabbix_version` can still be used, but will be deprecated in later releases. - -#### Java Gateway - -The following properties are renamed in the `zabbix_javagateway` role. - -|From|To| -|----|--| -|`zabbix_version`|`zabbix_javagateway_version`| -|`javagateway_package_state`|`zabbix_javagateway_package_state`| -|`javagateway_pidfile`|`zabbix_javagateway_pidfile`| -|`javagateway_listenip`|`zabbix_javagateway_listenip`| -|`javagateway_listenport`|`zabbix_javagateway_listenport`| -|`javagateway_startpollers`|`zabbix_javagateway_startpollers`| - -NOTE: The `zabbix_version` can still be used, but will be deprecated in later releases. - -## 0.2.0 - -### Roles - -#### Agent - -A 1-on-1 copy of the Ansible role `dj-wasabi.zabbix-agent` to this collection. Due to naming of roles as part of a collection, some characters (Like the `-`) are not allowed anymore. This role is therefore renamed from `zabbix-agent` to `zabbix_agent`. - -Example of using the role in this collection: -```yaml -- hosts: all - roles: - - role: community.zabbix.zabbix_agent - zabbix_agent_server: 192.168.33.30 - zabbix_agent_serveractive: 192.168.33.30 -``` - -#### Server - -A 1-on-1 copy of the Ansible role `dj-wasabi.zabbix-server` to this collection. Due to naming of roles as part of a collection, some characters (Like the `-`) are not allowed anymore. This role is therefore renamed from `zabbix-server` to `zabbix_server`. - -Example of using the role in this collection:: -```yaml -- hosts: zabbix-server - roles: - - role: community.zabbix.zabbix_server - zabbix_server_database: mysql - zabbix_server_database_long: mysql - zabbix_server_dbport: 3306 -``` - -#### Proxy - -A 1-on-1 copy of the Ansible role `dj-wasabi.zabbix-proxy` to this collection. Due to naming of roles as part of a collection, some characters (Like the `-`) are not allowed anymore. This role is therefore renamed from `zabbix-proxy` to `zabbix_proxy`. - -Example of using the role in this collection:: -```yaml -- hosts: zabbix-proxy - roles: - - role: community.zabbix.zabbix_proxy - zabbix_proxy_server: 192.168.1.1 - zabbix_server_database: mysql - zabbix_server_database_long: mysql - zabbix_server_dbport: 3306 -``` - -#### Web - -A 1-on-1 copy of the Ansible role `dj-wasabi.zabbix-web` to this collection. Due to naming of roles as part of a collection, some characters (Like the `-`) are not allowed anymore. This role is therefore renamed from `zabbix-web` to `zabbix_web`. - -Example of using the role in this collection:: -```yaml -- hosts: zabbix-web - become: yes - roles: - - role: geerlingguy.apache - - role: community.zabbix.zabbix_web - zabbix_url: zabbix.mydomain.com - zabbix_server_hostname: zabbix-server - zabbix_server_database: mysql - zabbix_server_database_long: mysql - zabbix_server_dbport: 3306 -``` - -#### Java Gateway - -A 1-on-1 copy of the Ansible role `dj-wasabi.zabbix-javagateway` to this collection. Due to naming of roles as part of a collection, some characters (Like the `-`) are not allowed anymore. This role is therefore renamed from `zabbix-javagateway` to `zabbix_javagateway`. - -Example of using the role in this collection:: -```yaml -- hosts: zabbix-server - roles: - - role: community.zabbix.zabbix_server - zabbix_server_database: mysql - zabbix_server_database_long: mysql - zabbix_server_dbport: 3306 - zabbix_server_javagateway: 192.168.1.1 - - role: community.zabbix.zabbix_javagateway -``` diff --git a/ansible_collections/community/zabbix/docs/ZABBIX_AGENT_ROLE.md b/ansible_collections/community/zabbix/docs/ZABBIX_AGENT_ROLE.md index f3fe06c9d..aa73fab3a 100644 --- a/ansible_collections/community/zabbix/docs/ZABBIX_AGENT_ROLE.md +++ b/ansible_collections/community/zabbix/docs/ZABBIX_AGENT_ROLE.md @@ -44,15 +44,10 @@ This role will work on the following operating systems: * Red Hat - * Fedora * Debian * Ubuntu - * opensuse * Windows (Best effort) - * macOS - -So, you'll need one of those operating systems.. :-) -Please send Pull Requests or suggestions when you want to use this role for other Operating systems. + * macOS (Best effort) ## Ansible 2.10 and higher @@ -62,7 +57,7 @@ With the release of Ansible 2.10, modules have been moved into collections. Wit ansible-galaxy collection install ansible.posix ansible-galaxy collection install community.general ``` -If you are willing to create host_groups and hosts in Zabbix via API as a part of this role execution then you need to install `ansible.netcommon` collection too: +If you are wanting to create host_groups and hosts in Zabbix via API as a part of this role execution then you need to install `ansible.netcommon` collection too: ``` ansible-galaxy collection install ansible.netcommon @@ -95,24 +90,18 @@ To successfully complete the install the role requires `python-netaddr` on the c See the following list of supported Operating systems with the Zabbix releases: -| Zabbix | 6.4 | 6.2 | 6.0 | 5.4 | 5.2 | 5.0 (LTS)| 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----|-----|-----|----------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | V | V | V | V | V | V | V | V | V | -| Red Hat Fam 6 | V | V | V | V | V | V | | | V | -| Red Hat Fam 5 | | | V | V | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | V | V | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | V | V | V | V | V | V | V | V | | -| Ubuntu 14.04 trusty | V | V | V | V | V | V | V | V | V | -| Debian 10 buster | V | V | V | V | V | V | V | | | -| Debian 9 stretch | V | V | | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Red Hat Fam 7 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | V | V | V | +| Debian 12 bookworm | V | V | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | V | V | V | + # Getting started @@ -124,7 +113,7 @@ In order to get the Zabbix Agent running, you'll have to define the following pr * `zabbix_agent(2)_server` * `zabbix_agent(2)_serveractive` (When using active checks) -The `zabbix_agent_version` is optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_agent_version: 4.0`, `zabbix_agent_version: 3.4` or `zabbix_agent_version: 2.2`. +The `zabbix_agent_version` is optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_agent_version: 6.0`. The `zabbix_agent(2)_server` (and `zabbix_agent(2)_serveractive`) should contain the ip or fqdn of the host running the Zabbix Server. @@ -140,16 +129,13 @@ The following is an overview of all available configuration default for this rol ### Overall Zabbix -* `zabbix_agent_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. +* `zabbix_agent_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.4, 6.2, or 6.0 * `zabbix_agent_version_minor`: When you want to specify a minor version to be installed. Is also used for `zabbix_sender` and `zabbix_get`. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. +* `zabbix_agent_disable_repo`: A list of repos to disable during install. Default `epel`. +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_agent_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### SElinux @@ -158,7 +144,7 @@ The following is an overview of all available configuration default for this rol ### Zabbix Agent * `zabbix_agent_ip`: The IP address of the host. When not provided, it will be determined via the `ansible_default_ipv4` fact. -* `zabbix_agent2`: Default: `False`. When you want to install the `Zabbix Agent2` instead of the "old" `Zabbix Agent`. +* `zabbix_agent2`: Default: `False`. When you want to install the `Zabbix Agent2` instead of the "old" `Zabbix Agent`.zabbix_agent_version * `zabbix_agent_listeninterface`: Interface zabbix-agent listens on. Leave blank for all. * `zabbix_agent_package_remove`: If `zabbix_agent2: True` and you want to remove the old installation. Default: `False`. * `zabbix_agent_package`: The name of the zabbix-agent package. Default: `zabbix-agent`. In case for EPEL, it is automatically renamed. @@ -174,7 +160,6 @@ The following is an overview of all available configuration default for this rol * `zabbix_agent_userparameters_scripts_src`: indicates the relative path (from `files/`) where userparameter scripts are searched * `zabbix_agent_runas_user`: Drop privileges to a specific, existing user on the system. Only has effect if run as 'root' and AllowRoot is disabled. * `zabbix_agent_become_on_localhost`: Default: `True`. Set to `False` if you don't need to elevate privileges on localhost to install packages locally with pip. -* `zabbix_install_pip_packages`: Default: `True`. Set to `False` if you don't want to install the required pip packages. Useful when you control your environment completely. * `zabbix_agent_apt_priority`: Add a weight (`Pin-Priority`) for the APT repository. * `zabbix_agent_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. * `zabbix_agent_dont_detect_ip`: Default `false`. When set to `true`, it won't detect available ip addresses on the host and no need for the Python module `netaddr` to be installed. @@ -193,6 +178,7 @@ Otherwise it just for the Zabbix Agent or for the Zabbix Agent 2. * `zabbix_agent(2)_pidfile`: name of pid file. * `zabbix_agent(2)_logfile`: name of log file. * `zabbix_agent(2)_logfilesize`: maximum size of log file in mb. +* `zabbix_agent(2)_additional_include`: A list of additional complete paths to include in configuration * `zabbix_agent(2)_logtype`: Specifies where log messages are written to * `zabbix_agent(2)_debuglevel`: specifies debug level * `zabbix_agent(2)_sourceip`: source ip address for outgoing connections. @@ -261,16 +247,17 @@ These variables need to be overridden when you want to make use of the Zabbix AP Host encryption configuration will be set to match agent configuration. -* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth. -* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth. -* `zabbix_api_create_hosts`: Default: `False`. When you want to enable the Zabbix API to create/delete the host. This has to be set to `True` if you want to make use of `zabbix_agent_host_state`. -* `zabbix_api_create_hostgroup`: When you want to enable the Zabbix API to create/delete the hostgroups. This has to be set to `True` if you want to make use of `zabbix_agent_hostgroups_state`.Default: `False` * `zabbix_api_server_host`: The IP or hostname/FQDN of Zabbix server. Example: zabbix.example.com -* `zabbix_api_server_port`: TCP port to use to connect to Zabbix server. Example: 8080 -* `zabbix_api_use_ssl`: yes (Default) if we need to connect to Zabbix server over HTTPS -* `zabbix_api_validate_certs` : yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used +* `zabbix_api_use_ssl`: Is SSL required to connect to the Zabbix API server? Default: `false` +* `zabbix_api_server_port`: 80 if `zabbix_api_use_ssl` is `false` and 443 if `true` (Default) TCP port to use to connect to Zabbix server. Example: 8080 * `zabbix_api_login_user`: Username of user which has API access. * `zabbix_api_login_pass`: Password for the user which has API access. +* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_validate_certs`: yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used. +* `zabbix_api_timeout`: How many seconds to wait for API response (default 30s). +* `zabbix_api_create_hosts`: Default: `False`. When you want to enable the Zabbix API to create/delete the host. This has to be set to `True` if you want to make use of `zabbix_agent_host_state`. +* `zabbix_api_create_hostgroup`: When you want to enable the Zabbix API to create/delete the hostgroups. This has to be set to `True` if you want to make use of `zabbix_agent_hostgroups_state`.Default: `False` * `ansible_zabbix_url_path`: URL path if Zabbix WebUI running on non-default (zabbix) path, e.g. if http://<FQDN>/zabbixeu then set to `zabbixeu` * `zabbix_agent_hostgroups_state`: present (Default) if the hostgroup needs to be created or absent if you want to delete it. This only works when `zabbix_api_create_hostgroup` is set to `True`. * `zabbix_host_status`: enabled (Default) when host in monitored, disabled when host is disabled for monitoring. @@ -290,7 +277,7 @@ Host encryption configuration will be set to match agent configuration. **NOTE** -_Supporting Windows is a best effort (I don't have the possibility to either test/verify changes on the various amount of available Windows instances). PRs specific to Windows will almost immediately be merged, unless someone is able to provide a Windows test mechanism via Travis for Pull Requests._ +_Supporting Windows is a best effort (We don't have the possibility to either test/verify changes on the various amount of available Windows instances). PRs specific to Windows will almost immediately be merged, unless someone is able to provide a Windows test mechanism via Travis for Pull Requests._ When `(2)` is used in the name of the property, like `zabbix_agent(2)_win_logfile`, it will show that you can configure `zabbix_agent_win_logfile` for the Zabbix Agent configuration file and `zabbix_agent2_win_logfile` for the Zabbix Agent 2 configuration file. Otherwise it just for the Zabbix Agent or for the Zabbix Agent 2. @@ -308,6 +295,10 @@ Otherwise it just for the Zabbix Agent or for the Zabbix Agent 2. ## macOS Variables +**NOTE** + +_Supporting Windows is a best effort (We don't have the possibility to either test/verify changes on the various amount of available Windows instances). PRs specific to Windows will almost immediately be merged, unless someone is able to provide a Windows test mechanism via Travis for Pull Requests._ + * `zabbix_version_long`: The long (major.minor.patch) version of the Zabbix Agent. This will be used to generate the `zabbix_mac_download_link` link. * `zabbix_mac_download_link`: The download url to the `pkg` file. @@ -344,17 +335,6 @@ Keep in mind that using the Zabbix Agent in a Container requires changes to the * `zabbix_agent_docker_volumes`: A list with all directories that needs to be available in the Container. * `zabbix_agent_docker_env`: A dict with all environment variables that needs to be set for the Container. -## FirewallD/Iptables - -* `zabbix_agent_firewall_enable`: If IPtables needs to be updated by opening an TCP port for port configured in `zabbix_agent_listenport`. -* `zabbix_agent_firewall_source`: When provided, IPtables will be configuring to only allow traffic from this IP address/range. -* `zabbix_agent_firewalld_enable`: If firewalld needs to be updated by opening an TCP port for port configured in `zabbix_agent_listenport` and `zabbix_agent_jmx_listenport` if defined. -* `zabbix_agent_firewalld_source`: When provided, firewalld will be configuring to only allow traffic for IP configured in `zabbix_agent_server`. -* `zabbix_agent_firewalld_zone`: When provided, the firewalld rule will be attached to this zone (only if zabbix_agent_firewalld_enable is set to true). The default behavior is to use the default zone define by the remote host firewalld configuration. -* `zabbix_agent_firewall_action`: Default: `insert`. When to `insert` the rule or to `append` to IPTables. -* `zabbix_agent_firewall_chain`: Default `INPUT`. Which `chain` to add the rule to IPTables. - - ## IPMI variables * `zabbix_agent_ipmi_authtype`: IPMI authentication algorithm. Possible values are 1 (callback), 2 (user), 3 (operator), 4 (admin), 5 (OEM), with 2 being the API default. @@ -369,6 +349,17 @@ When the target host does not have access to the internet, but you do have a pro * `zabbix_http_proxy` * `zabbix_https_proxy` +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Dependencies There are no dependencies on other roles. @@ -440,10 +431,11 @@ Including an example of how to use your role (for instance, with variables passe - role: community.zabbix.zabbix_agent zabbix_agent_server: 192.168.33.30 zabbix_agent_serveractive: 192.168.33.30 - zabbix_api_server_url: http://zabbix.example.com - zabbix_api_use: true # use zabbix_api_create_hosts and/or zabbix_api_create_hostgroup from 0.8.0 + zabbix_api_server_host: zabbix.example.com zabbix_api_login_user: Admin zabbix_api_login_pass: zabbix + zabbix_api_create_hostgroup: true + zabbix_api_create_hosts: true zabbix_agent_host_state: present zabbix_host_groups: - Linux Servers @@ -465,10 +457,11 @@ You can also use the group_vars or the host_vars files for setting the variables ```yaml zabbix_agent_server: 192.168.33.30 zabbix_agent_serveractive: 192.168.33.30 - zabbix_api_server_url: http://zabbix.example.com - zabbix_api_use: true # use zabbix_api_create_hosts and/or zabbix_api_create_hostgroup from 0.8.0 + zabbix_api_server_host: zabbix.example.com zabbix_api_login_user: Admin zabbix_api_login_pass: zabbix + zabbix_api_create_hostgroup: true + zabbix_api_create_hosts: true zabbix_agent_host_state: present zabbix_host_groups: - Linux Servers diff --git a/ansible_collections/community/zabbix/docs/ZABBIX_JAVAGATEWAY_ROLE.md b/ansible_collections/community/zabbix/docs/ZABBIX_JAVAGATEWAY_ROLE.md index 70427d97c..1761c7f8b 100644 --- a/ansible_collections/community/zabbix/docs/ZABBIX_JAVAGATEWAY_ROLE.md +++ b/ansible_collections/community/zabbix/docs/ZABBIX_JAVAGATEWAY_ROLE.md @@ -29,29 +29,22 @@ This role will work on the following operating systems: * Ubuntu So, you'll need one of those operating systems.. :-) -Please send Pull Requests or suggestions when you want to use this role for other Operating systems. ## Zabbix Versions See the following list of supported Operating systems with the Zabbix releases. -| Zabbix | 6.4 | 6.2 | 6.0 (LTS) | 5.2 | 5.0 | 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----------|-----|-----|-----|-----------|-----------| -| Red Hat Fam 8 | V | V | V | V | V | V | | | -| Red Hat Fam 7 | | | | V | V | V | V | V | -| Red Hat Fam 6 | | | | V | V | | | V | -| Red Hat Fam 5 | | | | V | V | | | V | -| Fedora | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | | | | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | V | V | V | V | V | -| Debian 10 buster | V | V | V | V | V | V | | | -| Debian 9 stretch | | | | V | V | V | V | | -| Debian 8 jessie | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | V | V | -| macOS 10.15 | | | | | | V | V | | -| macOS 10.14 | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Red Hat Fam 7 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | V | V | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | V | V | V | # Role Variables @@ -61,17 +54,14 @@ The following is an overview of all available configuration default for this rol ### Overall Zabbix -* `zabbix_javagateway_version`: This is the version of zabbix. Default: 5.2. Can be overridden to 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo +The `zabbix_javagateway_version` is optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_javagateway_version: 6.0`. * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. +* `zabbix_javagateway_disable_repo`: A list of repos to disable during install. Default `epel`. * `zabbix_javagateway_package_state`: Default: `present`. Can be overridden to `latest` to update packages when needed. * `zabbix_javagateway_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_agent_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### Java Gatewaty @@ -106,6 +96,17 @@ or when using the zabbix-proxy: zabbix_proxy_javagateway: 192.168.1.2 ``` +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Example Playbook Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: diff --git a/ansible_collections/community/zabbix/docs/ZABBIX_PROXY_ROLE.md b/ansible_collections/community/zabbix/docs/ZABBIX_PROXY_ROLE.md index 6682f6c18..baec42155 100644 --- a/ansible_collections/community/zabbix/docs/ZABBIX_PROXY_ROLE.md +++ b/ansible_collections/community/zabbix/docs/ZABBIX_PROXY_ROLE.md @@ -77,24 +77,17 @@ ansible-galaxy collection install community.postgresql See the following list of supported Operating systems with the Zabbix releases. -| Zabbix | 6.4 | 6.2 | 6.0 | 5.4 | 5.2 | 5.0 (LTS)| 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----|-----|-----|-----------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | V | V | V | V | V | V | V | V | V | -| Red Hat Fam 6 | | | | | V | V | | | V | -| Red Hat Fam 5 | | | | | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | | | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | | V | V | V | V | V | -| Debian 10 buster | V | | V | V | V | V | V | | | -| Debian 9 stretch | V | | V | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Red Hat Fam 7 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | V | V | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | V | V | V | # Role Variables @@ -102,104 +95,49 @@ See the following list of supported Operating systems with the Zabbix releases. The following is an overview of all available configuration default for this role. -### Overall Zabbix - -* `zabbix_proxy_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2, 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. -* `zabbix_proxy_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo -* `zabbix_repo_yum`: A list with Yum repository configuration. -* `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. - -### SElinux - -* `zabbix_selinux`: Default: `False`. Enables an SELinux policy so that the Proxy will run. - ### Zabbix Proxy +* `zabbix_proxy_version`: Optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_proxy_version: 6.0`. +* `zabbix_proxy_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) * `zabbix_proxy_ip`: The IP address of the host. When not provided, it will be determined via the `ansible_default_ipv4` fact. * `zabbix_proxy_server`: The ip or dns name for the zabbix-server machine. -* `zabbix_proxy_serverport`: The port on which the zabbix-server is running. Default: 10051 -* `*zabbix_proxy_package_state`: Default: `present`. Can be overridden to `latest` to update packages * `zabbix_proxy_install_database_client`: Default: `True`. False does not install database client. -* `zabbix_proxy_become_on_localhost`: Default: `True`. Set to `False` if you don't need to elevate privileges on localhost to install packages locally with pip. * `zabbix_proxy_manage_service`: Default: `True`. When you run multiple Zabbix proxies in a High Available cluster setup (e.g. pacemaker), you don't want Ansible to manage the zabbix-proxy service, because Pacemaker is in control of zabbix-proxy service. -* `zabbix_install_pip_packages`: Default: `True`. Set to `False` if you don't want to install the required pip packages. Useful when you control your environment completely. -* `zabbix_proxy_startpreprocessors`: Number of pre-forked instances of preprocessing workers. The preprocessing manager process is automatically started when a preprocessor worker is started.This parameter is supported since Zabbix 4.2.0. -* `zabbix_proxy_username`: Default: `zabbix`. The name of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_proxy_logtype`: Specifies where log messages are written to: system, file, console. -* `zabbix_proxy_logfile`: Name of log file. -* `zabbix_proxy_userid`: The UID of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_proxy_groupname`: Default: `zabbix`. The name of the group of the user on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_proxy_groupid`: The GID of the group on the host. Will only be used when `zabbix_repo: epel` is used. * `zabbix_proxy_include_mode`: Default: `0755`. The "mode" for the directory configured with `zabbix_proxy_include`. * `zabbix_proxy_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. -* `zabbix_proxy_statsallowedip`: Default: `127.0.0.1`. Allowed IP foe remote gathering of the ZabbixPorixy internal metrics. -* `zabbix_proxy_vaulttoken`: Vault authentication token that should have been generated exclusively for Zabbix server with read only permission -* `zabbix_proxy_vaulturl`: Vault server HTTP[S] URL. System-wide CA certificates directory will be used if SSLCALocation is not specified. -* `zabbix_proxy_vaultdbpath`: Vault path from where credentials for database will be retrieved by keys 'password' and 'username'. -* `zabbix_proxy_listenbacklog`: The maximum number of pending connections in the queue. ### Database specific * `zabbix_proxy_dbhost_run_install`: Default: `True`. When set to `True`, sql files will be executed on the host running the database. * `zabbix_proxy_database`: Default: `mysql`. The type of database used. Can be: `mysql`, `pgsql` or `sqlite3` -* `zabbix_proxy_database_long`: Default: `mysql`. The type of database used, but long name. Can be: `mysql`, `postgresql` or `sqlite3` -* `zabbix_proxy_dbhost`: The hostname on which the database is running. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbhost`: Default: localhost. The hostname on which the database is running. Will be ignored when `sqlite3` is used as database. * `zabbix_proxy_real_dbhost`: The hostname of the dbhost that is running behind a loadbalancer/VIP (loadbalancers doesn't accept ssh connections) Will be ignored when `sqlite3` is used as database. -* `zabbix_proxy_dbname`: The database name which is used by the Zabbix Proxy. -* `zabbix_proxy_dbuser`: The database username which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. -* `zabbix_proxy_dbpassword`: The database user password which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbname`: Default: zabbix_proxy. The database name which is used by the Zabbix Proxy. +* `zabbix_proxy_dbuser`: Default: zabbix_proxy. The database username which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbpassword`: Default: zabbix_proxy. The database user password which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. * `zabbix_proxy_dbport`: The database port which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. -* `zabbix_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. +* `zabbix_proxy_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. * `zabbix_proxy_install_database_client`: Default: `True`. False does not install database client. Default true -* `zabbix_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. +* `zabbix_proxy_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. * `zabbix_proxy_dbencoding`: Default: `utf8`. The encoding for the MySQL database. * `zabbix_proxy_dbcollation`: Default: `utf8_bin`. The collation for the MySQL database.zabbix_proxy_ -* `zabbix_server_allowunsupporteddbversions`: Allow proxy to work with unsupported database versions. -* `zabbix_proxy_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. -### TLS Specific configuration - -These variables are specific for Zabbix 3.0 and higher: - -* `zabbix_proxy_tlsconnect`: How the agent should connect to server or proxy. Used for active checks. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_proxy_tlsaccept`: What incoming connections to accept. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_proxy_tlscafile`: Full pathname of a file containing the top-level CA(s) certificates for peer certificate verification. -* `zabbix_proxy_tlscrlfile`: Full pathname of a file containing revoked certificates. -* `zabbix_proxy_tlsservercertissuer`: Allowed server certificate issuer. -* `zabbix_proxy_tlsservercertsubject`: Allowed server certificate subject. -* `zabbix_proxy_tlscertfile`: Full pathname of a file containing the agent certificate or certificate chain. -* `zabbix_proxy_tlskeyfile`: Full pathname of a file containing the agent private key. -* `zabbix_proxy_dbtlsconnect`: Setting this option enforces to use TLS connection to database: - -`required` - connect using TLS -`verify_ca` - connect using TLS and verify certificate -`verify_full` - connect using TLS, verify certificate and verify that database identity specified by DBHost matches its certificate - -On `MySQL` starting from 5.7.11 and `PostgreSQL` the following values are supported: `required`, `verify`, `verify_full`. On MariaDB starting from version 10.2.6 `required` and `verify_full` values are supported. -By default not set to any option and the behaviour depends on database configuration. -This parameter is supported since Zabbix 5.0.0. - -* `zabbix_proxy_dbtlscafile`: Full pathname of a file containing the top-level CA(s) certificates for database certificate verification. This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlscertfile`: Full pathname of file containing Zabbix Proxy certificate for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlskeyfile`: Full pathname of file containing the private key for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlscipher`: The list of encryption ciphers that Zabbix Proxy permits for TLS protocols up through TLSv1.2. Supported only for MySQL.This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlscipher13`: The list of encryption ciphersuites that Zabbix Proxy permits for TLSv1.3 protocol. Supported only for MySQL, starting from version 8.0.16. This parameter is supported since Zabbix 5.0.0. - -## proxy + +### Yum/APT +* `zabbix_repo_yum`: A list with Yum repository configuration. +* `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) +* `zabbix_repo_yum_gpgcheck`: Default: `0`. Should yum perform a GPG check on the repository +* `zabbix_proxy_disable_repo`: A list of repos to disable during install. Default `epel`. +* `zabbix_proxy_apt_priority`: APT priority for the zabbix repository +* `*zabbix_proxy_package_state`: Default: `present`. Can be overridden to `latest` to update packages +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_proxy_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. +### SElinux + +* `zabbix_proxy_selinux`: Default: `False`. Enables an SELinux policy so that the Proxy will run. + +## Proxy When the target host does not have access to the internet, but you do have a proxy available then the following properties needs to be set to download the packages via the proxy: @@ -210,9 +148,9 @@ When the target host does not have access to the internet, but you do have a pro With Zabbix Proxy you can make use of 2 different databases: -* `mysql` -* `postgresql` -* `SQLite3` +* MySQL +* PostgreSQL +* SQLite3 In the following paragraphs we dive into both setups. @@ -232,12 +170,12 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: mysql -zabbix_proxy_database_long: mysql zabbix_proxy_dbport: 3306 zabbix_proxy_dbpassword: <SOME_SECRET_STRING> ``` Please generate a value for the `zabbix_proxy_dbpassword` property (Maybe use `ansible-vault` for this). The zabbix-proxy role will create an database and username (With the provided value for the password) in `MySQL`. + 3. Execute the role by running the Ansible playbook that calls this role. At the end of this run, the Zabbix Proxy with `MySQL` will be running. #### Separate Setup @@ -249,7 +187,6 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: mysql -zabbix_proxy_database_long: mysql zabbix_proxy_dbport: 3306 zabbix_proxy_dbhost: mysql-host zabbix_proxy_dbhost_run_install: false @@ -283,7 +220,6 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: pgsql -zabbix_proxy_database_long: postgresql zabbix_proxy_dbport: 5432 zabbix_proxy_dbpassword: <SOME_SECRET_STRING> ``` @@ -300,7 +236,6 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: pgsql -zabbix_proxy_database_long: postgresql zabbix_proxy_dbport: 5432 zabbix_proxy_dbhost: pgsql-host zabbix_proxy_dbhost_run_install: false @@ -326,7 +261,6 @@ The following properties needs to be set when using `SQLite3` as the database: ```yaml zabbix_proxy_database: sqlite3 -zabbix_proxy_database_long: sqlite3 zabbix_proxy_dbname: /path/to/sqlite3.db ``` @@ -336,20 +270,140 @@ NOTE: When using `zabbix_proxy_dbname: zabbix_proxy` (Which is default with this These variables need to be overridden when you want to make use of the Zabbix API for automatically creating and or updating proxies, i.e. when `zabbix_api_create_proxy` is set to `True`. -* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth. -* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth. * `zabbix_api_server_host`: The IP or hostname/FQDN of Zabbix server. Example: zabbix.example.com -* `zabbix_api_server_port`: TCP port to use to connect to Zabbix server. Example: 8080 -* `zabbix_api_use_ssl`: yes (Default) if we need to connect to Zabbix server over HTTPS -* `zabbix_api_validate_certs` : yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used +* `zabbix_api_use_ssl`: Is SSL required to connect to the Zabbix API server? Default: `false` +* `zabbix_api_server_port`: 80 if `zabbix_api_use_ssl` is `false` and 443 if `true` (Default) TCP port to use to connect to Zabbix server. Example: 8080 * `zabbix_api_login_user`: Username of user which has API access. * `zabbix_api_login_pass`: Password for the user which has API access. +* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_validate_certs`: yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used. +* `zabbix_api_timeout`: timeout for API calls (default to 30 seconds) * `ansible_zabbix_url_path`: URL path if Zabbix WebUI running on non-default (zabbix) path, e.g. if http://<FQDN>/zabbixeu then set to `zabbixeu` * `zabbix_api_create_proxy`: When you want to enable the Zabbix API to create/delete the proxy. This has to be set to `True` if you want to make use of `zabbix_proxy_state`. Default: `False` * `zabbix_proxy_name`: name of the Zabbix proxy as it is seen by Zabbix server * `zabbix_proxy_state`: present (Default) if the proxy needs to be created or absent if you want to delete it. This only works when `zabbix_api_create_proxy` is set to `True`. * `zabbix_proxy_status`: active (Default) if the proxy needs to be active or passive. -* `zabbix_api_timeout`: timeout for API calls (default to 30 seconds) + +## Configuration Variables + +The following table lists all variables that are exposed to modify the configuration of the zabbix_proxy.conf file. Specific details of each variable can be found in the Zabbix documentation. + +**NOTE**: Only variables with a default value appear in the defaults file, all others must be added. + +| Zabbix Name | Variable Name | Default Value |Notes | +|-----------|------------------|--------|--------| +| AllowRoot | zabbix_proxy_allowroot |0| | +| AllowUnsupportedDBVersions | zabbix_proxy_allowunsupporteddbversions |0| | +| CacheSize | zabbix_proxy_cachesize | 8M| | +| ConfigFrequency | zabbix_proxy_configfrequency |3600| | +| DataSenderFrequency | zabbix_proxy_datasenderfrequency |1| | +| DBHost | zabbix_proxy_dbhost | localhost| | +| DBName | zabbix_proxy_dbname | zabbix_proxy| | +| DBPassword | zabbix_proxy_dbpassword | zabbix_proxy| | +| DBSchema | zabbix_proxy_dbschema || | +| DBSocket | zabbix_proxy_dbsocket || | +| DBTLSCAFile | zabbix_proxy_dbtlscafile || | +| DBTLSCertFile | zabbix_proxy_dbtlscertfile || | +| DBTLSCipher | zabbix_proxy_dbtlscipher || | +| DBTLSCipher13 | zabbix_proxy_dbtlscipher13 || | +| DBTLSConnect | zabbix_proxy_dbtlsconnect || | +| DBTLSKeyFile | zabbix_proxy_dbtlskeyfile || | +| DBUser | zabbix_proxy_dbuser | zabbix_proxy| | +| DebugLevel | zabbix_proxy_debuglevel |3| | +| EnableRemoteCommands | zabbix_proxy_enableremotecommands |0| | +| ExternalScripts | zabbix_proxy_externalscripts | /usr/lib/zabbix/externalscripts| | +| Fping6Location | zabbix_proxy_fping6location | OS Specific Value | | +| FpingLocation | zabbix_proxy_fpinglocation | OS Specific Value | | +| HeartbeatFrequency | zabbix_proxy_heartbeatfrequency |60| Version 6.2 or Lower| +| HistoryCacheSize | zabbix_proxy_historycachesize | 8M| | +| HistoryIndexCacheSize | zabbix_proxy_historyindexcachesize | 4M| | +| Hostname | zabbix_proxy_hostname | "{{ inventory_hostname }}"| | +| HostnameItem | zabbix_proxy_hostnameitem || | +| HousekeepingFrequency | zabbix_proxy_housekeepingfrequency |1| | +| Include | zabbix_proxy_include | /etc/zabbix/zabbix_proxy.conf.d| | +| JavaGateway | zabbix_proxy_javagateway || | +| JavaGatewayPort | zabbix_proxy_javagatewayport |10052| | +| ListenBacklog | zabbix_proxy_listenbacklog || | +| ListenIP | zabbix_proxy_listenip || | +| ListenPort | zabbix_proxy_listenport |10051| | +| LoadModule | zabbix_proxy_loadmodule || | +| LoadModulePath | zabbix_proxy_loadmodulepath | /usr/lib/zabbix/modules| | +| LogFile | zabbix_proxy_logfile | /var/log/zabbix/zabbix_proxy.log| | +| LogFileSize | zabbix_proxy_logfilesize |10| | +| LogRemoteCommands | zabbix_proxy_logremotecommands || | +| LogSlowQueries | zabbix_proxy_logslowqueries || | +| LogType | zabbix_proxy_logtype | file| | +| PidFile | zabbix_proxy_pidfile | /var/run/zabbix/zabbix_proxy.pid| | +| ProxyLocalBuffer | zabbix_proxy_proxylocalbuffer |0| | +| ProxyMode | zabbix_proxy_proxymode || | +| ProxyOfflineBuffer | zabbix_proxy_proxyofflinebuffer |1| | +| Server | zabbix_proxy_server | 192.168.1.1| | +| SNMPTrapperFile | zabbix_proxy_snmptrapperfile | /tmp/zabbix_traps.tmp| | +| SocketDir | zabbix_proxy_socketdir | /var/run/zabbix| | +| SourceIP | zabbix_proxy_sourceip || | +| SSHKeyLocation | zabbix_proxy_sshkeylocation || | +| SSLCALocation | zabbix_proxy_sslcalocation || | +| SSLCertLocation | zabbix_proxy_sslcertlocation || | +| SSLKeyLocation | zabbix_proxy_sslkeylocation || | +| StartDBSyncers | zabbix_proxy_startdbsyncers |4| | +| StartDiscoverers | zabbix_proxy_startdiscoverers |1| | +| StartHTTPPollers | zabbix_proxy_starthttppollers |1| | +| StartIPMIPollers | zabbix_proxy_startipmipollers |0| | +| StartJavaPollers | zabbix_proxy_startjavapollers || | +| StartODBCPollers | zabbix_proxy_startodbcpollers |1| | +| StartPingers | zabbix_proxy_startpingers |1| | +| StartPollers | zabbix_proxy_startpollers |5| | +| StartPollersUnreachable | zabbix_proxy_startpollersunreachable |1| | +| StartPreprocessors | zabbix_proxy_startpreprocessors |3| | +| StartSNMPTrapper | zabbix_proxy_startsnmptrapper || | +| StartTrappers | zabbix_proxy_starttrappers |5| | +| StartVMwareCollectors | zabbix_proxy_startvmwarecollectors || | +| StatsAllowedIP | zabbix_proxy_statsallowedip | "127.0.0.1"| | +| Timeout | zabbix_proxy_timeout |3| | +| TLSAccept | zabbix_proxy_tlsaccept || | +| TLSCAFile | zabbix_proxy_tlscafile || | +| TLSCertFile | zabbix_proxy_tlscertfile || | +| TLSCipherAll | zabbix_proxy_tlscipherall || | +| TLSCipherAll13 | zabbix_proxy_tlscipherall13 || | +| TLSCipherCert | zabbix_proxy_tlsciphercert || | +| TLSCipherCert13 | zabbix_proxy_tlsciphercert13 || | +| TLSCipherPSK | zabbix_proxy_tlscipherpsk || | +| TLSCipherPSK13 | zabbix_proxy_tlscipherpsk13 || | +| TLSConnect | zabbix_proxy_tlsconnect || | +| TLSCRLFile | zabbix_proxy_tlscrlfile || | +| TLSKeyFile | zabbix_proxy_tlskeyfile || | +| TLSPSKFile | zabbix_proxy_tlspskfile || | +| TLSPSKIdentity | zabbix_proxy_tlspskidentity || | +| TLSServerCertIssuer | zabbix_proxy_tlsservercertissuer || | +| TLSServerCertSubject | zabbix_proxy_tlsservercertsubject || | +| TmpDir | zabbix_proxy_tmpdir | /tmp| | +| TrapperTimeout | zabbix_proxy_trappertimeout |300| | +| UnavailableDelay | zabbix_proxy_unavailabledelay || | +| UnreachableDelay | zabbix_proxy_unreachabledelay || | +| UnreachablePeriod | zabbix_proxy_unreachableperiod |45| | +| User | zabbix_proxy_user || | +| Vault | zabbix_proxy_vault || Version 6.2 or Greater | +| VaultDBPath | zabbix_proxy_vaultdbpath || | +| VaultTLSCertFile | zabbix_proxy_vaulttlscertfile || Version 6.2 or Greater | +| VaultTLSKeyFile | zabbix_proxy_vaulttlskeyfile || Version 6.2 or Greater | +| VaultToken | zabbix_proxy_vaulttoken || | +| VaultURL | zabbix_proxy_vaulturl |https://127.0.0.1:8200| | +| VMwareCacheSize | zabbix_proxy_vmwarecachesize | 8M| | +| VMwareFrequency | zabbix_proxy_vmwarefrequency |60| | +| VMwarePerfFrequency | zabbix_proxy_vmwareperffrequency | | | +| VMwareTimeout | zabbix_proxy_vmwaretimeout | | | + +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. # Example Playbook @@ -361,7 +415,6 @@ Including an example of how to use your role (for instance, with variables passe - role: community.zabbix.zabbix_proxy zabbix_proxy_server: 192.168.1.1 zabbix_proxy_database: mysql - zabbix_proxy_database_long: mysql ``` # Molecule @@ -385,3 +438,4 @@ See LICENCE to see the full text. Please send suggestion or pull requests to make this role better. Also let us know if you encounter any issues installing or using this role. Github: https://github.com/ansible-collections/community.zabbix + diff --git a/ansible_collections/community/zabbix/docs/ZABBIX_SERVER_ROLE.md b/ansible_collections/community/zabbix/docs/ZABBIX_SERVER_ROLE.md index 4643fbc3f..f154f4951 100644 --- a/ansible_collections/community/zabbix/docs/ZABBIX_SERVER_ROLE.md +++ b/ansible_collections/community/zabbix/docs/ZABBIX_SERVER_ROLE.md @@ -75,26 +75,16 @@ ansible-galaxy collection install community.postgresql See the following list of supported Operating systems with the Zabbix releases: -| Zabbix | 6.4 | 6.2 | 6.0 | 5.4 | 5.2 | 5.0 (LTS) | 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----|-----|-----|-----------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | | | | | | V | V | V | V | -| Red Hat Fam 6 | | | | | V | V | | | V | -| Red Hat Fam 5 | | | | | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | | | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | | V | V | V | V | V | -| Debian 10 buster | | | V | V | V | V | V | | | -| Debian 9 stretch | | | V | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | - -See https://support.zabbix.com/browse/ZBX-18790 why RHEL7 is not supported anymore. +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | | | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | | | V | # Installation @@ -110,112 +100,48 @@ The following is an overview of all available configuration default for this rol ### Overall Zabbix -* `zabbix_server_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2, 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. +* `zabbix_server_version`: Optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_server_version: 6.0`. * `zabbix_server_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. +* `zabbix_server_disable_repo`: A list of repos to disable during install. Default `epel`. * `zabbix_service_state`: Default: `started`. Can be overridden to stopped if needed * `zabbix_service_enabled`: Default: `True` Can be overridden to `False` if needed +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_server_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### SElinux -* `zabbix_selinux`: Default: `False`. Enables an SELinux policy so that the server will run. +* `zabbix_server_selinux`: Default: `False`. Enables an SELinux policy so that the server will run. * `selinux_allow_zabbix_can_network`: Default: `False`. * `selinux_allow_zabbix_can_http`: Default: `False`. ### Zabbix Server * `zabbix_server_package_state`: Default: `present`. Can be overridden to `latest` to update packages when needed. -* `zabbix_server_listenport`: Default: `10051`. On which port the Zabbix Server is available. * `zabbix_server_install_recommends`: Default: `True`. `False` does not install the recommended packages that come with the zabbix-server install. * `zabbix_server_manage_service`: Default: `True`. When you run multiple Zabbix servers in a High Available cluster setup (e.g. pacemaker), you don't want Ansible to manage the zabbix-server service, because Pacemaker is in control of zabbix-server service and in this case, it needs to be set to `False`. -* `zabbix_proxy_startpreprocessors`: Number of pre-forked instances of preprocessing workers. The preprocessing manager process is automatically started when a preprocessor worker is started. This parameter is supported since Zabbix 4.2.0. -* `zabbix_server_username`: Default: `zabbix`. The name of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_server_userid`: The UID of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_server_groupname`: Default: `zabbix`. The name of the group of the user on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_server_groupid`: The GID of the group on the host. Will only be used when `zabbix_repo: epel` is used. * `zabbix_server_include_mode`: Default: `0755`. The "mode" for the directory configured with `zabbix_server_include`. * `zabbix_server_conf_mode`: Default: `0640`. The "mode" for the Zabbix configuration file. -* `zabbix_server_listenbacklog`: The maximum number of pending connections in the queue. -* `zabbix_server_trendcachesize`: Size of trend cache, in bytes. -* `zabbix_server_trendfunctioncachesize`: Size of trend function cache, in bytes. -* `zabbix_server_vaulttoken`: Vault authentication token that should have been generated exclusively for Zabbix server with read only permission -* `zabbix_server_vaulturl`: Vault server HTTP[S] URL. System-wide CA certificates directory will be used if SSLCALocation is not specified. -* `zabbix_server_vaultdbpath`: Vault path from where credentials for database will be retrieved by keys 'password' and 'username'. -* `zabbix_server_startreportwriters`: Number of pre-forked report writer instances. -* `zabbix_server_webserviceurl`: URL to Zabbix web service, used to perform web related tasks. -* `zabbix_server_servicemanagersyncfrequency`: How often Zabbix will synchronize configuration of a service manager (in seconds). -* `zabbix_server_problemhousekeepingfrequency`: How often Zabbix will delete problems for deleted triggers (in seconds). -* `zabbix_server_connectors`: Number of pre-forked instances of preprocessing workers. - -### High Availability - -These variables are specific for Zabbix 6.0 and higher: - -* `zabbix_server_hanodename`: The high availability cluster node name. When empty, server is working in standalone mode; a node with empty name is registered with address for the frontend to connect to. (Default: empty) -* `zabbix_server_nodeaddress`: IP or hostname with optional port to specify how frontend should connect to the server. ### Database specific * `zabbix_server_dbhost_run_install`: Default: `True`. When set to `True`, sql files will be executed on the host running the database. * `zabbix_server_database`: Default: `pgsql`. The type of database used. Can be: `mysql` or `pgsql` -* `zabbix_server_database_long`: Default: `postgresql`. The type of database used, but long name. Can be: `mysql` or `postgresql` * `zabbix_server_dbhost`: The hostname on which the database is running. * `zabbix_server_real_dbhost`: The hostname of the dbhost that is running behind a loadbalancer/VIP (loadbalancers doesn't accept ssh connections) * `zabbix_server_dbname`: The database name which is used by the Zabbix Server. * `zabbix_server_dbuser`: The database username which is used by the Zabbix Server. * `zabbix_server_dbpassword`: The database user password which is used by the Zabbix Server. +* `zabbix_server_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. * `zabbix_server_dbport`: The database port which is used by the Zabbix Server. * `zabbix_server_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. -* `zabbix_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. +* `zabbix_server_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. * `zabbix_server_install_database_client`: Default: `True`. False does not install database client. Default true -* `zabbix_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. -* `zabbix_database_timescaledb`:False / True. When you want to use timescaledb extension into the database, you can set it to True (this option only works for postgreSQL database). +* `zabbix_server_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. +* `zabbix_server_database_timescaledb`:False / True. When you want to use timescaledb extension into the database, you can set it to True (this option only works for postgreSQL database). * `zabbix_server_dbencoding`: Default: `utf8`. The encoding for the MySQL database. * `zabbix_server_dbcollation`: Default: `utf8_bin`. The collation for the MySQL database. -* `zabbix_server_allowunsupporteddbversions`: Allow server to work with unsupported database versions. - -### TLS Specific configuration - -These variables are specific for Zabbix 3.0 and higher: - -* `zabbix_server_tlsconnect`: How the agent should connect to server or proxy. Used for active checks. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_server_tlsaccept`: What incoming connections to accept. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_server_tlscafile`: Full pathname of a file containing the top-level CA(s) certificates for peer certificate verification. -* `zabbix_server_tlscrlfile`: Full pathname of a file containing revoked certificates. -* `zabbix_server_tlsservercertissuer`: Allowed server certificate issuer. -* `zabbix_server_tlsservercertsubject`: Allowed server certificate subject. -* `zabbix_server_tlscertfile`: Full pathname of a file containing the agent certificate or certificate chain. -* `zabbix_server_tlskeyfile`: Full pathname of a file containing the agent private key. -* `zabbix_server_dbtlsconnect`: Setting this option enforces to use TLS connection to database: - -`required` - connect using TLS -`verify_ca` - connect using TLS and verify certificate -`verify_full` - connect using TLS, verify certificate and verify that database identity specified by DBHost matches its certificate - -On `MySQL` starting from 5.7.11 and `PostgreSQL` the following values are supported: `required`, `verify`, `verify_full`. On MariaDB starting from version 10.2.6 `required` and `verify_full` values are supported. -By default not set to any option and the behaviour depends on database configuration. -This parameter is supported since Zabbix 5.0.0. - -* `zabbix_server_dbtlscafile`: Full pathname of a file containing the top-level CA(s) certificates for database certificate verification. This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlscertfile`: Full pathname of file containing Zabbix server certificate for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlskeyfile`: Full pathname of file containing the private key for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlscipher`: The list of encryption ciphers that Zabbix server permits for TLS protocols up through TLSv1.2. Supported only for MySQL.This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlscipher13`: The list of encryption ciphersuites that Zabbix server permits for TLSv1.3 protocol. Supported only for MySQL, starting from version 8.0.16. This parameter is supported since Zabbix 5.0.0. ### Custom Zabbix Scripts @@ -350,6 +276,135 @@ The `zabbix_server_privileged_host` can be set to the hostname/ip of the host ru 3. Execute the role by running the Ansible playbook that calls this role. At the end of this run, the Zabbix Server with `PgSQL` on a different host will be running. +## Configuration Variables + +The following table lists all variables that are exposed to modify the configuration of the zabbix_server.conf file. Specific details of each variable can be found in the Zabbix documentation. + +**NOTE**: Only variables with a default value appear in the defaults file, all others must be added. + +| Zabbix Name | Variable Name | Default Value |Notes | +|-----------|------------------|--------|--------| +|AlertScriptsPath | zabbix_server_alertscriptspath | /usr/lib/zabbix/alertscripts | | +|AllowRoot | zabbix_server_allowroot | 0 | | +|AllowUnsupportedDBVersions | zabbix_server_allowunsupporteddbversions |0 | | +|CacheSize | zabbix_server_cachesize | | | +|CacheUpdateFrequency | zabbix_server_cacheupdatefrequency | | | +|DBHost | zabbix_server_dbhost | localhost | | +|DBName | zabbix_server_dbname | zabbix-server | | +|DBPassword | zabbix_server_dbpassword | zabbix-server | | +|DBPort | zabbix_server_dbport | 5432 | | +|DBSchema | zabbix_server_dbschema | | | +|DBSocket | zabbix_server_dbsocket | | | +|DBTLSCAFile | zabbix_server_dbtlscafile | | | +|DBTLSCertFile | zabbix_server_dbtlscertfile | | | +|DBTLSCipher | zabbix_server_dbtlscipher | | | +|DBTLSCipher13 | zabbix_server_dbtlscipher13 | | | +|DBTLSConnect | zabbix_server_dbtlsconnect | | | +|DBTLSKeyFile | zabbix_server_dbtlskeyfile | | | +|DBUser | zabbix_server_dbuser | zabbix-server | | +|DebugLevel | zabbix_server_debuglevel | 3 | | +|ExportDir | zabbix_server_exportdir | | | +|ExportFileSize | zabbix_server_exportfilesize | 1G | | +|ExportType | zabbix_server_exporttype | | | +|ExternalScripts | zabbix_server_externalscriptspath | /usr/lib/zabbix/externalscripts | | +|Fping6Location | zabbix_server_fping6location | OS Specific Value | | +|FpingLocation | zabbix_server_fpinglocation | OS Specific Value | | +|HANodeName | zabbix_server_hanodename | | | +|HistoryCacheSize | zabbix_server_historycachesize | | | +|HistoryIndexCacheSize | zabbix_server_historyindexcachesize | | | +|HistoryStorageDateIndex | zabbix_server_historystoragedateindex | 0 | | +|HistoryStorageTypes | zabbix_server_historystoragetypes | uint,dbl,str,log,text | | +|HistoryStorageURL | zabbix_server_historystorageurl | | | +|HousekeepingFrequency | zabbix_server_housekeepingfrequency | 1 | | +|Include | zabbix_server_include | /etc/zabbix/zabbix_server.conf.d | | +|JavaGateway | zabbix_server_javagateway | | | +|JavaGatewayPort | zabbix_server_javagatewayport | 10052 | | +|ListenBacklog | zabbix_server_listenbacklog | | | +|ListenIP | zabbix_server_listenip | | | +|ListenPort | zabbix_server_listenport | 10051 | | +|LoadModule | zabbix_server_loadmodule | | | +|LoadModulePath | zabbix_server_loadmodulepath | ${libdir}/modules | | +|LogFile | zabbix_server_logfile | /var/log/zabbix/zabbix_server.log | | +|LogFileSize | zabbix_server_logfilesize | 10 | | +|LogSlowQueries | zabbix_server_logslowqueries | 0 | | +|LogType | zabbix_server_logtype | file | | +|MaxHousekeeperDelete | zabbix_server_maxhousekeeperdelete | 500 | | +|NodeAddress | zabbix_server_nodeaddress | | | +|PidFile | zabbix_server_pidfile | /var/run/zabbix/zabbix_server.pid | | +|ProxyConfigFrequency | zabbix_server_proxyconfigfrequency | | | +|ProxyDataFrequency | zabbix_server_proxydatafrequency | 1 | | +|SNMPTrapperFile | zabbix_server_snmptrapperfile | | | +|SocketDir | zabbix_server_socketdir | /var/run/zabbix | | +|SourceIP | zabbix_server_sourceip | | | +|SSHKeyLocation | zabbix_server_sshkeylocation | | | +|SSLCALocation | zabbix_server_sslcalocation | | | +|SSLCertLocation | zabbix_server_sslcertlocation | ${datadir}/zabbix/ssl/certs | | +|SSLKeyLocation | zabbix_server_sslkeylocation | ${datadir}/zabbix/ssl/keys | | +|StartAlerters | zabbix_server_startalerters | | | +|StartConnectors | zabbix_server_connectors | | Version 6.4 or later | +|StartDBSyncers | zabbix_server_startdbsyncers | 4 | | +|StartDiscoverers | zabbix_server_startdiscoverers | 1 | | +|StartEscalators | zabbix_server_startescalators | 1 | | +|StartHistoryPollers | zabbix_server_starthistorypollers | | | +|StartHTTPPollers | zabbix_server_starthttppollers | 1 | | +|StartIPMIPollers | zabbix_server_startipmipollers | 0 | | +|StartJavaPollers | zabbix_server_startjavapollers | 0 | | +|StartLLDProcessors | zabbix_server_startlldprocessors | | | +|StartODBCPollers | zabbix_server_startodbcpollers | | | +|StartPingers | zabbix_server_startpingers | 1 | | +|StartPollers | zabbix_server_startpollers | 5 | | +|StartPollersUnreachable | zabbix_server_startpollersunreachable | 1 | | +|StartPreprocessors | zabbix_server_startpreprocessors | | | +|StartProxyPollers | zabbix_server_startproxypollers | | | +|StartReportWriters | zabbix_server_startreportwriters | 0 | | +|StartSNMPTrapper | zabbix_server_startsnmptrapper | 0 | | +|StartTimers | zabbix_server_starttimers | 1 | | +|StartTrappers | zabbix_server_starttrappers | 5 | | +|StartVMwareCollectors | zabbix_server_startvmwarecollectors | 0 | | +|StasAllowedIP | zabbix_server_statsallowedip | | | +|Timeout | zabbix_server_timeout | 3 | | +|TLSCAFile | zabbix_server_tlscafile | | | +|TLSCertFile | zabbix_server_tlscertfile | | | +|TLSCipherAll | zabbix_server_tlscipherall | | | +|TLSCipherAll13 | zabbix_server_tlscipherall13 | | | +|TLSCipherCert | zabbix_server_tlsciphercert | | | +|TLSCipherCert13 | zabbix_server_tlsciphercert13 | | | +|TLSCipherPSK | zabbix_server_tlscipherpsk | | | +|TLSCipherPSK13 | zabbix_server_tlscipherpsk13 | | | +|TLSCRLFile | zabbix_server_tlscrlfile | | | +|TLSKeyFile | zabbix_server_tlskeyfile | | | +|TmpDir | zabbix_server_tmpdir | /tmp | | +|TrapperTimeout | zabbix_server_trappertimeout | 300 | | +|TrendCacheSize | zabbix_server_trendcachesize | | | +|TrendFunctionCacheSize | zabbix_server_trendfunctioncachesize | | | +|UnavailableDelay | zabbix_server_unavailabledelay | 60 | | +|UnreachableDelay | zabbix_server_unreachabledelay | 15 | | +|UnreachablePeriod | zabbix_server_unreachableperiod | 45 | | +|User | zabbix_server_user | zabbix | | +|ValueCacheSize | zabbix_server_valuecachesize | | | +|Vault | zabbix_server_vault | | Version 6.2 or later | +|VaultDBPath | zabbix_server_vaultdbpath | | | +|VaultTLSKeyFile | zabbix_server_vaulttlskeyfile | | Version 6.2 or later | +|VaultTLSCertFile | zabbix_server_vaulttlscertfile | | Version 6.2 or later | +|VaultToken | zabbix_server_vaulttoken | | | +|VaultURL | zabbix_server_vaulturl | https://127.0.0.1:8200 | | +|VMwareCacheSize | zabbix_server_vmwarecachesize | | | +|VMwareFrequency | zabbix_server_vmwarefrequency | 60 | | +|VMwarePerfFrequency | zabbix_server_vmwareperffrequency | 60 | | +|VMwareTimeout | zabbix_server_vmwaretimeout | 10 | | +|WebServiceURL | zabbix_server_webserviceurl | | | + +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Example Playbook Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: diff --git a/ansible_collections/community/zabbix/docs/ZABBIX_WEB_ROLE.md b/ansible_collections/community/zabbix/docs/ZABBIX_WEB_ROLE.md index cef5d62e7..5904f8288 100644 --- a/ansible_collections/community/zabbix/docs/ZABBIX_WEB_ROLE.md +++ b/ansible_collections/community/zabbix/docs/ZABBIX_WEB_ROLE.md @@ -43,7 +43,7 @@ Please send Pull Requests or suggestions when you want to use this role for othe ## Ansible 2.10 and higher -With the release of Ansible 2.10, modules have been moved into collections. With the exception of ansible.builtin modules, this means additonal collections must be installed in order to use modules such as seboolean (now ansible.posix.seboolean). The following collections are now required: `ansible.posix`. The `community.general` collection is required when defining the `zabbix_web_htpasswd` variable (see variable section below). Installing the collections: +With the release of Ansible 2.10, modules have been moved into collections. With the exception of ansible.builtin modules, this means additonal collections must be installed in order to use modules such as seboolean (now ansible.posix.seboolean). The following collections are now required: `ansible.posix`. Installing the collections: ```sh ansible-galaxy collection install ansible.posix @@ -54,25 +54,16 @@ ansible-galaxy collection install community.general See the following list of supported Operating Systems with the Zabbix releases. -| Zabbix | 6.4 | 6.2 | 6.0 (LTS) | 5.4 | 5.2 | 5.0 (LTS) | 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----------|-----|-----|------------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | | V | V | V | V | V | V | V | V | -| Red Hat Fam 6 | | | | | V | V | | | V | -| Red Hat Fam 5 | | | | | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 22.04 jammy | V | V | V | | | | | | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | V | | | -| Ubuntu 18.04 bionic | | | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | | V | V | V | V | V | -| Debian 10 buster | V | V | V | V | V | V | V | | | -| Debian 9 stretch | | | V | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | | | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | | | V | # Installation @@ -93,107 +84,77 @@ The following is an overview of all available configuration defaults for this ro ### Overall Zabbix -* `zabbix_web_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2, 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. +* `zabbix_web_version`: Optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_web_version: 6.0`. * `zabbix_web_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. - +* `zabbix_web_disable_repo`: A list of repos to disable during install. Default `epel`. * `zabbix_web_package_state`: Default: `present`. Can be overridden to `latest` to update packages when needed. -* `zabbix_web_centos_release`: Default: True. When the `centos-release-scl` repository needs to be enabled. This is required when using Zabbix 5.0 due to installation of a recent version of `PHP`. -* `zabbix_web_rhel_release`: Default: True. When the `scl-utils` repository needs to be enabled. This is required when using Zabbix 5.0 due to installation of a recent version of `PHP`. * `zabbix_web_doubleprecision`: Default: `False`. For upgraded installations, please read database [upgrade notes](https://www.zabbix.com/documentation/current/manual/installation/upgrade_notes_500) (Paragraph "Enabling extended range of numeric (float) values") before enabling this option. * `zabbix_web_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_web_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### Zabbix Web specific * `zabbix_api_server_url`: This is the url on which the zabbix web interface is available. Default is zabbix.example.com, you should override it. For example, see "Example Playbook" +* `zabbix_web_http_server`: Which web server is in use. Valid values are 'apache' and 'nginx'. Default is `apache` * `zabbix_url_aliases`: A list with Aliases for the Apache Virtual Host configuration. * `zabbix_timezone`: Default: `Europe/Amsterdam`. This is the timezone. The Apache Virtual Host needs this parameter. -* `zabbix_vhost`: Default: `true`. When you don't want to create an Apache Virtual Host configuration, you can set it to False. +* `zabbix_web_create_vhost`: Default: `true`. When you don't want to create an Apache Virtual Host configuration, you can set it to False. +* `zabbix_web_create_php_fpm`: Configure php-fpm (Debian hosts only). Default is to use the same value as `zabbix_web_create_vhost`. * `zabbix_web_env`: (Optional) A Dictionary of PHP Environments settings. -* `zabbix_web_conf_web_user`: When provided, the user (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). -* `zabbix_web_conf_web_group`: When provided, the group (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). -* `zabbix_web_htpasswd`: (Optional) Allow HTTP authentication at the webserver level via a htpasswd file. -* `zabbix_web_htpasswd_file`: Default: `/etc/zabbix/web/htpasswd`. Allows the change the default path to the htpasswd file. -* `zabbix_web_htpasswd_users`: (Optional) Dictionary for creating users via `htpasswd_user` and passphrases via `htpasswd_pass` in htpasswd file. -* `zabbix_web_allowlist_ips`: (Optional) Allow web access at webserver level to a list of defined IPs or CIDR. +* `zabbix_web_user`: When provided, the user (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). +* `zabbix_web_group`: When provided, the group (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). * `zabbix_web_connect_ha_backend`: (Optional) Default: `false`. When set to `true` values for Zabbix server will not be written and frontend gets values from database to connect to active cluster node. Set `true` when operating Zabbix servers in a cluste (only >=6.0). * `zabbix_saml_idp_crt`: (Optional) The path to the certificate of the Identity Provider used for SAML authentication * `zabbix_saml_sp_crt`: (Optional) The path to the public certificate of Zabbix as Service Provider * `zabbix_saml_sp_key`: (Optional) The path to the private certificate of Zabbix as Service Provider -#### Apache configuration +#### Apache/Nginx Configuration -* `zabbix_apache_vhost_port`: The port on which Zabbix HTTP vhost is running. -* `zabbix_apache_vhost_tls_port`: The port on which Zabbix HTTPS vhost is running. -* `zabbix_apache_vhost_listen_ip`: On which interface the Apache Virtual Host is available. +* `zabbix_web_vhost_port`: The port on which Zabbix HTTP vhost is running. +* `zabbix_web_vhost_tls_port`: The port on which Zabbix HTTPS vhost is running. +* `zabbix_web_vhost_listen_ip`: On which interface the Apache Virtual Host is available. * `zabbix_apache_can_connect_ldap`: Default: `false`. Set SELinux boolean to allow httpd to connect to LDAP. -* `zabbix_php_install`: Default: `true`. True / False. Switch for extra install of packages for PHP, currently on for Debian/Ubuntu. -* `zabbix_web_max_execution_time`: -* `zabbix_web_memory_limit`: -* `zabbix_web_post_max_size`: -* `zabbix_web_upload_max_filesize`: +* `zabbix_web_max_execution_time`: PHP max execution time +* `zabbix_web_memory_limit`: PHP memory limit +* `zabbix_web_post_max_size`: PHP maximum post size +* `zabbix_web_upload_max_filesize`: PHP maximum file size * `zabbix_web_max_input_time`: -* `zabbix_apache_include_custom_fragment`: Default: `true`. Includes php_value vars max_execution_time, memory_limit, post_max_size, upload_max_filesize, max_input_time and date.timezone in vhost file.. place those in php-fpm configuration. -* `zabbix_apache_tls`: If the Apache vhost should be configured with TLS encryption or not. -* `zabbix_apache_redirect`: If a redirect should take place from HTTP to HTTPS -* `zabbix_apache_tls_crt`: The path to the TLS certificate file. -* `zabbix_apache_tls_key`: The path to the TLS key file. -* `zabbix_apache_tls_chain`: The path to the TLS certificate chain file. -* `zabbix_apache_SSLPassPhraseDialog`: Type of pass phrase dialog for encrypted private keys. -* `zabbix_apache_SSLSessionCache`: Type of the global/inter-process SSL Session Cache -* `zabbix_apache_SSLSessionCacheTimeout`: Number of seconds before an SSL session expires in the Session Cache -* `zabbix_apache_SSLCryptoDevice`: Enable use of a cryptographic hardware accelerator +* `zabbix_web_tls`: If the Apache vhost should be configured with TLS encryption or not. +* `zabbix_web_redirect`: If a redirect should take place from HTTP to HTTPS +* `zabbix_web_tls_crt`: The path to the TLS certificate file. +* `zabbix_web_tls_key`: The path to the TLS key file. +* `zabbix_web_tls_chain`: The path to the TLS certificate chain file. +* `zabbix_web_SSLPassPhraseDialog`: Type of pass phrase dialog for encrypted private keys. +* `zabbix_web_SSLSessionCache`: Type of the global/inter-process SSL Session Cache +* `zabbix_web_SSLSessionCacheTimeout`: Number of seconds before an SSL session expires in the Session Cache +* `zabbix_web_SSLCryptoDevice`: Enable use of a cryptographic hardware accelerator * `zabbix_apache_custom_includes`: Configure custom includes. Default: `[]` -When `zabbix_apache_tls_crt`, `zabbix_apache_tls_key` and/or `zabbix_apache_tls_chain` are used, make sure that these files exists before executing this role. The Zabbix-Web role will not install the mentioned files. +When `zabbix_web_tls_crt`, `zabbix_web_tls_key` and/or `zabbix_web_tls_chain` are used, make sure that these files exists before executing this role. The Zabbix-Web role will not install the mentioned files. See https://httpd.apache.org/docs/current/mod/mod_ssl.html for SSL* configuration options for Apache HTTPD. #### Nginx configuration -* `zabbix_nginx_vhost_port`: The port on which Zabbix HTTP vhost is running. -* `zabbix_nginx_vhost_tls_port`: The port on which Zabbix HTTPS vhost is running. -* `zabbix_nginx_tls`: If the Nginx vhost should be configured with TLS encryption or not. -* `zabbix_nginx_tls_crt`: The path to the TLS certificate file. -* `zabbix_nginx_tls_key`: The path to the TLS key file. -* `zabbix_nginx_tls_dhparam`: The path to the TLS DHParam file. -* `zabbix_nginx_tls_session_cache`: Type of the global/inter-process SSL Session Cache -* `zabbix_nginx_tls_session_timeout`: -* `zabbix_nginx_tls_session_tickets`: -* `zabbix_nginx_tls_protocols`: The TLS Protocols to accept. -* `zabbix_nginx_tls_ciphers`: The TLS Ciphers to be allowed. - -When `zabbix_nginx_tls_crt` and `zabbix_nginx_tls_key` are used, make sure that these files exists before executing this role. The Zabbix-Web role will not install the mentioned files. #### PHP-FPM The following properties are specific to Zabbix 5.0 and for the PHP(-FPM) configuration: -* `zabbix_php_version`: Either `7.3` or `7.4` (Based on the OS Family). When you want to override the PHP Version. * `zabbix_php_fpm_session`: The directory where sessions will be stored. If none are provided, defaults are used. * `zabbix_php_fpm_listen`: The path to a socket file or ipaddress:port combination on which PHP-FPM needs to listen. If none are provided, defaults are used. * `zabbix_php_fpm_conf_listen`: Default: `true`. If we want to configure the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. * `zabbix_php_fpm_conf_user`: The owner of the socket file (When `zabbix_php_fpm_listen` contains a patch to a socket file). -* `zabbix_php_fpm_conf_enable_user`: Default: `true`. If we want to configure the owner of the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. + * `zabbix_php_fpm_conf_group`: The group of the owner of the socket file (When `zabbix_php_fpm_listen` contains a patch to a socket file). -* `zabbix_php_fpm_conf_enable_group`: Default: `true`. If we want to configure the group of the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. -* `zabbix_php_fpm_conf_mode`: The mode for the socket file (When `zabbix_php_fpm_listen` contains a patch to a socket file). -* `zabbix_php_fpm_conf_enable_mode`: Default: `true`. If we want to configure the mode of the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. -* `zabbix_php_fpm_dir_etc`: etc HOME root directory of PHP-FPM setup. -* `zabbix_php_fpm_dir_var`: Var HOME root directory of PHP-FPM setup. ### Zabbix Server * `zabbix_server_name`: The name of the Zabbix Server. * `zabbix_server_database`: The type of database used. Can be: mysql or pgsql -* `zabbix_server_database_long`: The type of database used, but long name. Can be: mysql or postgresql * `zabbix_server_hostname`: The hostname on which the zabbix-server is running. Default set to: {{ inventory_hostname }} * `zabbix_server_listenport`: On which port the Zabbix Server is available. Default: 10051 * `zabbix_server_dbhost`: The hostname on which the database is running. @@ -201,6 +162,7 @@ The following properties are specific to Zabbix 5.0 and for the PHP(-FPM) config * `zabbix_server_dbuser`: The database username which is used by the Zabbix Server. * `zabbix_server_dbpassword`: The database user password which is used by the Zabbix Server. * `zabbix_server_dbport`: The database port which is used by the Zabbix Server. +* `zabbix_server_dbencryption`: Use encryption with the database connection The following properties are related when using Elasticsearch for history storage: @@ -218,6 +180,17 @@ When the target host does not have access to the internet, but you do have a pro * `zabbix_http_proxy` * `zabbix_https_proxy` +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Example Playbook There are two ways of using the zabbix-web: @@ -237,12 +210,12 @@ When there is one host running both Zabbix Server and the Zabbix Web (Running My - role: geerlingguy.php - role: community.zabbix.zabbix_server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 - role: community.zabbix.zabbix_web zabbix_api_server_url: zabbix.mydomain.com zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 ``` @@ -256,7 +229,7 @@ This is a two host setup. On one host (Named: "zabbix-server") the Zabbix Server roles: - role: community.zabbix.zabbix_server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 - hosts: zabbix-web @@ -268,7 +241,7 @@ This is a two host setup. On one host (Named: "zabbix-server") the Zabbix Server zabbix_api_server_url: zabbix.mydomain.com zabbix_server_hostname: zabbix-server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 ``` @@ -289,13 +262,13 @@ zabbix.conf.php, for example to add LDAP CA certificates. To do this add a `zabb php_packages: - php - php-fpm - - php-acpu + - php-apcu - role: geerlingguy.apache-php-fpm - role: community.zabbix.zabbix_web zabbix_api_server_url: zabbix.mydomain.com zabbix_server_hostname: zabbix-server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 zabbix_web_env: LDAPTLS_CACERT: /etc/ssl/certs/ourcert.pem diff --git a/ansible_collections/community/zabbix/meta/runtime.yml b/ansible_collections/community/zabbix/meta/runtime.yml index 3e4fe8b79..fc8aee37e 100644 --- a/ansible_collections/community/zabbix/meta/runtime.yml +++ b/ansible_collections/community/zabbix/meta/runtime.yml @@ -1,17 +1,16 @@ --- -requires_ansible: '>=2.9.10' +requires_ansible: '>=2.12' action_groups: zabbix: - zabbix_action + - zabbix_api_info - zabbix_authentication - zabbix_autoregister - zabbix_discovery_rule - zabbix_globalmacro - - zabbix_group_facts - zabbix_group_info - zabbix_group - zabbix_host_events_info - - zabbix_host_facts - zabbix_host_info - zabbix_hostmacro - zabbix_host @@ -21,11 +20,13 @@ action_groups: - zabbix_mediatype - zabbix_proxy_info - zabbix_proxy - - zabbix_screen + - zabbix_regexp - zabbix_script - zabbix_service + - zabbix_settings - zabbix_template_info - zabbix_template + - zabbix_token - zabbix_user_directory - zabbix_usergroup - zabbix_user_info diff --git a/ansible_collections/community/zabbix/molecule/requirements.txt b/ansible_collections/community/zabbix/molecule/requirements.txt index bec205a0a..b7cbb1138 100644 --- a/ansible_collections/community/zabbix/molecule/requirements.txt +++ b/ansible_collections/community/zabbix/molecule/requirements.txt @@ -1,11 +1,13 @@ # Install CI dependencies for the Zabbix Roles ansible==7.0.0 -ansible-compat==0.5.0 +ansible-compat==3.0.0 ansible-core==2.14.2 -docker==5.0.2 -molecule==3.5.1 -molecule-docker==1.0.2 +docker==6.1.3 +molecule==4.0.4 +molecule-docker==2.1.0 netaddr==0.8.0 -pytest-testinfra==6.1.0 +pytest==7.2.1 +pytest-testinfra==7.0.0 ipaddr==2.2.0 ipaddress==1.0.23 +requests==2.31.0 diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/molecule.yml b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/molecule.yml index a0222246f..a48b6ae60 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/molecule.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/molecule.yml @@ -4,8 +4,8 @@ driver: platforms: - name: zabbix-agent-${MY_MOLECULE_CONTAINER:-centos} - image: ${MY_MOLECULE_IMAGE:-"geerlingguy/docker-centos8-ansible"} - command: ${MY_MOLECULE_DOCKER_COMMAND:-""} + image: geerlingguy/docker-${MY_MOLECULE_IMAGE:-rockylinux8}-ansible:latest + command: ${MOLECULE_DOCKER_COMMAND:-""} privileged: true pre_build_image: true networks: @@ -14,11 +14,10 @@ platforms: - /sys/fs/cgroup:/sys/fs/cgroup:ro groups: - agent + - ${MY_MOLECULE_VERSION:-v64} provisioner: name: ansible - lint: - name: ansible-lint playbooks: prepare: ../../common/playbooks/prepare.yml converge: ../../common/playbooks/converge.yml @@ -36,11 +35,15 @@ provisioner: zabbix_agent_listenip: 0.0.0.0 zabbix_agent_tlsconnect: psk zabbix_agent_tlsaccept: psk - + v64: + zabbix_agent_version: 6.4 + v62: + zabbix_agent_version: 6.2 + v60: + zabbix_agent_version: 6.0 scenario: test_sequence: - dependency - - lint - cleanup - destroy - syntax @@ -54,5 +57,3 @@ scenario: - destroy verifier: name: testinfra - lint: - name: flake8 diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/playbooks/prepare.yml b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/playbooks/prepare.yml index 3ce015db6..cf1100aab 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/playbooks/prepare.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/playbooks/prepare.yml @@ -3,7 +3,7 @@ hosts: all tasks: - name: "Installing packages on CentOS family" - package: + ansible.builtin.package: pkg: - net-tools - which @@ -14,7 +14,7 @@ - ansible_os_family == 'RedHat' - name: "Installing packages on CentOS (Sangoma) family" - package: + ansible.builtin.package: pkg: - net-tools - which @@ -25,7 +25,7 @@ - ansible_os_family == 'Sangoma' - name: "Installing packages on Debian family" - apt: + ansible.builtin.apt: name: - "{{ 'net-tools' if ansible_distribution_major_version not in ['10','18', '20'] else 'iproute2' }}" state: present @@ -36,7 +36,7 @@ - ansible_os_family == 'Debian' - name: "Installing packages on Suse family" - shell: zypper install -y python-xml python-libxml2 net-tools which + ansible.builtin.shell: zypper install -y python-xml python-libxml2 net-tools which register: zabbix_agent_prepare_packages_install until: zabbix_agent_prepare_packages_install is succeeded when: ansible_os_family == 'Suse' @@ -47,7 +47,7 @@ hosts: docker tasks: - name: "Download Docker CE repo file" - get_url: + ansible.builtin.get_url: url: https://download.docker.com/linux/centos/docker-ce.repo dest: /etc/yum.repos.d/docker-ce.repo mode: 0644 @@ -55,7 +55,7 @@ until: zabbix_agent_prepare_docker_repo is succeeded - name: "Installing Epel" - package: + ansible.builtin.package: pkg: - epel-release state: present @@ -63,7 +63,7 @@ until: zabbix_agent_prepare_docker_install is succeeded - name: "Installing Docker" - package: + ansible.builtin.package: pkg: - docker-ce - python-pip @@ -73,7 +73,7 @@ until: zabbix_agent_prepare_docker_install is succeeded - name: "Installing Docker Python" - pip: + ansible.builtin.pip: name: - docker state: present @@ -81,6 +81,6 @@ until: zabbix_agent_prepare_docker_install is succeeded - name: "Starting Docker service" - service: + ansible.builtin.service: name: docker state: started diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/tests/common/test_agent.py b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/tests/common/test_agent.py index 96d4a1716..43d9fe244 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/tests/common/test_agent.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/common/tests/common/test_agent.py @@ -37,13 +37,13 @@ def test_socket(host): assert host.socket("tcp://0.0.0.0:10050").is_listening -def test_zabbix_package(host, zabbix_agent_package): - assert zabbix_agent_package.is_installed - - if host.system_info.distribution == "debian": - if host.system_info.codename in ["bullseye", "focal"]: - assert zabbix_agent_package.version.startswith("1:6.4") - else: - assert zabbix_agent_package.version.startswith("1:6.0") - if host.system_info.distribution == "centos": - assert zabbix_agent_package.version.startswith("6.4") +# def test_zabbix_package(host, zabbix_agent_package): +# assert zabbix_agent_package.is_installed + +# if host.system_info.distribution == "debian": +# if host.system_info.codename in ["bullseye", "focal"]: +# assert zabbix_agent_package.version.startswith("1:6.4") +# else: +# assert zabbix_agent_package.version.startswith("1:6.0") +# if host.system_info.distribution == "centos": +# assert zabbix_agent_package.version.startswith("6.4") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2/tests/common/test_agent.py b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2/tests/common/test_agent.py index 96d4a1716..43d9fe244 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2/tests/common/test_agent.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2/tests/common/test_agent.py @@ -37,13 +37,13 @@ def test_socket(host): assert host.socket("tcp://0.0.0.0:10050").is_listening -def test_zabbix_package(host, zabbix_agent_package): - assert zabbix_agent_package.is_installed - - if host.system_info.distribution == "debian": - if host.system_info.codename in ["bullseye", "focal"]: - assert zabbix_agent_package.version.startswith("1:6.4") - else: - assert zabbix_agent_package.version.startswith("1:6.0") - if host.system_info.distribution == "centos": - assert zabbix_agent_package.version.startswith("6.4") +# def test_zabbix_package(host, zabbix_agent_package): +# assert zabbix_agent_package.is_installed + +# if host.system_info.distribution == "debian": +# if host.system_info.codename in ["bullseye", "focal"]: +# assert zabbix_agent_package.version.startswith("1:6.4") +# else: +# assert zabbix_agent_package.version.startswith("1:6.0") +# if host.system_info.distribution == "centos": +# assert zabbix_agent_package.version.startswith("6.4") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2autopsk/tests/common/test_agent.py b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2autopsk/tests/common/test_agent.py index 96d4a1716..43d9fe244 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2autopsk/tests/common/test_agent.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/agent2autopsk/tests/common/test_agent.py @@ -37,13 +37,13 @@ def test_socket(host): assert host.socket("tcp://0.0.0.0:10050").is_listening -def test_zabbix_package(host, zabbix_agent_package): - assert zabbix_agent_package.is_installed - - if host.system_info.distribution == "debian": - if host.system_info.codename in ["bullseye", "focal"]: - assert zabbix_agent_package.version.startswith("1:6.4") - else: - assert zabbix_agent_package.version.startswith("1:6.0") - if host.system_info.distribution == "centos": - assert zabbix_agent_package.version.startswith("6.4") +# def test_zabbix_package(host, zabbix_agent_package): +# assert zabbix_agent_package.is_installed + +# if host.system_info.distribution == "debian": +# if host.system_info.codename in ["bullseye", "focal"]: +# assert zabbix_agent_package.version.startswith("1:6.4") +# else: +# assert zabbix_agent_package.version.startswith("1:6.0") +# if host.system_info.distribution == "centos": +# assert zabbix_agent_package.version.startswith("6.4") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/autopsk/tests/common/test_agent.py b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/autopsk/tests/common/test_agent.py index 96d4a1716..43d9fe244 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/autopsk/tests/common/test_agent.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/autopsk/tests/common/test_agent.py @@ -37,13 +37,13 @@ def test_socket(host): assert host.socket("tcp://0.0.0.0:10050").is_listening -def test_zabbix_package(host, zabbix_agent_package): - assert zabbix_agent_package.is_installed - - if host.system_info.distribution == "debian": - if host.system_info.codename in ["bullseye", "focal"]: - assert zabbix_agent_package.version.startswith("1:6.4") - else: - assert zabbix_agent_package.version.startswith("1:6.0") - if host.system_info.distribution == "centos": - assert zabbix_agent_package.version.startswith("6.4") +# def test_zabbix_package(host, zabbix_agent_package): +# assert zabbix_agent_package.is_installed + +# if host.system_info.distribution == "debian": +# if host.system_info.codename in ["bullseye", "focal"]: +# assert zabbix_agent_package.version.startswith("1:6.4") +# else: +# assert zabbix_agent_package.version.startswith("1:6.0") +# if host.system_info.distribution == "centos": +# assert zabbix_agent_package.version.startswith("6.4") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/default/tests/common/test_agent.py b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/default/tests/common/test_agent.py index 96d4a1716..43d9fe244 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/default/tests/common/test_agent.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_agent_tests/molecule/default/tests/common/test_agent.py @@ -37,13 +37,13 @@ def test_socket(host): assert host.socket("tcp://0.0.0.0:10050").is_listening -def test_zabbix_package(host, zabbix_agent_package): - assert zabbix_agent_package.is_installed - - if host.system_info.distribution == "debian": - if host.system_info.codename in ["bullseye", "focal"]: - assert zabbix_agent_package.version.startswith("1:6.4") - else: - assert zabbix_agent_package.version.startswith("1:6.0") - if host.system_info.distribution == "centos": - assert zabbix_agent_package.version.startswith("6.4") +# def test_zabbix_package(host, zabbix_agent_package): +# assert zabbix_agent_package.is_installed + +# if host.system_info.distribution == "debian": +# if host.system_info.codename in ["bullseye", "focal"]: +# assert zabbix_agent_package.version.startswith("1:6.4") +# else: +# assert zabbix_agent_package.version.startswith("1:6.0") +# if host.system_info.distribution == "centos": +# assert zabbix_agent_package.version.startswith("6.4") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_javagateway/molecule.yml b/ansible_collections/community/zabbix/molecule/zabbix_javagateway/molecule.yml index f56745b9b..ee072707d 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_javagateway/molecule.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_javagateway/molecule.yml @@ -3,25 +3,35 @@ driver: name: docker platforms: - - name: zabbix-javagateway-${MY_MOLECULE_CONTAINER:-centos} - image: ${MY_MOLECULE_IMAGE:-"geerlingguy/docker-centos8-ansible"} - command: ${MY_MOLECULE_DOCKER_COMMAND:-""} + - name: zabbix-server-${MY_MOLECULE_CONTAINER:-centos} + image: geerlingguy/docker-${MY_MOLECULE_IMAGE:-rockylinux8}-ansible:latest privileged: true pre_build_image: true + command: ${MOLECULE_DOCKER_COMMAND:-""} networks: - name: zabbix volumes: - /sys/fs/cgroup:/sys/fs/cgroup:ro - + groups: + - ${MY_MOLECULE_VERSION:-v64} + - ${MY_MOLECULE_INTERPRETER:-python3} provisioner: name: ansible - lint: - name: ansible-lint env: ANSIBLE_COLLECTIONS_PATHS: $HOME/.ansible/collections/ansible_collections/community/zabbix ANSIBLE_ROLES_PATH: $HOME/.ansible/collections/ansible_collections/community/zabbix/roles + inventory: + group_vars: + python3: + ansible_python_interpreter: /usr/bin/python3 + python: + ansible_python_interpreter: /usr/bin/python + v64: + zabbix_javagateway_version: 6.4 + v62: + zabbix_javagateway_version: 6.2 + v60: + zabbix_javagateway_version: 6.0 verifier: name: testinfra - lint: - name: flake8 diff --git a/ansible_collections/community/zabbix/molecule/zabbix_javagateway/prepare.yml b/ansible_collections/community/zabbix/molecule/zabbix_javagateway/prepare.yml index 9d24c9f7e..3e3db6a1b 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_javagateway/prepare.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_javagateway/prepare.yml @@ -2,13 +2,12 @@ - name: Prepare hosts: all pre_tasks: - - name: "Set short version name" - set_fact: + ansible.builtin.set_fact: zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" - name: "Installing packages on CentOS" - yum: + ansible.builtin.yum: name: - net-tools - which @@ -20,21 +19,21 @@ - ansible_os_family == 'RedHat' - name: "Make sure the docs can be installed. (Debian)" - lineinfile: + ansible.builtin.lineinfile: path: /etc/dpkg/dpkg.cfg.d/excludes state: absent - regexp: 'path-exclude=/usr/share/doc/*' + regexp: "path-exclude=/usr/share/doc/*" when: - ansible_os_family != 'RedHat' - name: Check if warn parameter can be used for shell module - set_fact: + ansible.builtin.set_fact: produce_warn: False when: ansible_version.full is version("2.14", "<") # https://github.com/geerlingguy/ansible-role-java/issues/64 - name: "Apt update" - shell: "apt-get update && mkdir -p /usr/share/man/man1" + ansible.builtin.shell: "apt-get update && mkdir -p /usr/share/man/man1" args: warn: "{{ produce_warn | default(omit) }}" register: installation_dependencies @@ -43,7 +42,7 @@ - ansible_os_family != 'RedHat' - name: "Installing packages on NON-CentOS" - apt: + ansible.builtin.apt: name: - net-tools - apt-utils @@ -53,7 +52,6 @@ - "{{ zabbix_python_prefix }}-apt" - sudo - software-properties-common - - openjdk-11-jdk update_cache: true state: present register: installation_dependencies diff --git a/ansible_collections/community/zabbix/molecule/zabbix_proxy/molecule.yml b/ansible_collections/community/zabbix/molecule/zabbix_proxy/molecule.yml index 21ab813c4..4eb173acf 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_proxy/molecule.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_proxy/molecule.yml @@ -1,43 +1,51 @@ --- - driver: name: docker platforms: - - name: zabbix-proxy-${MY_MOLECULE_CONTAINER:-mysql-centos} - image: ${MY_MOLECULE_IMAGE:-"geerlingguy/docker-centos8-ansible"} - command: ${MY_MOLECULE_DOCKER_COMMAND:-""} + - name: zabbix-proxy-${MY_MOLECULE_CONTAINER:-centos} + image: geerlingguy/docker-${MY_MOLECULE_IMAGE:-rockylinux8}-ansible:latest privileged: true pre_build_image: true + command: ${MOLECULE_DOCKER_COMMAND:-""} networks: - name: zabbix volumes: - /sys/fs/cgroup:/sys/fs/cgroup:ro groups: - - ${MY_MOLECULE_GROUP:-mysql} + - ${MY_MOLECULE_DATABASE:-mysql} + - ${MY_MOLECULE_VERSION:-v64} provisioner: name: ansible - lint: - name: ansible-lint env: ANSIBLE_COLLECTIONS_PATHS: $HOME/.ansible/collections/ansible_collections/community/zabbix ANSIBLE_ROLES_PATH: $HOME/.ansible/collections/ansible_collections/community/zabbix/roles inventory: group_vars: + python3: + ansible_python_interpreter: /usr/bin/python3 + python: + ansible_python_interpreter: /usr/bin/python + v64: + zabbix_proxy_version: 6.4 + v62: + zabbix_proxy_version: 6.2 + v60: + zabbix_proxy_version: 6.0 mysql: + zabbix_proxy_dbname: zabbix + zabbix_proxy_dbuser: zabbix-dbuser zabbix_proxy_database: mysql - zabbix_proxy_database_long: mysql zabbix_proxy_dbport: 3306 zabbix_proxy_dbhost: mysql-host zabbix_proxy_dbhost_run_install: false - zabbix_proxy_privileged_host: '%' + zabbix_proxy_privileged_host: "%" zabbix_proxy_mysql_login_host: mysql-host zabbix_proxy_mysql_login_user: root zabbix_proxy_mysql_login_password: changeme zabbix_proxy_mysql_login_port: 3306 - postgresql: + pgsql: zabbix_proxy_database: pgsql - zabbix_proxy_database_long: postgresql zabbix_proxy_dbport: 5432 zabbix_proxy_dbhost: postgresql-host zabbix_proxy_dbhost_run_install: false @@ -49,8 +57,5 @@ provisioner: zabbix_proxy_database: sqlite3 zabbix_proxy_database_long: sqlite3 zabbix_proxy_dbname: /path/to/sqlite3.db - verifier: name: testinfra - lint: - name: flake8 diff --git a/ansible_collections/community/zabbix/molecule/zabbix_proxy/prepare.yml b/ansible_collections/community/zabbix/molecule/zabbix_proxy/prepare.yml index 0fc4ef320..c5e3b9e45 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_proxy/prepare.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_proxy/prepare.yml @@ -3,7 +3,6 @@ hosts: localhost connection: local pre_tasks: - - name: "Create MySQL Container" docker_container: name: mysql-host @@ -32,14 +31,13 @@ no_log: true with_items: "{{ molecule_yml.platforms }}" when: - - '"postgresql" in item.groups' + - '"pgsql" in item.groups' - name: Prepare hosts: all tasks: - - name: "Set short version name" - set_fact: + ansible.builtin.set_fact: zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" - name: "Create group for imaginary host" @@ -51,7 +49,7 @@ changed_when: false - name: "Installing packages on CentOS" - yum: + ansible.builtin.yum: name: - net-tools - which @@ -62,24 +60,13 @@ when: - ansible_os_family == 'RedHat' - - name: "Installing packages on CentOS" - yum: - name: - - mysql - state: present - register: installation_dependencies - until: installation_dependencies is succeeded - when: - - ansible_os_family == 'RedHat' - - inventory_hostname in groups['mysql'] - - name: Check if warn parameter can be used for shell module - set_fact: + ansible.builtin.set_fact: produce_warn: False when: ansible_version.full is version("2.14", "<") - name: "Apt update" - shell: "apt-get update && echo exit 0 > /usr/sbin/policy-rc.d" + ansible.builtin.shell: "apt-get update && echo exit 0 > /usr/sbin/policy-rc.d" args: warn: "{{ produce_warn | default(omit) }}" register: installation_dependencies @@ -88,7 +75,7 @@ - ansible_os_family != 'RedHat' - name: "Installing packages on NON-CentOS" - apt: + ansible.builtin.apt: name: - net-tools - apt-utils @@ -104,13 +91,13 @@ - ansible_os_family != 'RedHat' - name: "Configure SUDO." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/sudoers line: "Defaults !requiretty" state: present - name: "Make sure the docs can be installed. (RedHat)" - lineinfile: + ansible.builtin.lineinfile: dest: /etc/yum.conf line: "tsflags=nodocs" state: absent @@ -118,17 +105,9 @@ - ansible_os_family == 'RedHat' - name: "Make sure the docs can be installed. (Debian)" - lineinfile: + ansible.builtin.lineinfile: path: /etc/dpkg/dpkg.cfg.d/excludes state: absent - regexp: 'path-exclude=/usr/share/doc/*' + regexp: "path-exclude=/usr/share/doc/*" when: - ansible_os_family != 'RedHat' - - - name: PyMySQL - pip: - name: PyMySQL - register: installation_dependencies - until: installation_dependencies is succeeded - when: - - inventory_hostname in groups['mysql'] diff --git a/ansible_collections/community/zabbix/molecule/zabbix_proxy/tests/test_default.py b/ansible_collections/community/zabbix/molecule/zabbix_proxy/tests/test_default.py index 4ccbfeb4e..f96874740 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_proxy/tests/test_default.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_proxy/tests/test_default.py @@ -17,28 +17,18 @@ def test_zabbixproxy_running_and_enabled(host): assert zabbix.is_running -@pytest.mark.parametrize( - "proxy", [("zabbix-proxy-pgsql"), ("zabbix-proxy-mysql"), ("zabbix-proxy-sqlite3")] -) -def test_zabbix_package(host, proxy): +def test_zabbix_package(host): ansible_data = host.ansible.get_variables() - zabbixhost = ansible_data["inventory_hostname"] + version = ansible_data['zabbix_proxy_version'] + database = ansible_data['zabbix_proxy_database'] - zabbixhost = zabbixhost.replace("-centos", "") - zabbixhost = zabbixhost.replace("-debian", "") - zabbixhost = zabbixhost.replace("-ubuntu", "") - - if zabbixhost == proxy: - zabbix_proxy = host.package(proxy) - if host.system_info.distribution in ["debian", "ubuntu"]: - assert zabbix_proxy.version.startswith("1:6.4") - elif host.system_info.distribution == "centos": - assert zabbix_proxy.version.startswith("6.4") - assert zabbix_proxy.is_installed + zabbix_proxy = host.package(f'zabbix-proxy-%s' % database) + assert str(version) in zabbix_proxy.version def test_zabbix_proxy_dot_conf(host): zabbix_proxy_conf = host.file("/etc/zabbix/zabbix_proxy.conf") + assert zabbix_proxy_conf.exists assert zabbix_proxy_conf.user == "zabbix" assert zabbix_proxy_conf.group == "zabbix" assert zabbix_proxy_conf.mode == 0o644 @@ -52,13 +42,13 @@ def test_zabbix_include_dir(host): assert zabbix_include_dir.is_directory assert zabbix_include_dir.user == "zabbix" assert zabbix_include_dir.group == "zabbix" - # assert zabbix_include_dir.mode == 0o644 def test_zabbix_proxy_logfile(host): zabbix_logfile = host.file("/var/log/zabbix/zabbix_proxy.log") - + assert zabbix_logfile.exists assert not zabbix_logfile.contains("Access denied for user") assert not zabbix_logfile.contains("database is down: reconnecting") + assert not zabbix_logfile.contains("Both are missing in the system.") # Missing fping assert zabbix_logfile.contains("current database version") assert zabbix_logfile.contains(r"proxy #0 started \[main process\]") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_server/molecule.yml b/ansible_collections/community/zabbix/molecule/zabbix_server/molecule.yml index 4fa0a8daa..2424455f4 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_server/molecule.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_server/molecule.yml @@ -1,43 +1,54 @@ --- - driver: name: docker platforms: - - name: zabbix-server-${MY_MOLECULE_CONTAINER:-mysql-centos} - image: ${MY_MOLECULE_IMAGE:-"geerlingguy/docker-centos8-ansible"} - command: ${MY_MOLECULE_DOCKER_COMMAND:-""} + - name: zabbix-server-${MY_MOLECULE_CONTAINER:-centos} + image: geerlingguy/docker-${MY_MOLECULE_IMAGE:-rockylinux8}-ansible:latest privileged: true pre_build_image: true + command: ${MOLECULE_DOCKER_COMMAND:-""} networks: - name: zabbix volumes: - /sys/fs/cgroup:/sys/fs/cgroup:ro groups: - - ${MY_MOLECULE_GROUP:-mysql} + - ${MY_MOLECULE_DATABASE:-mysql} + - ${MY_MOLECULE_VERSION:-v64} + - ${MY_MOLECULE_INTERPRETER:-python3} provisioner: name: ansible - lint: - name: ansible-lint env: ANSIBLE_COLLECTIONS_PATHS: $HOME/.ansible/collections/ansible_collections/community/zabbix ANSIBLE_ROLES_PATH: $HOME/.ansible/collections/ansible_collections/community/zabbix/roles inventory: group_vars: + python3: + ansible_python_interpreter: /usr/bin/python3 + python: + ansible_python_interpreter: /usr/bin/python + v64: + zabbix_server_version: 6.4 + v62: + zabbix_server_version: 6.2 + v60: + zabbix_server_version: 6.0 + v50: + zabbix_server_version: 5.0 mysql: + zabbix_server_dbname: zabbix + zabbix_server_dbuser: zabbix-dbuser zabbix_server_database: mysql - zabbix_server_database_long: mysql zabbix_server_dbport: 3306 zabbix_server_dbhost: mysql-host zabbix_server_dbhost_run_install: false - zabbix_server_privileged_host: '%' + zabbix_server_privileged_host: "%" zabbix_server_mysql_login_host: mysql-host zabbix_server_mysql_login_user: root zabbix_server_mysql_login_password: changeme zabbix_server_mysql_login_port: 3306 - postgresql: + pgsql: zabbix_server_database: pgsql - zabbix_server_database_long: postgresql zabbix_server_dbport: 5432 zabbix_server_dbhost: postgresql-host zabbix_server_dbhost_run_install: false @@ -48,5 +59,3 @@ provisioner: verifier: name: testinfra - lint: - name: flake8 diff --git a/ansible_collections/community/zabbix/molecule/zabbix_server/prepare.yml b/ansible_collections/community/zabbix/molecule/zabbix_server/prepare.yml index 51945c066..922b33753 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_server/prepare.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_server/prepare.yml @@ -3,11 +3,10 @@ hosts: localhost connection: local pre_tasks: - - name: "Create MySQL Container" docker_container: name: mysql-host - image: mysql:8.0 + image: mysql:8.0.32 state: started recreate: true networks: @@ -32,12 +31,11 @@ no_log: true with_items: "{{ molecule_yml.platforms }}" when: - - '"postgresql" in item.groups' + - '"pgsql" in item.groups' - name: Prepare hosts: all tasks: - - name: "Create group for imaginary host" add_host: name: imaginary-host @@ -47,7 +45,7 @@ changed_when: false - name: "Installing packages on CentOS" - yum: + ansible.builtin.yum: name: - net-tools - which @@ -59,7 +57,7 @@ - ansible_os_family == 'RedHat' - name: "Installing packages on CentOS" - yum: + ansible.builtin.yum: name: - mysql state: present @@ -70,12 +68,12 @@ - inventory_hostname in groups['mysql'] - name: Check if warn parameter can be used for shell module - set_fact: - produce_warn: False + ansible.builtin.set_fact: + produce_warn: false when: ansible_version.full is version("2.14", "<") - name: "Apt update" - shell: "apt-get update && echo exit 0 > /usr/sbin/policy-rc.d" + ansible.builtin.shell: "apt-get update && echo exit 0 > /usr/sbin/policy-rc.d" args: warn: "{{ produce_warn | default(omit) }}" register: installation_dependencies @@ -84,7 +82,7 @@ - ansible_os_family != 'RedHat' - name: "Installing packages on NON-CentOS" - apt: + ansible.builtin.apt: name: - net-tools - apt-utils @@ -99,13 +97,13 @@ - ansible_os_family != 'RedHat' - name: "Configure SUDO." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/sudoers line: "Defaults !requiretty" state: present - name: "Make sure the docs are installed." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/yum.conf line: "tsflags=nodocs" state: absent @@ -113,7 +111,7 @@ - ansible_os_family == 'RedHat' - name: PyMySQL - pip: + ansible.builtin.pip: name: PyMySQL register: installation_dependencies until: installation_dependencies is succeeded diff --git a/ansible_collections/community/zabbix/molecule/zabbix_server/tests/test_default.py b/ansible_collections/community/zabbix/molecule/zabbix_server/tests/test_default.py index 9a119d5ac..ee43ad2a3 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_server/tests/test_default.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_server/tests/test_default.py @@ -1,5 +1,7 @@ import os import pytest +from pathlib import Path + import testinfra.utils.ansible_runner @@ -17,26 +19,18 @@ def test_zabbiserver_running_and_enabled(host): assert zabbix.is_running -@pytest.mark.parametrize("server", [("zabbix-server-pgsql"), ("zabbix-server-mysql")]) -def test_zabbix_package(host, server): +def test_zabbix_package(host): ansible_data = host.ansible.get_variables() - zabbixhost = ansible_data["inventory_hostname"] - - zabbixhost = zabbixhost.replace("-centos", "") - zabbixhost = zabbixhost.replace("-debian", "") - zabbixhost = zabbixhost.replace("-ubuntu", "") + version = ansible_data['zabbix_server_version'] + database = ansible_data['zabbix_server_database'] - if zabbixhost == server: - zabbix_server = host.package(server) - if host.system_info.distribution in ["debian", "ubuntu"]: - assert zabbix_server.version.startswith("1:6.4") - elif host.system_info.distribution == "centos": - assert zabbix_server.version.startswith("6.4") - assert zabbix_server.is_installed + zabbix_server = host.package(f'zabbix-server-%s' % database) + assert str(version) in zabbix_server.version def test_zabbix_server_dot_conf(host): zabbix_server_conf = host.file("/etc/zabbix/zabbix_server.conf") + assert zabbix_server_conf.exists assert zabbix_server_conf.user == "zabbix" assert zabbix_server_conf.group == "zabbix" assert zabbix_server_conf.mode == 0o640 @@ -50,13 +44,13 @@ def test_zabbix_include_dir(host): assert zabbix_include_dir.is_directory assert zabbix_include_dir.user == "zabbix" assert zabbix_include_dir.group == "zabbix" - # assert zabbix_include_dir.mode == 0o644 def test_zabbix_server_logfile(host): zabbix_logfile = host.file("/var/log/zabbix/zabbix_server.log") - + assert zabbix_logfile.exists assert not zabbix_logfile.contains("Access denied for user") assert not zabbix_logfile.contains("database is down: reconnecting") + assert not zabbix_logfile.contains("Both are missing in the system.") # Missing fping assert zabbix_logfile.contains("current database version") assert zabbix_logfile.contains(r"server #0 started \[main process\]") diff --git a/ansible_collections/community/zabbix/molecule/zabbix_web/molecule.yml b/ansible_collections/community/zabbix/molecule/zabbix_web/molecule.yml index baffecc47..0aa3ab800 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_web/molecule.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_web/molecule.yml @@ -10,30 +10,45 @@ dependency: driver: name: docker platforms: - - name: zabbix-web-${MY_MOLECULE_CONTAINER:-mysql-centos8} - image: ${MY_MOLECULE_IMAGE:-"geerlingguy/docker-centos8-ansible"} - command: ${MY_MOLECULE_DOCKER_COMMAND:-""} + - name: zabbix-web-${MY_MOLECULE_CONTAINER:-centos} + image: geerlingguy/docker-${MY_MOLECULE_IMAGE:-rockylinux8}-ansible:latest privileged: true pre_build_image: true + command: ${MOLECULE_DOCKER_COMMAND:-""} networks: - name: zabbix volumes: - /sys/fs/cgroup:/sys/fs/cgroup:ro groups: - - ${MY_MOLECULE_GROUP:-mysql} + - ${MY_MOLECULE_DATABASE:-mysql} + - ${MY_MOLECULE_VERSION:-v64} + - ${MY_MOLECULE_INTERPRETER:-python3} + - ${MY_MOLECULE_WEB_SERVER:-apache} provisioner: name: ansible - lint: - name: ansible-lint env: ANSIBLE_COLLECTIONS_PATHS: $HOME/.ansible/collections/ansible_collections/community/zabbix ANSIBLE_ROLES_PATH: $HOME/.ansible/collections/ansible_collections/community/zabbix/roles inventory: group_vars: + all: + zabbix_api_server_url: zabbix-web-${MY_MOLECULE_CONTAINER:-centos} + python3: + ansible_python_interpreter: /usr/bin/python3 + python: + ansible_python_interpreter: /usr/bin/python + v64: + zabbix_server_version: 6.4 + zabbix_web_version: 6.4 + v62: + zabbix_server_version: 6.2 + zabbix_web_version: 6.2 + v60: + zabbix_server_version: 6.0 + zabbix_web_version: 6.0 mysql: zabbix_server_database: mysql - zabbix_server_database_long: mysql zabbix_server_dbport: 3306 zabbix_server_dbhost: mysql-host zabbix_server_dbhost_run_install: false @@ -42,9 +57,8 @@ provisioner: zabbix_server_mysql_login_user: root zabbix_server_mysql_login_password: changeme zabbix_server_mysql_login_port: 3306 - postgresql: + pgsql: zabbix_server_database: pgsql - zabbix_server_database_long: postgresql zabbix_server_dbport: 5432 zabbix_server_dbhost: postgresql-host zabbix_server_dbhost_run_install: false @@ -52,44 +66,11 @@ provisioner: zabbix_server_pgsql_login_user: postgres zabbix_server_pgsql_login_password: changeme zabbix_server_pgsql_login_port: 5432 - host_vars: - zabbix-web-pgsql-debian: - zabbix_websrv: apache - zabbix_php_fpm_conf_listen: false - zabbix_api_server_url: zabbix-web-pgsql-debian - zabbix_websrv_servername: zabbix-web-pgsql-debian - zabbix-web-mysql-debian: - zabbix_websrv: apache - zabbix_php_fpm_conf_listen: false - zabbix_api_server_url: zabbix-web-mysql-debian - zabbix_websrv_servername: zabbix-web-mysql-debian - zabbix-web-pgsql-centos8: - ansible_rhn_repo_disable_gpg_check: true - zabbix_websrv: apache - zabbix_php_fpm_conf_listen: false - zabbix_api_server_url: zabbix-web-pgsql-centos8 - zabbix_websrv_servername: zabbix-web-pgsql-centos8 - zabbix-web-mysql-centos8: - ansible_rhn_repo_disable_gpg_check: true - php_fpm_pool_user: nginx - php_fpm_pool_group: nginx - zabbix_websrv: nginx - zabbix_php_fpm_conf_listen: false - zabbix_api_server_url: zabbix-web-mysql-centos8 - zabbix_websrv_servername: zabbix-web-mysql-centos8 - zabbix-web-mysql-ubuntu18: - zabbix_websrv: nginx - zabbix_php_fpm_conf_listen: false - zabbix_api_server_url: zabbix-web-mysql-ubuntu18 - zabbix_websrv_servername: zabbix-web-mysql-ubuntu18 + apache: + zabbix_web_http_server: apache + nginx: + zabbix_web_http_server: nginx php_webserver_daemon: nginx - zabbix-web-pgsql-ubuntu20: - zabbix_php_fpm_conf_listen: false - zabbix_websrv: apache - zabbix_api_server_url: zabbix-web-pgsql-ubuntu20 - zabbix_websrv_servername: zabbix-web-pgsql-ubuntu20 verifier: name: testinfra - lint: - name: flake8 diff --git a/ansible_collections/community/zabbix/molecule/zabbix_web/prepare.yml b/ansible_collections/community/zabbix/molecule/zabbix_web/prepare.yml index 3c0c6db86..204eb8f56 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_web/prepare.yml +++ b/ansible_collections/community/zabbix/molecule/zabbix_web/prepare.yml @@ -31,7 +31,7 @@ no_log: true with_items: "{{ molecule_yml.platforms }}" when: - - '"postgresql" in item.groups' + - '"pgsql" in item.groups' - name: Prepare hosts: all @@ -45,14 +45,11 @@ changed_when: false - name: "Installing packages on CentOS" - yum: + ansible.builtin.yum: name: - net-tools - which - - curl - sudo - - "{{ 'python3-pip' if ansible_distribution_major_version == '8' else 'python-pip' }}" - - "{{ 'python3-libselinux' if ansible_distribution_major_version == '8' else 'libselinux-python' }}" state: present register: installation_dependencies until: installation_dependencies is succeeded @@ -60,7 +57,7 @@ - ansible_os_family == 'RedHat' - name: "Installing packages (CentOS7)" - yum: + ansible.builtin.yum: name: - centos-release-scl state: present @@ -70,7 +67,7 @@ - ansible_distribution_major_version == '7' - name: "Installing MySQL on CentOS" - yum: + ansible.builtin.yum: name: - mysql state: present @@ -80,20 +77,29 @@ - ansible_os_family == 'RedHat' - inventory_hostname in groups['mysql'] + - name: Check if warn parameter can be used for shell module + ansible.builtin.set_fact: + produce_warn: false + when: ansible_version.full is version("2.14", "<") + + - name: "Apt update" + ansible.builtin.shell: "apt-get update && echo exit 0 > /usr/sbin/policy-rc.d" + args: + warn: "{{ produce_warn | default(omit) }}" + register: installation_dependencies + until: installation_dependencies is succeeded + when: + - ansible_os_family != 'RedHat' + - name: "Installing packages on NON-CentOS" - apt: + ansible.builtin.apt: name: - net-tools - - curl - apt-utils - - apt-transport-https - - ca-certificates - - gnupg2 + - python3-pip - gpg-agent - sudo - - vim - - "{{ 'python3-apt' if ansible_distribution_major_version in ['10', '11', '18', '20'] else 'python-apt' }}" - - "{{ 'python3-pip' if ansible_distribution_major_version in ['10', '11', '18', '20'] else 'python-pip' }}" + - curl update_cache: true state: present register: installation_dependencies @@ -102,13 +108,13 @@ - ansible_os_family != 'RedHat' - name: "Configure SUDO." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/sudoers line: "Defaults !requiretty" state: present - name: "Make sure the docs are installed." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/yum.conf line: "tsflags=nodocs" state: absent @@ -116,7 +122,7 @@ - ansible_os_family == 'RedHat' - name: PyMySQL - pip: + ansible.builtin.pip: name: PyMySQL register: installation_dependencies until: installation_dependencies is succeeded @@ -124,26 +130,72 @@ - inventory_hostname in groups['mysql'] - name: Enabeling PHP 7.4 - command: dnf module enable php:7.4 -y + ansible.builtin.command: dnf module enable php:7.4 -y when: - ansible_os_family == 'RedHat' - ansible_distribution_major_version == "8" + - name: Set PHP packages (Centos 8+) + ansible.builtin.set_fact: + php_packages: + - php + - php-cli + - php-common + - php-devel + - php-fpm + - php-gd + - php-ldap + - php-mbstring + - php-opcache + - php-pdo + - php-pear + - php-pecl-apcu + - php-xml + when: + - ansible_distribution_major_version >= '8' + - ansible_os_family == "RedHat" + + - name: Set PHP Version (Ubuntu 2204) + ansible.builtin.set_fact: + __php_default_version_debian: "8.1" + when: + - ansible_distribution_major_version >= '22' + - ansible_os_family == "Debian" + + - name: Set PHP packages (Ubuntu 2204) + ansible.builtin.set_fact: + __php_packages: + - php{{ __php_default_version_debian }}-common + - php{{ __php_default_version_debian }}-cli + - php{{ __php_default_version_debian }}-dev + - php{{ __php_default_version_debian }}-fpm + - libpcre3-dev + - php{{ __php_default_version_debian }}-gd + - php{{ __php_default_version_debian }}-curl + - php{{ __php_default_version_debian }}-imap + - php-json + - php{{ __php_default_version_debian }}-opcache + - php{{ __php_default_version_debian }}-xml + - php{{ __php_default_version_debian }}-mbstring + - php{{ __php_default_version_debian }}-apcu + - php{{ __php_default_version_debian }}-sqlite3 + when: + - ansible_distribution_major_version >= '22' + - ansible_os_family == "Debian" + roles: - role: geerlingguy.apache when: - - zabbix_websrv == "apache" + - zabbix_web_http_server == "apache" - role: geerlingguy.nginx when: - - zabbix_websrv == "nginx" + - zabbix_web_http_server == "nginx" - role: geerlingguy.php - when: - - ansible_os_family != 'RedHat' or (ansible_os_family == 'RedHat' and ansible_distribution_major_version == "8") - role: zabbix_server post_tasks: - name: "Remove file" - file: + ansible.builtin.file: path: "{{ item }}" state: absent with_items: diff --git a/ansible_collections/community/zabbix/molecule/zabbix_web/tests/test_default.py b/ansible_collections/community/zabbix/molecule/zabbix_web/tests/test_default.py index a6f7527b0..f4882b97b 100644 --- a/ansible_collections/community/zabbix/molecule/zabbix_web/tests/test_default.py +++ b/ansible_collections/community/zabbix/molecule/zabbix_web/tests/test_default.py @@ -8,34 +8,19 @@ testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( ).get_hosts("all") -@pytest.mark.parametrize( - "server, redhat, debian", - [ - ("zabbix-server-pgsql", "zabbix-web-pgsql", "zabbix-frontend-php"), - ("zabbix-server-mysql", "zabbix-web-mysql", "zabbix-frontend-php"), - ], -) -def test_zabbix_package(host, server, redhat, debian): - host = host.backend.get_hostname() - host = host.replace("-centos7", "") - host = host.replace("-centos8", "") - host = host.replace("-debian", "") - host = host.replace("-ubuntu", "") +def test_zabbix_package(host): + ansible_data = host.ansible.get_variables() + version = ansible_data['zabbix_web_version'] + webserver = ansible_data['zabbix_web_http_server'] - if host == server: - if host.system_info.distribution in ["debian", "ubuntu"]: - zabbix_web = host.package(debian) - assert zabbix_web.version.startswith("1:6.4") - elif host.system_info.distribution == "centos": - zabbix_web = host.package(redhat) - assert zabbix_web.version.startswith("6.4") - assert zabbix_web.is_installed + zabbix_web = host.package(f'zabbix-%s-conf' % webserver) + assert str(version) in zabbix_web.version def test_zabbix_web(host): zabbix_web = host.file("/etc/zabbix/web/zabbix.conf.php") ansible_variables = host.ansible.get_variables() - zabbix_websrv = str(ansible_variables["zabbix_websrv"]) + zabbix_websrv = str(ansible_variables["zabbix_web_http_server"]) if host.system_info.distribution in ["debian", "ubuntu"]: assert zabbix_web.user == "www-data" @@ -47,7 +32,7 @@ def test_zabbix_web(host): elif zabbix_websrv == "nginx": assert zabbix_web.user == "nginx" assert zabbix_web.group == "nginx" - assert zabbix_web.mode == 0o640 + assert zabbix_web.mode == 0o644 def test_zabbix_api(host): diff --git a/ansible_collections/community/zabbix/plugins/doc_fragments/connection_persistent.py b/ansible_collections/community/zabbix/plugins/doc_fragments/connection_persistent.py deleted file mode 100644 index 6d9a82a8e..000000000 --- a/ansible_collections/community/zabbix/plugins/doc_fragments/connection_persistent.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -from __future__ import absolute_import, division, print_function - -__metaclass__ = type - - -class ModuleDocFragment(object): - - # Standard files documentation fragment - DOCUMENTATION = r""" -options: - persistent_connect_timeout: - type: int - description: - - Configures, in seconds, the amount of time to wait when trying to initially - establish a persistent connection. If this value expires before the connection - to the remote device is completed, the connection will fail. - default: 30 - ini: - - section: persistent_connection - key: connect_timeout - env: - - name: ANSIBLE_PERSISTENT_CONNECT_TIMEOUT - vars: - - name: ansible_connect_timeout - persistent_command_timeout: - type: int - description: - - Configures, in seconds, the amount of time to wait for a command to - return from the remote device. If this timer is exceeded before the - command returns, the connection plugin will raise an exception and - close. - default: 30 - ini: - - section: persistent_connection - key: command_timeout - env: - - name: ANSIBLE_PERSISTENT_COMMAND_TIMEOUT - vars: - - name: ansible_command_timeout - persistent_log_messages: - type: boolean - description: - - This flag will enable logging the command executed and response received from - target device in the ansible log file. For this option to work 'log_path' ansible - configuration option is required to be set to a file path with write access. - - Be sure to fully understand the security implications of enabling this - option as it could create a security vulnerability by logging sensitive information in log file. - default: False - ini: - - section: persistent_connection - key: log_messages - env: - - name: ANSIBLE_PERSISTENT_LOG_MESSAGES - vars: - - name: ansible_persistent_log_messages -""" diff --git a/ansible_collections/community/zabbix/plugins/doc_fragments/zabbix.py b/ansible_collections/community/zabbix/plugins/doc_fragments/zabbix.py index 2cd64b00f..5cb7fcd54 100644 --- a/ansible_collections/community/zabbix/plugins/doc_fragments/zabbix.py +++ b/ansible_collections/community/zabbix/plugins/doc_fragments/zabbix.py @@ -7,31 +7,8 @@ class ModuleDocFragment(object): # Standard documentation fragment - DOCUMENTATION = r''' + DOCUMENTATION = r""" options: - server_url: - description: - - URL of Zabbix server, with protocol (http or https). - C(url) is an alias for C(server_url). - - If not set the environment variable C(ZABBIX_SERVER) will be used. - - This option is deprecated with the move to httpapi connection and will be removed in the next release - required: false - type: str - aliases: [ url ] - login_user: - description: - - Zabbix user name. - - If not set the environment variable C(ZABBIX_USERNAME) will be used. - - This option is deprecated with the move to httpapi connection and will be removed in the next release - type: str - required: false - login_password: - description: - - Zabbix user password. - - If not set the environment variable C(ZABBIX_PASSWORD) will be used. - - This option is deprecated with the move to httpapi connection and will be removed in the next release - type: str - required: false http_login_user: description: - Basic Auth login @@ -42,20 +19,4 @@ options: - Basic Auth password type: str required: false - timeout: - description: - - The timeout of API request (seconds). - - This option is deprecated with the move to httpapi connection and will be removed in the next release - - The default value is C(10) - type: int - validate_certs: - description: - - If set to False, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. - - If not set the environment variable C(ZABBIX_VALIDATE_CERTS) will be used. - - This option is deprecated with the move to httpapi connection and will be removed in the next release - - The default value is C(true) - type: bool -notes: - - If you use I(login_password=zabbix), the word "zabbix" is replaced by "********" in all module output, because I(login_password) uses C(no_log). - See L(this FAQ,https://docs.ansible.com/ansible/latest/network/user_guide/faq.html#why-is-my-output-sometimes-replaced-with) for more information. -''' + """ diff --git a/ansible_collections/community/zabbix/plugins/httpapi/zabbix.py b/ansible_collections/community/zabbix/plugins/httpapi/zabbix.py index 3db65532c..56ba0356d 100644 --- a/ansible_collections/community/zabbix/plugins/httpapi/zabbix.py +++ b/ansible_collections/community/zabbix/plugins/httpapi/zabbix.py @@ -165,12 +165,16 @@ class HttpApi(HttpApiBase): try: json_data = json.loads(value) if value else {} - if "result" in json_data: - json_data = json_data["result"] # JSONDecodeError only available on Python 3.5+ except ValueError: raise ConnectionError("Invalid JSON response: %s" % value) + if "error" in json_data: + raise ConnectionError("REST API returned %s when sending %s" % (json_data["error"], data)) + + if "result" in json_data: + json_data = json_data["result"] + try: # Some methods return bool not a dict in "result" iter(json_data) @@ -178,9 +182,6 @@ class HttpApi(HttpApiBase): # Do not try to find "error" if it is not a dict return response.getcode(), json_data - if "error" in json_data: - raise ConnectionError("REST API returned %s when sending %s" % (json_data["error"], data)) - return response.getcode(), json_data except AnsibleConnectionFailure as e: self.connection.queue_message("vvv", "AnsibleConnectionFailure: %s" % e) diff --git a/ansible_collections/community/zabbix/plugins/inventory/zabbix_inventory.py b/ansible_collections/community/zabbix/plugins/inventory/zabbix_inventory.py index 437d34227..8e4be416b 100644 --- a/ansible_collections/community/zabbix/plugins/inventory/zabbix_inventory.py +++ b/ansible_collections/community/zabbix/plugins/inventory/zabbix_inventory.py @@ -1,8 +1,9 @@ # # Copyright: (c), Ansible Project # -# (c) 2013, Greg Buehler +# (c) 2023, Alexandre Georges # (c) 2018, Filippo Ferrazini +# (c) 2013, Greg Buehler # (c) 2021, Timothy Test # Modified from ServiceNow Inventory Plugin and Zabbix inventory Script # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -10,7 +11,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" name: zabbix_inventory author: - Timothy Test (@ttestscripting) @@ -20,8 +21,7 @@ description: - Zabbix Inventory plugin - All vars from zabbix are prefixed with zbx_ requirements: - - "python >= 2.6" - - "zabbix-api >= 0.5.4" + - "python >= 3.9" options: server_url: description: @@ -35,7 +35,7 @@ options: proxy: description: Proxy server to use for reaching zabbix API type: string - default: '' + default: "" host_zapi_query: description: - API query for hosts - see zabbix documentation for more details U(https://www.zabbix.com/documentation/current/manual/api/reference/host/get) @@ -47,9 +47,9 @@ options: description: - query - Return an applications property with host applications. - - To return all values specify 'extend' - - Can be limited to different fields for example setting the vaule to ['name'] will only return the name - - Additional fields can be specified by comma seperated value ['name', 'field2'] + - To return all values specify "extend" + - Can be limited to different fields for example setting the vaule to ["name"] will only return the name + - Additional fields can be specified by comma seperated value ["name", "field2"] - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/application/object) for more details on field names selectDiscoveries: type: str @@ -200,6 +200,12 @@ options: required: true env: - name: ZABBIX_PASSWORD + auth_token: + description: + - Zabbix authentication token (see https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/users/api_tokens) + - If provided then C(login_user) and C(login_password) are ignored + type: str + required: false http_login_user: description: - Basic Auth login @@ -228,9 +234,9 @@ options: extends_documentation_fragment: - constructed - inventory_cache -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # Simple Inventory Plugin example # This will create an inventory with details from zabbix such as applications name, applicaitonids, Parent Template Name, and group membership name #It will also create 2 ansible inventory groups for enabled and disabled hosts in zabbix based on the status field. @@ -286,27 +292,34 @@ validate_certs: false compose: zbx_testvar: zbx_status.replace("1", "Disabled") +#Using auth token instead of username/password +plugin: community.zabbix.zabbix_inventory +server_url: https://zabbix.com +auth_token: 3bc3dc85e13e2431812e7a32fa8341cbcf378e5101356c015fdf2e35fd511b06 +validate_certs: false -''' +""" from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable, to_safe_group_name import os import atexit -import traceback - -try: - from zabbix_api import ZabbixAPI - HAS_ZABBIX_API = True -except ImportError: - ZBX_IMP_ERR = traceback.format_exc() - HAS_ZABBIX_API = False +import json +from ansible.module_utils.urls import Request +from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError +from ansible.module_utils.compat.version import LooseVersion +from ansible.errors import AnsibleParserError class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): NAME = 'community.zabbix.zabbix_inventory' - def login_zabbix(self): + def __init__(self): + super().__init__() + self.auth = '' + self.zabbix_verion = '' + + def api_request(self, method, params=None): # set proxy information if required proxy = self.get_option('proxy') os.environ['http_proxy'] = proxy @@ -315,24 +328,74 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): os.environ['HTTPS_PROXY'] = proxy server_url = self.get_option('server_url') - http_login_user = self.get_option('login_user') - http_login_password = self.get_option('login_password') validate_certs = self.get_option('validate_certs') timeout = self.get_option('timeout') - self._zapi = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) - self.login() - self._zbx_api_version = self._zapi.api_version()[:5] - - def login(self): - # check if api already logged in - if not self._zapi.auth != '': - try: - login_user = self.get_option('login_user') - login_password = self.get_option('login_password') - self._zapi.login(login_user, login_password) - atexit.register(self._zapi.logout) - except Exception as e: - self.display.vvv(msg="Failed to connect to Zabbix server: %s" % e) + + headers = {'Content-Type': 'application/json-rpc'} + payload = { + 'jsonrpc': '2.0', + 'method': method, + 'id': '1' + } + if params is None: + payload['params'] = {} + else: + payload['params'] = params + + if self.auth != '': + if (LooseVersion(self.zabbix_version) >= LooseVersion('6.4')): + headers['Authorization'] = 'Bearer ' + self.auth + else: + payload['auth'] = self.auth + + api_url = server_url + '/api_jsonrpc.php' + req = Request( + headers=headers, + timeout=timeout, + validate_certs=validate_certs + ) + try: + self.display.vvv("Sending request to {0}".format(api_url)) + response = req.post(api_url, data=json.dumps(payload)) + except ValueError: + raise AnsibleParserError("something went wrong with JSON loading") + except (URLError, HTTPError) as error: + raise AnsibleParserError(error) + + return response + + def get_version(self): + response = self.api_request( + 'apiinfo.version' + ) + res = json.load(response) + self.zabbix_version = res['result'] + + def logout_zabbix(self): + self.api_request( + 'user.logout', + [] + ) + + def login_zabbix(self): + auth_token = self.get_option('auth_token') + if auth_token: + self.auth = auth_token + return + + atexit.register(self.logout_zabbix) + + login_user = self.get_option('login_user') + login_password = self.get_option('login_password') + response = self.api_request( + 'user.login', + { + "username": login_user, + "password": login_password + } + ) + res = json.load(response) + self.auth = res["result"] def verify_file(self, path): valid = False @@ -354,9 +417,15 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): self.use_cache = self.get_option('cache') and cache self.update_cache = self.get_option('cache') and not cache + self.get_version() self.login_zabbix() zapi_query = self.get_option('host_zapi_query') - content = self._zapi.host.get(zapi_query) + response = self.api_request( + 'host.get', + zapi_query + ) + res = json.load(response) + content = res['result'] strict = self.get_option('strict') @@ -377,7 +446,16 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): # organize inventory by zabbix groups if self.get_option('add_zabbix_groups'): - content = self._zapi.host.get({'selectGroups': ['name']}) + + response = self.api_request( + 'host.get', + { + 'selectGroups': ['name'] + } + ) + res = json.load(response) + content = res['result'] + for record in content: host_name = record['host'] if len(record['groups']) >= 1: diff --git a/ansible_collections/community/zabbix/plugins/module_utils/api_request.py b/ansible_collections/community/zabbix/plugins/module_utils/api_request.py index a29f492de..18b588e17 100644 --- a/ansible_collections/community/zabbix/plugins/module_utils/api_request.py +++ b/ansible_collections/community/zabbix/plugins/module_utils/api_request.py @@ -12,7 +12,7 @@ __metaclass__ = type from uuid import uuid4 -from ansible.module_utils.urls import CertificateError +from ssl import CertificateError from ansible.module_utils.connection import ConnectionError from ansible.module_utils.connection import Connection from ansible.module_utils._text import to_text diff --git a/ansible_collections/community/zabbix/plugins/module_utils/base.py b/ansible_collections/community/zabbix/plugins/module_utils/base.py index 8858a02e1..a1c73291e 100644 --- a/ansible_collections/community/zabbix/plugins/module_utils/base.py +++ b/ansible_collections/community/zabbix/plugins/module_utils/base.py @@ -7,7 +7,6 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -from ansible_collections.community.zabbix.plugins.module_utils.wrappers import ZapiWrapper from ansible_collections.community.zabbix.plugins.module_utils.api_request import ZabbixApiRequest @@ -17,17 +16,5 @@ class ZabbixBase(object): """ def __init__(self, module, zbx=None, zapi_wrapper=None): self._module = module - - if module._socket_path is None: - # ansible_connection = local - if zapi_wrapper is None: - self._zapi_wrapper = ZapiWrapper(module, zbx) - else: - self._zapi_wrapper = zapi_wrapper - - self._zapi = self._zapi_wrapper._zapi - self._zbx_api_version = self._zapi_wrapper._zbx_api_version - else: - # ansible_connection = httpapi - self._zapi = ZabbixApiRequest(module) - self._zbx_api_version = self._zapi.api_version() + self._zapi = ZabbixApiRequest(module) + self._zbx_api_version = self._zapi.api_version() diff --git a/ansible_collections/community/zabbix/plugins/module_utils/helpers.py b/ansible_collections/community/zabbix/plugins/module_utils/helpers.py index 6c9c0fca5..87e0c0925 100644 --- a/ansible_collections/community/zabbix/plugins/module_utils/helpers.py +++ b/ansible_collections/community/zabbix/plugins/module_utils/helpers.py @@ -7,15 +7,6 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -from ansible.module_utils.basic import env_fallback - - -def require_creds_params(module): - if module._socket_path is None: - # ansible_connection = local - if ((not module.params.get('server_url', None)) or (not module.params.get('login_user', None)) or (not module.params.get('login_password', None))): - module.fail_json(msg="server_url, login_user, login_password are mandatory parameters when httpapi connection is not used") - def zabbix_common_argument_spec(): """ @@ -23,22 +14,6 @@ def zabbix_common_argument_spec(): The options are commonly used by most of Zabbix modules. """ return dict( - server_url=dict( - type='str', - required=False, - aliases=['url'], - fallback=(env_fallback, ['ZABBIX_SERVER']) - ), - login_user=dict( - type='str', required=False, - fallback=(env_fallback, ['ZABBIX_USERNAME']) - ), - login_password=dict( - type='str', - required=False, - no_log=True, - fallback=(env_fallback, ['ZABBIX_PASSWORD']) - ), http_login_user=dict( type='str', required=False, @@ -49,15 +24,7 @@ def zabbix_common_argument_spec(): required=False, default=None, no_log=True - ), - timeout=dict( - type='int' - ), - validate_certs=dict( - type='bool', - required=False, - fallback=(env_fallback, ['ZABBIX_VALIDATE_CERTS']) - ), + ) ) diff --git a/ansible_collections/community/zabbix/plugins/module_utils/wrappers.py b/ansible_collections/community/zabbix/plugins/module_utils/wrappers.py deleted file mode 100644 index a982108f8..000000000 --- a/ansible_collections/community/zabbix/plugins/module_utils/wrappers.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -from __future__ import absolute_import, division, print_function -__metaclass__ = type - -import atexit -import traceback - -from ansible.module_utils.basic import missing_required_lib - -try: - from zabbix_api import ZabbixAPI, Already_Exists, ZabbixAPIException - - HAS_ZABBIX_API = True - ZBX_IMP_ERR = Exception() -except ImportError: - ZBX_IMP_ERR = traceback.format_exc() - HAS_ZABBIX_API = False - - -class ZapiWrapper(object): - """ - A simple wrapper over the Zabbix API - """ - def __init__(self, module, zbx=None): - self._module = module - - if not HAS_ZABBIX_API: - module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) - - # check if zbx is already instantiated or not - if zbx is not None and isinstance(zbx, ZabbixAPI): - self._zapi = zbx - else: - server_url = module.params['server_url'] - - if module.params['validate_certs'] is None: - validate_certs = True - else: - validate_certs = module.params['validate_certs'] - - if module.params['timeout'] is None: - timeout = 10 - else: - timeout = module.params['timeout'] - - self._zapi = ZabbixAPI(server_url, timeout=timeout, validate_certs=validate_certs) - - self.login() - - self._zbx_api_version = self._zapi.api_version() - - def login(self): - # check if api already logged in - if not self._zapi.auth != '': - try: - login_user = self._module.params['login_user'] - login_password = self._module.params['login_password'] - self._zapi.login(login_user, login_password) - atexit.register(self._zapi.logout) - except Exception as e: - self._module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) - - -class ScreenItem(object): - @staticmethod - def create(zapi_wrapper, data, ignoreExists=False): - try: - zapi_wrapper._zapi.screenitem.create(data) - except Already_Exists as ex: - if not ignoreExists: - raise ex - - @staticmethod - def delete(zapi_wrapper, id_list=None): - try: - if id_list is None: - id_list = [] - zapi_wrapper._zapi.screenitem.delete(id_list) - except ZabbixAPIException as ex: - raise ex diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_action.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_action.py index 8e130de69..c0123ae1f 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_action.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_action.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: zabbix_action @@ -23,41 +23,51 @@ author: - Ruben Harutyunov (@K-DOT) requirements: - - "python >= 2.6" + - "python >= 3.9" options: name: + type: str description: - Name of the action required: true event_source: + type: str description: - Type of events that the action will handle. - Required when C(state=present). required: false - choices: ['trigger', 'discovery', 'auto_registration', 'internal'] + choices: ["trigger", "discovery", "auto_registration", "internal"] state: + type: str description: - State of the action. - On C(present), it will create an action if it does not exist or update the action if the associated data is different. - On C(absent), it will remove the action if it exists. - choices: ['present', 'absent'] - default: 'present' + choices: ["present", "absent"] + default: "present" status: + type: str description: - Status of the action. - choices: ['enabled', 'disabled'] - default: 'enabled' + choices: ["enabled", "disabled"] + default: "enabled" pause_in_maintenance: description: - Whether to pause escalation during maintenance periods or not. - Can be used when I(event_source=trigger). - type: 'bool' + type: "bool" + default: true + notify_if_canceled: + description: + - Weather to notify when escalation is canceled. + - Can be used when I(event_source=trigger). + type: "bool" default: true esc_period: + type: str description: - Default operation step duration. Must be greater than 60 seconds. - - Accepts only seconds in int for <= Zabbix 3.2 - Accepts seconds, time unit with suffix and user macro since => Zabbix 3.4 - Required when C(state=present). required: false @@ -68,112 +78,123 @@ options: - List of conditions to use for filtering results. - For more information about suboptions of this option please check out Zabbix API documentation U(https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_filter_condition) + default: [] suboptions: type: + type: str description: - Type (label) of the condition. - - C(application) is available only with <= Zabbix 5.2. - - 'Possible values when I(event_source=trigger):' - - ' - C(host_group)' - - ' - C(host)' - - ' - C(trigger)' - - ' - C(trigger_name)' - - ' - C(trigger_severity)' - - ' - C(time_period)' - - ' - C(host_template)' - - ' - C(application)' - - ' - C(maintenance_status) known in Zabbix 4.0 and above as "Problem is suppressed"' - - ' - C(event_tag)' - - ' - C(event_tag_value)' - - 'Possible values when I(event_source=discovery):' - - ' - C(host_IP)' - - ' - C(discovered_service_type)' - - ' - C(discovered_service_port)' - - ' - C(discovery_status)' - - ' - C(uptime_or_downtime_duration)' - - ' - C(received_value)' - - ' - C(discovery_rule)' - - ' - C(discovery_check)' - - ' - C(proxy)' - - ' - C(discovery_object)' - - 'Possible values when I(event_source=auto_registration):' - - ' - C(proxy)' - - ' - C(host_name)' - - ' - C(host_metadata)' - - 'Possible values when I(event_source=internal):' - - ' - C(host_group)' - - ' - C(host)' - - ' - C(host_template)' - - ' - C(application)' - - ' - C(event_type)' + - "Possible values when I(event_source=trigger):" + - " - C(host_group)" + - " - C(host)" + - " - C(trigger)" + - " - C(trigger_name)" + - " - C(trigger_severity)" + - " - C(time_period)" + - " - C(host_template)" + - " - C(maintenance_status) known in Zabbix 4.0 and above as 'Problem is suppressed'" + - " - C(event_tag)" + - " - C(event_tag_value)" + - "Possible values when I(event_source=discovery):" + - " - C(host_IP)" + - " - C(discovered_service_type)" + - " - C(discovered_service_port)" + - " - C(discovery_status)" + - " - C(uptime_or_downtime_duration)" + - " - C(received_value)" + - " - C(discovery_rule)" + - " - C(discovery_check)" + - " - C(proxy)" + - " - C(discovery_object)" + - "Possible values when I(event_source=auto_registration):" + - " - C(proxy)" + - " - C(host_name)" + - " - C(host_metadata)" + - "Possible values when I(event_source=internal):" + - " - C(host_group)" + - " - C(host)" + - " - C(host_template)" + - " - C(event_type)" + required: true value: + type: str description: - Value to compare with. - - 'When I(type=discovery_status), the choices are:' - - ' - C(up)' - - ' - C(down)' - - ' - C(discovered)' - - ' - C(lost)' - - 'When I(type=discovery_object), the choices are:' - - ' - C(host)' - - ' - C(service)' - - 'When I(type=event_type), the choices are:' - - ' - C(item in not supported state)' - - ' - C(item in normal state)' - - ' - C(LLD rule in not supported state)' - - ' - C(LLD rule in normal state)' - - ' - C(trigger in unknown state)' - - ' - C(trigger in normal state)' - - 'When I(type=trigger_severity), the choices are (case-insensitive):' - - ' - C(not classified)' - - ' - C(information)' - - ' - C(warning)' - - ' - C(average)' - - ' - C(high)' - - ' - C(disaster)' + - "When I(type=discovery_status), the choices are:" + - " - C(up)" + - " - C(down)" + - " - C(discovered)" + - " - C(lost)" + - "When I(type=discovery_object), the choices are:" + - " - C(host)" + - " - C(service)" + - "When I(type=event_type), the choices are:" + - " - C(item in not supported state)" + - " - C(item in normal state)" + - " - C(LLD rule in not supported state)" + - " - C(LLD rule in normal state)" + - " - C(trigger in unknown state)" + - " - C(trigger in normal state)" + - "When I(type=trigger_severity), the choices are (case-insensitive):" + - " - C(not classified)" + - " - C(information)" + - " - C(warning)" + - " - C(average)" + - " - C(high)" + - " - C(disaster)" - Irrespective of user-visible names being changed in Zabbix. Defaults to C(not classified) if omitted. - Besides the above options, this is usually either the name of the object or a string to compare with. value2: + type: str description: - Secondary value to compare with. - Required for trigger actions when condition I(type=event_tag_value). operator: + type: str description: - Condition operator. - When I(type) is set to C(time_period), the choices are C(in), C(not in). - - C(matches), C(does not match), C(Yes) and C(No) condition operators work only with >= Zabbix 4.0 - - When I(type) is set to C(maintenance_status), the choices are C(Yes) and C(No) for Zabbix >= 6.0 choices: - - C(equals) or C(=) - - C(does not equal) or C(<>) - - C(contains) or C(like) - - C(does not contain) or C(not like) - - C(in) - - C(is greater than or equals) or C(>=) - - C(is less than or equals) or C(<=) - - C(not in) - - C(matches) - - C(does not match) - - C(Yes) - - C(No) + - "equals" + - "=" + - "does not equal" + - "<>" + - "contains" + - "like" + - "does not contain" + - "not like" + - "in" + - "is greater than or equals" + - ">=" + - "is less than or equals" + - "<=" + - "not in" + - "matches" + - "does not match" + - "Yes" + - "No" + required: true formulaid: + type: str description: - Arbitrary unique ID that is used to reference the condition from a custom expression. - Can only contain upper-case letters. - Required for custom expression filters and ignored otherwise. eval_type: + type: str description: - Filter condition evaluation method. - Defaults to C(andor) if conditions are less then 2 or if I(formula) is not specified. - Defaults to C(custom_expression) when formula is specified. choices: - - 'andor' - - 'and' - - 'or' - - 'custom_expression' + - "andor" + - "and" + - "or" + - "custom_expression" formula: + type: str description: - User-defined expression to be used for evaluating conditions with a custom expression. - The expression must contain IDs that reference each condition by its formulaid. @@ -182,48 +203,21 @@ options: - Required when I(eval_type=custom_expression). - Use sequential IDs that start at "A". If non-sequential IDs are used, Zabbix re-indexes them. This makes each module run notice the difference in IDs and update the action. - default_message: - description: - - Problem message default text. - - With >= Zabbix 5.0 this field is removed from the API and is dropped silently by module. - - Works only with < Zabbix 5.0 - default_subject: - description: - - Problem message default subject. - - With >= Zabbix 5.0 this field is removed from the API and is dropped silently by module. - - Works only with < Zabbix 5.0 - recovery_default_message: - description: - - Recovery message text. - - With >= Zabbix 5.0 this field is removed from the API and is dropped silently by module. - - Works only with >= Zabbix 3.2 and < Zabbix 5.0 - recovery_default_subject: - description: - - Recovery message subject. - - With >= Zabbix 5.0 this field is removed from the API and is dropped silently by module. - - Works only with >= Zabbix 3.2 and < Zabbix 5.0 - acknowledge_default_message: - description: - - Update operation (known as "Acknowledge operation" before Zabbix 4.0) message text. - - With >= Zabbix 5.0 this field is removed from the API and is dropped silently by module. - - Works only with >= Zabbix 3.4 and < Zabbix 5.0 - acknowledge_default_subject: - description: - - Update operation (known as "Acknowledge operation" before Zabbix 4.0) message subject. - - With >= Zabbix 5.0 this field is removed from the API and is dropped silently by module. - - Works only with >= Zabbix 3.4 and < Zabbix 5.0 operations: type: list + elements: dict description: - List of action operations + default: [] suboptions: type: + type: str description: - Type of operation. - - 'Valid choices when setting type for I(recovery_operations) and I(acknowledge_operations):' - - ' - C(send_message)' - - ' - C(remote_command)' - - ' - C(notify_all_involved)' + - "Valid choices when setting type for I(recovery_operations) and I(acknowledge_operations):" + - " - C(send_message)" + - " - C(remote_command)" + - " - C(notify_all_involved)" - Choice C(notify_all_involved) only supported in I(recovery_operations) and I(acknowledge_operations). choices: - send_message @@ -238,47 +232,55 @@ options: - disable_host - set_host_inventory_mode - notify_all_involved + required: true esc_period: + type: str description: - Duration of an escalation step in seconds. - Must be greater than 60 seconds. - - Accepts only seconds in int for <= Zabbix 3.2 - - Accepts seconds, time unit with suffix and user macro since => Zabbix 3.4 + - Accepts seconds, time unit with suffix and user macro. - If set to 0 or 0s, the default action escalation period will be used. default: 0s esc_step_from: + type: int description: - Step to start escalation from. default: 1 esc_step_to: + type: int description: - Step to end escalation at. - Specify 0 for infinitely. default: 1 send_to_groups: type: list + elements: str description: - User groups to send messages to. send_to_users: type: list + elements: str description: - Users (usernames or aliases) to send messages to. - message: + op_message: + type: str description: - Operation message text. - - Will check the 'default message' and use the text from I(default_message) if this and I(default_subject) are not specified + - If I(op_message) and I(subject) not defined then "default message" from media type will be used subject: + type: str description: - Operation message subject. - - Will check the 'default message' and use the text from I(default_subject) if this and I(default_subject) are not specified + - If I(op_message) and I(subject) not defined then "default message" from media type will be used media_type: + type: str description: - Media type that will be used to send the message. - Can be used with I(type=send_message) or I(type=notify_all_involved) inside I(acknowledge_operations). - Set to C(all) for all media types - default: 'all' + default: "all" operation_condition: - type: 'str' + type: "str" description: - The action operation condition object defines a condition that must be met to perform the current operation. choices: @@ -286,15 +288,18 @@ options: - not_acknowledged host_groups: type: list + elements: str description: - List of host groups host should be added to. - Required when I(type=add_to_host_group) or I(type=remove_from_host_group). templates: type: list + elements: str description: - List of templates host should be linked to. - Required when I(type=link_to_template) or I(type=unlink_from_template). inventory: + type: str description: - Host inventory mode. - Required when I(type=set_host_inventory_mode). @@ -302,6 +307,7 @@ options: - manual - automatic command_type: + type: str description: - Type of operation command. - Required when I(type=remote_command). @@ -312,10 +318,12 @@ options: - telnet - global_script command: + type: str description: - Command to run. - Required when I(type=remote_command) and I(command_type!=global_script). execute_on: + type: str description: - Target on which the custom script operation command will be executed. - Required when I(type=remote_command) and I(command_type=custom_script). @@ -324,15 +332,20 @@ options: - server - proxy run_on_groups: + type: list + elements: str description: - Host groups to run remote commands on. - Required when I(type=remote_command) and I(run_on_hosts) is not set. run_on_hosts: + type: list + elements: str description: - Hosts to run remote commands on. - Required when I(type=remote_command) and I(run_on_groups) is not set. - If set to 0 the command will be run on the current host. ssh_auth_type: + type: str description: - Authentication method used for SSH commands. - Required when I(type=remote_command) and I(command_type=ssh). @@ -340,48 +353,292 @@ options: - password - public_key ssh_privatekey_file: + type: str description: - Name of the private key file used for SSH commands with public key authentication. - Required when I(ssh_auth_type=public_key). - Can be used when I(type=remote_command). ssh_publickey_file: + type: str description: - Name of the public key file used for SSH commands with public key authentication. - Required when I(ssh_auth_type=public_key). - Can be used when I(type=remote_command). username: + type: str description: - User name used for authentication. - Required when I(ssh_auth_type in [public_key, password]) or I(command_type=telnet). - Can be used when I(type=remote_command). password: + type: str description: - Password used for authentication. - Required when I(ssh_auth_type=password) or I(command_type=telnet). - Can be used when I(type=remote_command). port: + type: int description: - Port number used for authentication. - Can be used when I(command_type in [ssh, telnet]) and I(type=remote_command). script_name: + type: str description: - The name of script used for global script commands. - Required when I(command_type=global_script). - Can be used when I(type=remote_command). recovery_operations: type: list + elements: dict description: - List of recovery operations. - C(Suboptions) are the same as for I(operations). - - Works only with >= Zabbix 3.2 + default: [] + suboptions: + type: + type: str + description: + - Type of operation. + choices: + - send_message + - remote_command + - notify_all_involved + required: true + command_type: + type: str + required: false + description: + - Type of operation command. + choices: + - custom_script + - ipmi + - ssh + - telnet + - global_script + command: + type: str + required: false + description: + - Command to run. + execute_on: + type: str + required: false + description: + - Target on which the custom script operation command will be executed. + choices: + - agent + - server + - proxy + ssh_auth_type: + type: str + description: + - Authentication method used for SSH commands. + - Required when I(type=remote_command) and I(command_type=ssh). + choices: + - password + - public_key + ssh_privatekey_file: + type: str + description: + - Name of the private key file used for SSH commands with public key authentication. + - Required when I(ssh_auth_type=public_key). + - Can be used when I(type=remote_command). + ssh_publickey_file: + type: str + description: + - Name of the public key file used for SSH commands with public key authentication. + - Required when I(ssh_auth_type=public_key). + - Can be used when I(type=remote_command). + run_on_groups: + type: list + elements: str + description: + - Host groups to run remote commands on. + - Required when I(type=remote_command) and I(run_on_hosts) is not set. + run_on_hosts: + type: list + elements: str + description: + - Hosts to run remote commands on. + - Required when I(type=remote_command) and I(run_on_groups) is not set. + - If set to 0 the command will be run on the current host. + send_to_groups: + type: list + elements: str + description: + - User groups to send messages to. + send_to_users: + type: list + elements: str + description: + - Users (usernames or aliases) to send messages to. + media_type: + type: str + description: + - Media type that will be used to send the message. + - Can be used with I(type=send_message) or I(type=notify_all_involved) inside I(acknowledge_operations). + - Set to C(all) for all media types + default: "all" + op_message: + type: str + description: + - Operation message text. + - If I(op_message) and I(subject) not defined then "default message" from media type will be used + subject: + type: str + description: + - Operation message subject. + - If I(op_message) and I(subject) not defined then "default message" from media type will be used + username: + type: str + description: + - User name used for authentication. + - Required when I(ssh_auth_type in [public_key, password]) or I(command_type=telnet). + - Can be used when I(type=remote_command). + password: + type: str + description: + - Password used for authentication. + - Required when I(ssh_auth_type=password) or I(command_type=telnet). + - Can be used when I(type=remote_command). + port: + type: int + description: + - Port number used for authentication. + - Can be used when I(command_type in [ssh, telnet]) and I(type=remote_command). + script_name: + type: str + description: + - The name of script used for global script commands. + - Required when I(command_type=global_script). + - Can be used when I(type=remote_command). acknowledge_operations: type: list + elements: dict description: - List of acknowledge operations. - Action acknowledge operations are known as update operations since Zabbix 4.0. - C(Suboptions) are the same as for I(operations). - - Works only with >= Zabbix 3.4 + suboptions: + type: + type: str + description: + - Type of operation. + choices: + - send_message + - remote_command + - notify_all_involved + required: true + command_type: + type: str + description: + - Type of operation command. + required: false + choices: + - custom_script + - ipmi + - ssh + - telnet + - global_script + execute_on: + type: str + required: false + description: + - Target on which the custom script operation command will be executed. + choices: + - agent + - server + - proxy + command: + type: str + required: false + description: + - Command to run. + ssh_auth_type: + type: str + description: + - Authentication method used for SSH commands. + - Required when I(type=remote_command) and I(command_type=ssh). + choices: + - password + - public_key + ssh_privatekey_file: + type: str + description: + - Name of the private key file used for SSH commands with public key authentication. + - Required when I(ssh_auth_type=public_key). + - Can be used when I(type=remote_command). + ssh_publickey_file: + type: str + description: + - Name of the public key file used for SSH commands with public key authentication. + - Required when I(ssh_auth_type=public_key). + - Can be used when I(type=remote_command). + run_on_groups: + type: list + elements: str + description: + - Host groups to run remote commands on. + - Required when I(type=remote_command) and I(run_on_hosts) is not set. + run_on_hosts: + type: list + elements: str + description: + - Hosts to run remote commands on. + - Required when I(type=remote_command) and I(run_on_groups) is not set. + - If set to 0 the command will be run on the current host. + send_to_groups: + type: list + elements: str + description: + - User groups to send messages to. + send_to_users: + type: list + elements: str + description: + - Users (usernames or aliases) to send messages to. + media_type: + type: str + description: + - Media type that will be used to send the message. + - Can be used with I(type=send_message) or I(type=notify_all_involved) inside I(acknowledge_operations). + - Set to C(all) for all media types + default: "all" + op_message: + type: str + description: + - Operation message text. + - If I(op_message) and I(subject) not defined then "default message" from media type will be used + subject: + type: str + description: + - Operation message subject. + - If I(op_message) and I(subject) not defined then "default message" from media type will be used + username: + type: str + description: + - User name used for authentication. + - Required when I(ssh_auth_type in [public_key, password]) or I(command_type=telnet). + - Can be used when I(type=remote_command). + password: + type: str + description: + - Password used for authentication. + - Required when I(ssh_auth_type=password) or I(command_type=telnet). + - Can be used when I(type=remote_command). + port: + type: int + description: + - Port number used for authentication. + - Can be used when I(command_type in [ssh, telnet]) and I(type=remote_command). + script_name: + type: str + description: + - The name of script used for global script commands. + - Required when I(command_type=global_script). + - Can be used when I(type=remote_command). aliases: [ update_operations ] + default: [] pause_symptoms: type: bool description: @@ -390,26 +647,23 @@ options: - Works only with >= Zabbix 6.4 default: true -notes: - - Only Zabbix >= 3.0 is supported. - extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 # Trigger action with only one condition @@ -421,25 +675,25 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_action: name: "Send alerts to Admin" - event_source: 'trigger' + event_source: "trigger" state: present status: enabled esc_period: 60 conditions: - - type: 'trigger_severity' - operator: '>=' - value: 'Information' + - type: "trigger_severity" + operator: ">=" + value: "Information" operations: - type: send_message subject: "Something bad is happening" - message: "Come on, guys do something" - media_type: 'Email' + op_message: "Come on, guys do something" + media_type: "Email" send_to_users: - - 'Admin' + - "Admin" # Trigger action with multiple conditions and operations - name: Deploy trigger action @@ -450,31 +704,31 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_action: name: "Send alerts to Admin" - event_source: 'trigger' + event_source: "trigger" state: present status: enabled esc_period: 1m conditions: - - type: 'trigger_name' - operator: 'like' - value: 'Zabbix agent is unreachable' + - type: "trigger_name" + operator: "like" + value: "Zabbix agent is unreachable" formulaid: A - - type: 'trigger_severity' - operator: '>=' - value: 'disaster' + - type: "trigger_severity" + operator: ">=" + value: "disaster" formulaid: B formula: A or B operations: - type: send_message - media_type: 'Email' + media_type: "Email" send_to_users: - - 'Admin' + - "Admin" - type: remote_command - command: 'systemctl restart zabbix-agent' + command: "systemctl restart zabbix-agent" command_type: custom_script execute_on: server run_on_hosts: @@ -489,46 +743,46 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_action: name: "Send alerts to Admin" - event_source: 'trigger' + event_source: "trigger" state: present status: enabled esc_period: 1h conditions: - - type: 'trigger_severity' - operator: '>=' - value: 'Information' + - type: "trigger_severity" + operator: ">=" + value: "Information" operations: - type: send_message subject: "Something bad is happening" - message: "Come on, guys do something" - media_type: 'Email' + op_message: "Come on, guys do something" + media_type: "Email" send_to_users: - - 'Admin' + - "Admin" recovery_operations: - type: send_message subject: "Host is down" - message: "Come on, guys do something" - media_type: 'Email' + op_message: "Come on, guys do something" + media_type: "Email" send_to_users: - - 'Admin' + - "Admin" acknowledge_operations: - type: send_message - media_type: 'Email' + media_type: "Email" send_to_users: - - 'Admin' -''' + - "Admin" +""" -RETURN = ''' +RETURN = """ msg: description: The result of the operation returned: success type: str - sample: 'Action Deleted: Register webservers, ID: 0001' -''' + sample: "Action Deleted: Register webservers, ID: 0001" +""" from ansible.module_utils.basic import AnsibleModule @@ -558,16 +812,11 @@ class Zapi(ZabbixBase): _params = { "selectOperations": "extend", "selectRecoveryOperations": "extend", - "selectAcknowledgeOperations": "extend", + "selectUpdateOperations": "extend", "selectFilter": "extend", - 'filter': {'name': [name]} + "filter": {"name": [name]} } - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - _params['selectUpdateOperations'] = _params.pop('selectAcknowledgeOperations', 'extend') _action = self._zapi.action.get(_params) - if len(_action) > 0 and LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - _action[0]['recovery_operations'] = _action[0].pop('recoveryOperations', []) - _action[0]['acknowledge_operations'] = _action[0].pop('acknowledgeOperations', []) return _action except Exception as e: self._module.fail_json(msg="Failed to check if action '%s' exists: %s" % (name, e)) @@ -584,8 +833,8 @@ class Zapi(ZabbixBase): """ try: action_list = self._zapi.action.get({ - 'output': 'extend', - 'filter': {'name': [name]} + "output": "extend", + "filter": {"name": [name]} }) if len(action_list) < 1: self._module.fail_json(msg="Action not found: %s" % name) @@ -606,9 +855,9 @@ class Zapi(ZabbixBase): """ try: host_list = self._zapi.host.get({ - 'output': 'extend', - 'selectInventory': 'extend', - 'filter': {'host': [host_name]} + "output": "extend", + "selectInventory": "extend", + "filter": {"host": [host_name]} }) if len(host_list) < 1: self._module.fail_json(msg="Host not found: %s" % host_name) @@ -629,8 +878,8 @@ class Zapi(ZabbixBase): """ try: hostgroup_list = self._zapi.hostgroup.get({ - 'output': 'extend', - 'filter': {'name': [hostgroup_name]} + "output": "extend", + "filter": {"name": [hostgroup_name]} }) if len(hostgroup_list) < 1: self._module.fail_json(msg="Host group not found: %s" % hostgroup_name) @@ -651,8 +900,8 @@ class Zapi(ZabbixBase): """ try: template_list = self._zapi.template.get({ - 'output': 'extend', - 'filter': {'host': [template_name]} + "output": "extend", + "filter": {"host": [template_name]} }) if len(template_list) < 1: self._module.fail_json(msg="Template not found: %s" % template_name) @@ -673,8 +922,8 @@ class Zapi(ZabbixBase): """ try: trigger_list = self._zapi.trigger.get({ - 'output': 'extend', - 'filter': {'description': [trigger_name]} + "output": "extend", + "filter": {"description": [trigger_name]} }) if len(trigger_list) < 1: self._module.fail_json(msg="Trigger not found: %s" % trigger_name) @@ -695,8 +944,8 @@ class Zapi(ZabbixBase): """ try: discovery_rule_list = self._zapi.drule.get({ - 'output': 'extend', - 'filter': {'name': [discovery_rule_name]} + "output": "extend", + "filter": {"name": [discovery_rule_name]} }) if len(discovery_rule_list) < 1: self._module.fail_json(msg="Discovery rule not found: %s" % discovery_rule_name) @@ -716,38 +965,38 @@ class Zapi(ZabbixBase): """ try: - discovery_rule_name, dcheck_type = discovery_check_name.split(': ') + discovery_rule_name, dcheck_type = discovery_check_name.split(": ") dcheck_type_to_number = { - 'SSH': '0', - 'LDAP': '1', - 'SMTP': '2', - 'FTP': '3', - 'HTTP': '4', - 'POP': '5', - 'NNTP': '6', - 'IMAP': '7', - 'TCP': '8', - 'Zabbix agent': '9', - 'SNMPv1 agent': '10', - 'SNMPv2 agent': '11', - 'ICMP ping': '12', - 'SNMPv3 agent': '13', - 'HTTPS': '14', - 'Telnet': '15' + "SSH": "0", + "LDAP": "1", + "SMTP": "2", + "FTP": "3", + "HTTP": "4", + "POP": "5", + "NNTP": "6", + "IMAP": "7", + "TCP": "8", + "Zabbix agent": "9", + "SNMPv1 agent": "10", + "SNMPv2 agent": "11", + "ICMP ping": "12", + "SNMPv3 agent": "13", + "HTTPS": "14", + "Telnet": "15" } if dcheck_type not in dcheck_type_to_number: self._module.fail_json(msg="Discovery check type: %s does not exist" % dcheck_type) discovery_rule_list = self._zapi.drule.get({ - 'output': ['dchecks'], - 'filter': {'name': [discovery_rule_name]}, - 'selectDChecks': 'extend' + "output": ["dchecks"], + "filter": {"name": [discovery_rule_name]}, + "selectDChecks": "extend" }) if len(discovery_rule_list) < 1: self._module.fail_json(msg="Discovery check not found: %s" % discovery_check_name) - for dcheck in discovery_rule_list[0]['dchecks']: - if dcheck_type_to_number[dcheck_type] == dcheck['type']: + for dcheck in discovery_rule_list[0]["dchecks"]: + if dcheck_type_to_number[dcheck_type] == dcheck["type"]: return dcheck self._module.fail_json(msg="Discovery check not found: %s" % discovery_check_name) except Exception as e: @@ -765,8 +1014,8 @@ class Zapi(ZabbixBase): """ try: proxy_list = self._zapi.proxy.get({ - 'output': 'extend', - 'filter': {'host': [proxy_name]} + "output": "extend", + "filter": {"host": [proxy_name]} }) if len(proxy_list) < 1: self._module.fail_json(msg="Proxy not found: %s" % proxy_name) @@ -785,22 +1034,19 @@ class Zapi(ZabbixBase): mediatype matching mediatype name """ - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.4'): - filter = {'name': [mediatype_name]} - else: - filter = {'description': [mediatype_name]} + filter = {"name": [mediatype_name]} try: - if str(mediatype_name).lower() == 'all': - return '0' + if str(mediatype_name).lower() == "all": + return "0" mediatype_list = self._zapi.mediatype.get({ - 'output': 'extend', - 'filter': filter + "output": "extend", + "filter": filter }) if len(mediatype_list) < 1: self._module.fail_json(msg="Media type not found: %s" % mediatype_name) else: - return mediatype_list[0]['mediatypeid'] + return mediatype_list[0]["mediatypeid"] except Exception as e: self._module.fail_json(msg="Failed to get mediatype '%s': %s" % (mediatype_name, e)) @@ -815,13 +1061,10 @@ class Zapi(ZabbixBase): """ try: - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.4'): - filter = {'username': [user_name]} - else: - filter = {'alias': [user_name]} + filter = {"username": [user_name]} user_list = self._zapi.user.get({ - 'output': 'extend', - 'filter': filter, + "output": "extend", + "filter": filter, }) if len(user_list) < 1: self._module.fail_json(msg="User not found: %s" % user_name) @@ -842,8 +1085,8 @@ class Zapi(ZabbixBase): """ try: usergroup_list = self._zapi.usergroup.get({ - 'output': 'extend', - 'filter': {'name': [usergroup_name]} + "output": "extend", + "filter": {"name": [usergroup_name]} }) if len(usergroup_list) < 1: self._module.fail_json(msg="User group not found: %s" % usergroup_name) @@ -867,8 +1110,8 @@ class Zapi(ZabbixBase): if script_name is None: return {} script_list = self._zapi.script.get({ - 'output': 'extend', - 'filter': {'name': [script_name]} + "output": "extend", + "filter": {"name": [script_name]} }) if len(script_list) < 1: self._module.fail_json(msg="Script not found: %s" % script_name) @@ -894,72 +1137,50 @@ class Action(Zapi): """ _params = { - 'name': kwargs['name'], - 'eventsource': zabbix_utils.helper_to_numeric_value([ - 'trigger', - 'discovery', - 'auto_registration', - 'internal'], kwargs['event_source']), - 'esc_period': kwargs.get('esc_period'), - 'filter': kwargs['conditions'], - 'def_longdata': kwargs['default_message'], - 'def_shortdata': kwargs['default_subject'], - 'r_longdata': kwargs['recovery_default_message'], - 'r_shortdata': kwargs['recovery_default_subject'], - 'ack_longdata': kwargs['acknowledge_default_message'], - 'ack_shortdata': kwargs['acknowledge_default_subject'], - 'operations': kwargs['operations'], - 'recovery_operations': kwargs.get('recovery_operations'), - 'acknowledge_operations': kwargs.get('acknowledge_operations'), - 'status': zabbix_utils.helper_to_numeric_value([ - 'enabled', - 'disabled'], kwargs['status']) + "name": kwargs["name"], + "eventsource": zabbix_utils.helper_to_numeric_value([ + "trigger", + "discovery", + "auto_registration", + "internal"], kwargs["event_source"]), + "esc_period": kwargs.get("esc_period"), + "filter": kwargs["conditions"], + "operations": kwargs["operations"], + "recovery_operations": kwargs.get("recovery_operations"), + "acknowledge_operations": kwargs.get("acknowledge_operations"), + "status": zabbix_utils.helper_to_numeric_value([ + "enabled", + "disabled"], kwargs["status"]) } - if kwargs['event_source'] == 'trigger': - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.0'): - _params['pause_suppressed'] = '1' if kwargs['pause_in_maintenance'] else '0' - else: - _params['maintenance_mode'] = '1' if kwargs['pause_in_maintenance'] else '0' - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.4'): - _params['pause_symptoms'] = '1' if kwargs['pause_symptoms'] else '0' - - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0'): - # remove some fields regarding - # https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object - _params.pop('def_longdata', None) - _params.pop('def_shortdata', None) - _params.pop('r_longdata', None) - _params.pop('r_shortdata', None) - - if (LooseVersion(self._zbx_api_version) < LooseVersion('3.4') - or LooseVersion(self._zbx_api_version) >= LooseVersion('5.0')): - _params.pop('ack_longdata', None) - _params.pop('ack_shortdata', None) - - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - _params['update_operations'] = kwargs.get('update_operations') - if 'update_operations' in _params and not isinstance(_params.get('update_operations', None), type(None)): - _params.pop('acknowledge_operations', None) - elif isinstance(_params.get('acknowledge_operations', None), list): - _params['update_operations'] = _params.pop('acknowledge_operations', []) - else: - _params['update_operations'] = [] - _params.pop('acknowledge_operations', None) + if kwargs["event_source"] == "trigger": + _params["pause_suppressed"] = "1" if kwargs["pause_in_maintenance"] else "0" + if LooseVersion(self._zbx_api_version) >= LooseVersion("6.4"): + _params["pause_symptoms"] = "1" if kwargs["pause_symptoms"] else "0" + _params["notify_if_canceled"] = "1" if kwargs["notify_if_canceled"] else "0" + + _params["update_operations"] = kwargs.get("update_operations") + if "update_operations" in _params and not isinstance(_params.get("update_operations", None), type(None)): + _params.pop("acknowledge_operations", None) + elif isinstance(_params.get("acknowledge_operations", None), list): + _params["update_operations"] = _params.pop("acknowledge_operations", []) + else: + _params["update_operations"] = [] + _params.pop("acknowledge_operations", None) - if 'esc_period' in _params and isinstance(_params.get('esc_period', None), type(None)): - _params.pop('esc_period') + if "esc_period" in _params and isinstance(_params.get("esc_period", None), type(None)): + _params.pop("esc_period") - if 'recovery_operations' in _params: - if isinstance(_params.get('recovery_operations', None), type(None)) or len(_params.get('recovery_operations', [])) == 0: - _params.pop('recovery_operations') + if "recovery_operations" in _params: + if isinstance(_params.get("recovery_operations", None), type(None)) or len(_params.get("recovery_operations", [])) == 0: + _params.pop("recovery_operations") - if 'update_operations' in _params: - if isinstance(_params.get('update_operations', None), type(None)) or len(_params.get('update_operations', [])) == 0: - _params.pop('update_operations') + if "update_operations" in _params: + if isinstance(_params.get("update_operations", None), type(None)) or len(_params.get("update_operations", [])) == 0: + _params.pop("update_operations") - if _params['eventsource'] not in [0, 3]: - _params.pop('esc_period') + if _params["eventsource"] not in [0, 3]: + _params.pop("esc_period") return _params @@ -972,7 +1193,7 @@ class Action(Zapi): Returns: dict: dictionary of differences """ - existing_action = zabbix_utils.helper_convert_unicode_to_str(self.check_if_action_exists(kwargs['name'])[0]) + existing_action = zabbix_utils.helper_convert_unicode_to_str(self.check_if_action_exists(kwargs["name"])[0]) parameters = zabbix_utils.helper_convert_unicode_to_str(self._construct_parameters(**kwargs)) change_parameters = {} _diff = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(parameters, existing_action, change_parameters)) @@ -990,10 +1211,10 @@ class Action(Zapi): try: if self._module.check_mode: self._module.exit_json(msg="Action would be updated if check mode was not specified: %s" % kwargs, changed=True) - kwargs['actionid'] = kwargs.pop('action_id') + kwargs["actionid"] = kwargs.pop("action_id") return self._zapi.action.update(kwargs) except Exception as e: - self._module.fail_json(msg="Failed to update action '%s': %s" % (kwargs['actionid'], e)) + self._module.fail_json(msg="Failed to update action '%s': %s" % (kwargs["actionid"], e)) def add_action(self, **kwargs): """Add action. @@ -1009,9 +1230,9 @@ class Action(Zapi): self._module.exit_json(msg="Action would be added if check mode was not specified", changed=True) parameters = self._construct_parameters(**kwargs) action_list = self._zapi.action.create(parameters) - return action_list['actionids'][0] + return action_list["actionids"][0] except Exception as e: - self._module.fail_json(msg="Failed to create action '%s': %s" % (kwargs['name'], e)) + self._module.fail_json(msg="Failed to create action '%s': %s" % (kwargs["name"], e)) def delete_action(self, action_id): """Delete action. @@ -1052,10 +1273,11 @@ class Operations(Zapi): "unlink_from_template", "enable_host", "disable_host", - "set_host_inventory_mode"], operation['type'] + "set_host_inventory_mode"], + operation["type"] ) except Exception: - self._module.fail_json(msg="Unsupported value '%s' for operation type." % operation['type']) + self._module.fail_json(msg="Unsupported value '%s' for operation type." % operation["type"]) def _construct_opmessage(self, operation): """Construct operation message. @@ -1068,12 +1290,12 @@ class Operations(Zapi): """ try: return { - 'default_msg': '0' if operation.get('message') is not None or operation.get('subject') is not None else '1', - 'mediatypeid': self._zapi_wrapper.get_mediatype_by_mediatype_name( - operation.get('media_type') - ) if operation.get('media_type') is not None else '0', - 'message': operation.get('message'), - 'subject': operation.get('subject'), + "default_msg": "0" if operation.get("op_message") is not None or operation.get("subject") is not None else "1", + "mediatypeid": self._zapi_wrapper.get_mediatype_by_mediatype_name( + operation.get("media_type") + ) if operation.get("media_type") is not None else "0", + "message": operation.get("op_message"), + "subject": operation.get("subject"), } except Exception as e: self._module.fail_json(msg="Failed to construct operation message. The error was: %s" % e) @@ -1087,11 +1309,11 @@ class Operations(Zapi): Returns: list: constructed operation message user or None if operation not found """ - if operation.get('send_to_users') is None: + if operation.get("send_to_users") is None: return None return [{ - 'userid': self._zapi_wrapper.get_user_by_user_name(_user)['userid'] - } for _user in operation.get('send_to_users')] + "userid": self._zapi_wrapper.get_user_by_user_name(_user)["userid"] + } for _user in operation.get("send_to_users")] def _construct_opmessage_grp(self, operation): """Construct operation message group. @@ -1102,11 +1324,11 @@ class Operations(Zapi): Returns: list: constructed operation message group or None if operation not found """ - if operation.get('send_to_groups') is None: + if operation.get("send_to_groups") is None: return None return [{ - 'usrgrpid': self._zapi_wrapper.get_usergroup_by_usergroup_name(_group)['usrgrpid'] - } for _group in operation.get('send_to_groups')] + "usrgrpid": self._zapi_wrapper.get_usergroup_by_usergroup_name(_group)["usrgrpid"] + } for _group in operation.get("send_to_groups")] def _construct_opcommand(self, operation): """Construct operation command. @@ -1118,39 +1340,11 @@ class Operations(Zapi): list: constructed operation command """ try: - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - opcommand = { - 'type': zabbix_utils.helper_to_numeric_value([ - 'custom_script', - 'ipmi', - 'ssh', - 'telnet', - 'global_script'], operation.get('command_type', 'custom_script')), - 'command': operation.get('command'), - 'execute_on': zabbix_utils.helper_to_numeric_value([ - 'agent', - 'server', - 'proxy'], operation.get('execute_on', 'server')), - 'scriptid': self._zapi_wrapper.get_script_by_script_name( - operation.get('script_name') - ).get('scriptid'), - 'authtype': zabbix_utils.helper_to_numeric_value([ - 'password', - 'public_key' - ], operation.get('ssh_auth_type')), - 'privatekey': operation.get('ssh_privatekey_file'), - 'publickey': operation.get('ssh_publickey_file'), - 'username': operation.get('username'), - 'password': operation.get('password'), - 'port': operation.get('port') - } - else: - # In 6.0 opcommand is an opbject with just one key 'scriptid' - opcommand = { - 'scriptid': self._zapi_wrapper.get_script_by_script_name( - operation.get('script_name') - ).get('scriptid') - } + opcommand = { + "scriptid": self._zapi_wrapper.get_script_by_script_name( + operation.get("script_name") + ).get("scriptid") + } return opcommand @@ -1166,11 +1360,11 @@ class Operations(Zapi): Returns: list: constructed operation command host """ - if operation.get('run_on_hosts') is None: + if operation.get("run_on_hosts") is None: return None return [{ - 'hostid': self._zapi_wrapper.get_host_by_host_name(_host)['hostid'] - } if str(_host) != '0' else {'hostid': '0'} for _host in operation.get('run_on_hosts')] + "hostid": self._zapi_wrapper.get_host_by_host_name(_host)["hostid"] + } if str(_host) != "0" else {"hostid": "0"} for _host in operation.get("run_on_hosts")] def _construct_opcommand_grp(self, operation): """Construct operation command group. @@ -1181,11 +1375,11 @@ class Operations(Zapi): Returns: list: constructed operation command group """ - if operation.get('run_on_groups') is None: + if operation.get("run_on_groups") is None: return None return [{ - 'groupid': self._zapi_wrapper.get_hostgroup_by_hostgroup_name(_group)['groupid'] - } for _group in operation.get('run_on_groups')] + "groupid": self._zapi_wrapper.get_hostgroup_by_hostgroup_name(_group)["groupid"] + } for _group in operation.get("run_on_groups")] def _construct_opgroup(self, operation): """Construct operation group. @@ -1197,8 +1391,8 @@ class Operations(Zapi): list: constructed operation group """ return [{ - 'groupid': self._zapi_wrapper.get_hostgroup_by_hostgroup_name(_group)['groupid'] - } for _group in operation.get('host_groups', [])] + "groupid": self._zapi_wrapper.get_hostgroup_by_hostgroup_name(_group)["groupid"] + } for _group in operation.get("host_groups", [])] def _construct_optemplate(self, operation): """Construct operation template. @@ -1210,8 +1404,8 @@ class Operations(Zapi): list: constructed operation template """ return [{ - 'templateid': self._zapi_wrapper.get_template_by_template_name(_template)['templateid'] - } for _template in operation.get('templates', [])] + "templateid": self._zapi_wrapper.get_template_by_template_name(_template)["templateid"] + } for _template in operation.get("templates", [])] def _construct_opinventory(self, operation): """Construct operation inventory. @@ -1223,10 +1417,10 @@ class Operations(Zapi): dict: constructed operation inventory """ return { - 'inventory_mode': zabbix_utils.helper_to_numeric_value([ - 'manual', - 'automatic' - ], operation.get('inventory')) + "inventory_mode": zabbix_utils.helper_to_numeric_value([ + "manual", + "automatic" + ], operation.get("inventory")) } def _construct_opconditions(self, operation): @@ -1238,16 +1432,16 @@ class Operations(Zapi): Returns: list: constructed operation conditions """ - _opcond = operation.get('operation_condition') + _opcond = operation.get("operation_condition") if _opcond is not None: - if _opcond == 'acknowledged': - _value = '1' - elif _opcond == 'not_acknowledged': - _value = '0' + if _opcond == "acknowledged": + _value = "1" + elif _opcond == "not_acknowledged": + _value = "0" return [{ - 'conditiontype': '14', - 'operator': '0', - 'value': _value + "conditiontype": "14", + "operator": "0", + "value": _value }] return [] @@ -1264,49 +1458,49 @@ class Operations(Zapi): for op in operations: operation_type = self._construct_operationtype(op) constructed_operation = { - 'operationtype': operation_type, - 'esc_period': op.get('esc_period'), - 'esc_step_from': op.get('esc_step_from'), - 'esc_step_to': op.get('esc_step_to') + "operationtype": operation_type, + "esc_period": op.get("esc_period"), + "esc_step_from": op.get("esc_step_from"), + "esc_step_to": op.get("esc_step_to") } # Send Message type - if constructed_operation['operationtype'] == 0: - constructed_operation['opmessage'] = self._construct_opmessage(op) - constructed_operation['opmessage_usr'] = self._construct_opmessage_usr(op) - constructed_operation['opmessage_grp'] = self._construct_opmessage_grp(op) - if event_source == 'trigger': - # opconditions valid only for 'trigger' action - constructed_operation['opconditions'] = self._construct_opconditions(op) + if constructed_operation["operationtype"] == 0: + constructed_operation["opmessage"] = self._construct_opmessage(op) + constructed_operation["opmessage_usr"] = self._construct_opmessage_usr(op) + constructed_operation["opmessage_grp"] = self._construct_opmessage_grp(op) + if event_source == "trigger": + # opconditions valid only for "trigger" action + constructed_operation["opconditions"] = self._construct_opconditions(op) # Send Command type - if constructed_operation['operationtype'] == 1: - constructed_operation['opcommand'] = self._construct_opcommand(op) - constructed_operation['opcommand_hst'] = self._construct_opcommand_hst(op) - constructed_operation['opcommand_grp'] = self._construct_opcommand_grp(op) - if event_source == 'trigger': - # opconditions valid only for 'trigger' action - constructed_operation['opconditions'] = self._construct_opconditions(op) + if constructed_operation["operationtype"] == 1: + constructed_operation["opcommand"] = self._construct_opcommand(op) + constructed_operation["opcommand_hst"] = self._construct_opcommand_hst(op) + constructed_operation["opcommand_grp"] = self._construct_opcommand_grp(op) + if event_source == "trigger": + # opconditions valid only for "trigger" action + constructed_operation["opconditions"] = self._construct_opconditions(op) # Add to/Remove from host group - if constructed_operation['operationtype'] in (4, 5): - constructed_operation['opgroup'] = self._construct_opgroup(op) + if constructed_operation["operationtype"] in (4, 5): + constructed_operation["opgroup"] = self._construct_opgroup(op) # Link/Unlink template - if constructed_operation['operationtype'] in (6, 7): - constructed_operation['optemplate'] = self._construct_optemplate(op) + if constructed_operation["operationtype"] in (6, 7): + constructed_operation["optemplate"] = self._construct_optemplate(op) # Set inventory mode - if constructed_operation['operationtype'] == 10: - constructed_operation['opinventory'] = self._construct_opinventory(op) + if constructed_operation["operationtype"] == 10: + constructed_operation["opinventory"] = self._construct_opinventory(op) # Remove escalation params when for event sources where they are not applicable - if event_source in ['trigger', 'internal']: - if isinstance(constructed_operation.get('esc_period'), type(None)): - constructed_operation['esc_period'] = 0 + if event_source in ["trigger", "internal"]: + if isinstance(constructed_operation.get("esc_period"), type(None)): + constructed_operation["esc_period"] = 0 else: - constructed_operation.pop('esc_period') - constructed_operation.pop('esc_step_from') - constructed_operation.pop('esc_step_to') + constructed_operation.pop("esc_period") + constructed_operation.pop("esc_step_from") + constructed_operation.pop("esc_step_to") constructed_data.append(constructed_operation) @@ -1317,6 +1511,7 @@ class RecoveryOperations(Operations): """ Restructures the user defined recovery operations data to fit the Zabbix API requirements """ + def _construct_operationtype(self, operation): """Construct operation type. @@ -1339,10 +1534,10 @@ class RecoveryOperations(Operations): None, None, None, - "notify_all_involved"], operation['type'] + "notify_all_involved"], operation["type"] ) except Exception: - self._module.fail_json(msg="Unsupported value '%s' for recovery operation type." % operation['type']) + self._module.fail_json(msg="Unsupported value '%s' for recovery operation type." % operation["type"]) def construct_the_data(self, operations): """Construct the recovery operations data using helper methods. @@ -1357,25 +1552,24 @@ class RecoveryOperations(Operations): for op in operations: operation_type = self._construct_operationtype(op) constructed_operation = { - 'operationtype': operation_type, + "operationtype": operation_type, } # Send Message type - if constructed_operation['operationtype'] == 0: - constructed_operation['opmessage'] = self._construct_opmessage(op) - constructed_operation['opmessage_usr'] = self._construct_opmessage_usr(op) - constructed_operation['opmessage_grp'] = self._construct_opmessage_grp(op) + if constructed_operation["operationtype"] == 0: + constructed_operation["opmessage"] = self._construct_opmessage(op) + constructed_operation["opmessage_usr"] = self._construct_opmessage_usr(op) + constructed_operation["opmessage_grp"] = self._construct_opmessage_grp(op) - if constructed_operation['operationtype'] == 11: - constructed_operation['opmessage'] = self._construct_opmessage(op) - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - constructed_operation['opmessage'].pop('mediatypeid') + if constructed_operation["operationtype"] == 11: + constructed_operation["opmessage"] = self._construct_opmessage(op) + constructed_operation["opmessage"].pop("mediatypeid") # Send Command type - if constructed_operation['operationtype'] == 1: - constructed_operation['opcommand'] = self._construct_opcommand(op) - constructed_operation['opcommand_hst'] = self._construct_opcommand_hst(op) - constructed_operation['opcommand_grp'] = self._construct_opcommand_grp(op) + if constructed_operation["operationtype"] == 1: + constructed_operation["opcommand"] = self._construct_opcommand(op) + constructed_operation["opcommand_hst"] = self._construct_opcommand_hst(op) + constructed_operation["opcommand_grp"] = self._construct_opcommand_grp(op) constructed_data.append(constructed_operation) @@ -1386,6 +1580,7 @@ class AcknowledgeOperations(Operations): """ Restructures the user defined acknowledge operations data to fit the Zabbix API requirements """ + def _construct_operationtype(self, operation): """Construct operation type. @@ -1409,10 +1604,10 @@ class AcknowledgeOperations(Operations): None, None, None, - "notify_all_involved"], operation['type'] + "notify_all_involved"], operation["type"] ) except Exception: - self._module.fail_json(msg="Unsupported value '%s' for acknowledge operation type." % operation['type']) + self._module.fail_json(msg="Unsupported value '%s' for acknowledge operation type." % operation["type"]) def construct_the_data(self, operations): """Construct the acknowledge operations data using helper methods. @@ -1427,25 +1622,24 @@ class AcknowledgeOperations(Operations): for op in operations: operation_type = self._construct_operationtype(op) constructed_operation = { - 'operationtype': operation_type, + "operationtype": operation_type, } # Send Message type - if constructed_operation['operationtype'] == 0: - constructed_operation['opmessage'] = self._construct_opmessage(op) - constructed_operation['opmessage_usr'] = self._construct_opmessage_usr(op) - constructed_operation['opmessage_grp'] = self._construct_opmessage_grp(op) + if constructed_operation["operationtype"] == 0: + constructed_operation["opmessage"] = self._construct_opmessage(op) + constructed_operation["opmessage_usr"] = self._construct_opmessage_usr(op) + constructed_operation["opmessage_grp"] = self._construct_opmessage_grp(op) - if constructed_operation['operationtype'] == 12: - constructed_operation['opmessage'] = self._construct_opmessage(op) - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - constructed_operation['opmessage'].pop('mediatypeid') + if constructed_operation["operationtype"] == 12: + constructed_operation["opmessage"] = self._construct_opmessage(op) + constructed_operation["opmessage"].pop("mediatypeid") # Send Command type - if constructed_operation['operationtype'] == 1: - constructed_operation['opcommand'] = self._construct_opcommand(op) - constructed_operation['opcommand_hst'] = self._construct_opcommand_hst(op) - constructed_operation['opcommand_grp'] = self._construct_opcommand_grp(op) + if constructed_operation["operationtype"] == 1: + constructed_operation["opcommand"] = self._construct_opcommand(op) + constructed_operation["opcommand_hst"] = self._construct_opcommand_hst(op) + constructed_operation["opcommand_grp"] = self._construct_opcommand_grp(op) constructed_data.append(constructed_operation) @@ -1465,40 +1659,40 @@ class Filter(Zapi): """ if len(_conditions) <= 1: return { - 'evaltype': '0', - 'formula': None + "evaltype": "0", + "formula": None } - if _eval_type == 'andor': + if _eval_type == "andor": return { - 'evaltype': '0', - 'formula': None + "evaltype": "0", + "formula": None } - if _eval_type == 'and': + if _eval_type == "and": return { - 'evaltype': '1', - 'formula': None + "evaltype": "1", + "formula": None } - if _eval_type == 'or': + if _eval_type == "or": return { - 'evaltype': '2', - 'formula': None + "evaltype": "2", + "formula": None } - if _eval_type == 'custom_expression': + if _eval_type == "custom_expression": if _formula is not None: return { - 'evaltype': '3', - 'formula': _formula + "evaltype": "3", + "formula": _formula } else: self._module.fail_json(msg="'formula' is required when 'eval_type' is set to 'custom_expression'") if _formula is not None: return { - 'evaltype': '3', - 'formula': _formula + "evaltype": "3", + "formula": _formula } return { - 'evaltype': '0', - 'formula': None + "evaltype": "0", + "formula": None } def _construct_conditiontype(self, _condition): @@ -1510,11 +1704,6 @@ class Filter(Zapi): Returns: str: constructed condition type data """ - # application is disabled is disabled for condition type since 5.4 version. - if (LooseVersion(self._zbx_api_version) >= LooseVersion('5.4') - and _condition['type'] == 'application'): - self._module.fail_json(msg="'%s' is disabled for condition type since 5.4 version." % _condition['type']) - try: return zabbix_utils.helper_to_numeric_value([ "host_group", @@ -1532,7 +1721,7 @@ class Filter(Zapi): "received_value", "host_template", None, - "application", + None, "maintenance_status", None, "discovery_rule", @@ -1543,10 +1732,10 @@ class Filter(Zapi): "event_type", "host_metadata", "event_tag", - "event_tag_value"], _condition['type'] + "event_tag_value"], _condition["type"] ) except Exception: - self._module.fail_json(msg="Unsupported value '%s' for condition type." % _condition['type']) + self._module.fail_json(msg="Unsupported value '%s' for condition type." % _condition["type"]) def _construct_operator(self, _condition): """Construct operator @@ -1570,10 +1759,10 @@ class Filter(Zapi): "matches", "does not match", "Yes", - "No"], _condition['operator'] + "No"], _condition["operator"] ) except Exception: - self._module.fail_json(msg="Unsupported value '%s' for operator." % _condition['operator']) + self._module.fail_json(msg="Unsupported value '%s' for operator." % _condition["operator"]) def _construct_value(self, conditiontype, value): """Construct operator @@ -1588,13 +1777,13 @@ class Filter(Zapi): try: # Host group if conditiontype == 0: - return self._zapi_wrapper.get_hostgroup_by_hostgroup_name(value)['groupid'] + return self._zapi_wrapper.get_hostgroup_by_hostgroup_name(value)["groupid"] # Host if conditiontype == 1: - return self._zapi_wrapper.get_host_by_host_name(value)['hostid'] + return self._zapi_wrapper.get_host_by_host_name(value)["hostid"] # Trigger if conditiontype == 2: - return self._zapi_wrapper.get_trigger_by_trigger_name(value)['triggerid'] + return self._zapi_wrapper.get_trigger_by_trigger_name(value)["triggerid"] # Trigger name: return as is # Trigger severity if conditiontype == 4: @@ -1645,20 +1834,19 @@ class Filter(Zapi): "lost"], value ) if conditiontype == 13: - return self._zapi_wrapper.get_template_by_template_name(value)['templateid'] - if LooseVersion(self._zapi_wrapper._zbx_api_version) >= LooseVersion('6.0'): - # maintenance_status - if conditiontype == 16: - return zabbix_utils.helper_to_numeric_value([ - "Yes", - "No"], value - ) + return self._zapi_wrapper.get_template_by_template_name(value)["templateid"] + # maintenance_status + if conditiontype == 16: + return zabbix_utils.helper_to_numeric_value([ + "Yes", + "No"], value + ) if conditiontype == 18: - return self._zapi_wrapper.get_discovery_rule_by_discovery_rule_name(value)['druleid'] + return self._zapi_wrapper.get_discovery_rule_by_discovery_rule_name(value)["druleid"] if conditiontype == 19: - return self._zapi_wrapper.get_discovery_check_by_discovery_check_name(value)['dcheckid'] + return self._zapi_wrapper.get_discovery_check_by_discovery_check_name(value)["dcheckid"] if conditiontype == 20: - return self._zapi_wrapper.get_proxy_by_proxy_name(value)['proxyid'] + return self._zapi_wrapper.get_proxy_by_proxy_name(value)["proxyid"] if conditiontype == 21: return zabbix_utils.helper_to_numeric_value([ "pchldrfor0", @@ -1697,10 +1885,10 @@ class Filter(Zapi): if _conditions is None: return None constructed_data = {} - constructed_data['conditions'] = [] + constructed_data["conditions"] = [] for cond in _conditions: condition_type = self._construct_conditiontype(cond) - constructed_data['conditions'].append({ + constructed_data["conditions"].append({ "conditiontype": condition_type, "value": self._construct_value(condition_type, cond.get("value")), "value2": cond.get("value2"), @@ -1710,10 +1898,10 @@ class Filter(Zapi): _constructed_evaltype = self._construct_evaltype( _eval_type, _formula, - constructed_data['conditions'] + constructed_data["conditions"] ) - constructed_data['evaltype'] = _constructed_evaltype['evaltype'] - constructed_data['formula'] = _constructed_evaltype['formula'] + constructed_data["evaltype"] = _constructed_evaltype["evaltype"] + constructed_data["formula"] = _constructed_evaltype["formula"] return zabbix_utils.helper_cleanup_data(constructed_data) @@ -1723,300 +1911,308 @@ def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - esc_period=dict(type='str', required=False), - name=dict(type='str', required=True), - event_source=dict(type='str', required=False, choices=['trigger', 'discovery', 'auto_registration', 'internal']), - state=dict(type='str', required=False, default='present', choices=['present', 'absent']), - status=dict(type='str', required=False, default='enabled', choices=['enabled', 'disabled']), - pause_in_maintenance=dict(type='bool', required=False, default=True), - default_message=dict(type='str', required=False, default=''), - default_subject=dict(type='str', required=False, default=''), - recovery_default_message=dict(type='str', required=False, default=''), - recovery_default_subject=dict(type='str', required=False, default=''), - acknowledge_default_message=dict(type='str', required=False, default=''), - acknowledge_default_subject=dict(type='str', required=False, default=''), + esc_period=dict(type="str", required=False), + name=dict(type="str", required=True), + event_source=dict(type="str", required=False, choices=["trigger", "discovery", "auto_registration", "internal"]), + state=dict(type="str", required=False, default="present", choices=["present", "absent"]), + status=dict(type="str", required=False, default="enabled", choices=["enabled", "disabled"]), + pause_in_maintenance=dict(type="bool", required=False, default=True), conditions=dict( - type='list', + type="list", required=False, default=[], - elements='dict', + elements="dict", options=dict( - formulaid=dict(type='str', required=False), - operator=dict(type='str', required=True), - type=dict(type='str', required=True), - value=dict(type='str', required=False), - value2=dict(type='str', required=False) + formulaid=dict(type="str", required=False), + operator=dict( + type="str", + required=True, + choices=[ + "equals", + "=", + "does not equal", + "<>", + "contains", + "like", + "does not contain", + "not like", + "in", + "is greater than or equals", + ">=", + "is less than or equals", + "<=", + "not in", + "matches", + "does not match", + "Yes", + "No" + ] + ), + type=dict(type="str", required=True), + value=dict(type="str", required=False), + value2=dict(type="str", required=False) ), required_if=[ - ['type', 'event_tag_value', ['value2']], + ["type", "event_tag_value", ["value2"]], ] ), - formula=dict(type='str', required=False, default=None), - eval_type=dict(type='str', required=False, default=None, choices=['andor', 'and', 'or', 'custom_expression']), + formula=dict(type="str", required=False, default=None), + eval_type=dict(type="str", required=False, default=None, choices=["andor", "and", "or", "custom_expression"]), operations=dict( - type='list', + type="list", required=False, default=[], - elements='dict', + elements="dict", options=dict( type=dict( - type='str', + type="str", required=True, choices=[ - 'send_message', - 'remote_command', - 'add_host', - 'remove_host', - 'add_to_host_group', - 'remove_from_host_group', - 'link_to_template', - 'unlink_from_template', - 'enable_host', - 'disable_host', - 'set_host_inventory_mode', + "send_message", + "remote_command", + "add_host", + "remove_host", + "add_to_host_group", + "remove_from_host_group", + "link_to_template", + "unlink_from_template", + "enable_host", + "disable_host", + "set_host_inventory_mode", + "notify_all_involved" ] ), - esc_period=dict(type='str', required=False), - esc_step_from=dict(type='int', required=False, default=1), - esc_step_to=dict(type='int', required=False, default=1), + esc_period=dict(type="str", required=False, default="0s"), + esc_step_from=dict(type="int", required=False, default=1), + esc_step_to=dict(type="int", required=False, default=1), operation_condition=dict( - type='str', + type="str", required=False, default=None, - choices=['acknowledged', 'not_acknowledged'] + choices=["acknowledged", "not_acknowledged"] ), # when type is remote_command command_type=dict( - type='str', + type="str", required=False, choices=[ - 'custom_script', - 'ipmi', - 'ssh', - 'telnet', - 'global_script' + "custom_script", + "ipmi", + "ssh", + "telnet", + "global_script" ] ), - command=dict(type='str', required=False), + command=dict(type="str", required=False), execute_on=dict( - type='str', + type="str", required=False, - choices=['agent', 'server', 'proxy'] + choices=["agent", "server", "proxy"] ), - password=dict(type='str', required=False, no_log=True), - port=dict(type='int', required=False), - run_on_groups=dict(type='list', required=False), - run_on_hosts=dict(type='list', required=False), - script_name=dict(type='str', required=False), - ssh_auth_type=dict(type='str', required=False, choices=['password', 'public_key']), - ssh_privatekey_file=dict(type='str', required=False), - ssh_publickey_file=dict(type='str', required=False), - username=dict(type='str', required=False), + password=dict(type="str", required=False, no_log=True), + port=dict(type="int", required=False), + run_on_groups=dict(type="list", required=False, elements="str"), + run_on_hosts=dict(type="list", required=False, elements="str"), + script_name=dict(type="str", required=False), + ssh_auth_type=dict(type="str", required=False, choices=["password", "public_key"]), + ssh_privatekey_file=dict(type="str", required=False), + ssh_publickey_file=dict(type="str", required=False), + username=dict(type="str", required=False), # when type is send_message - media_type=dict(type='str', required=False), - subject=dict(type='str', required=False), - message=dict(type='str', required=False), - send_to_groups=dict(type='list', required=False), - send_to_users=dict(type='list', required=False), + media_type=dict(type="str", required=False, default="all"), + subject=dict(type="str", required=False), + op_message=dict(type="str", required=False), + send_to_groups=dict(type="list", required=False, elements="str"), + send_to_users=dict(type="list", required=False, elements="str"), # when type is add_to_host_group or remove_from_host_group - host_groups=dict(type='list', required=False), + host_groups=dict(type="list", required=False, elements="str"), # when type is set_host_inventory_mode - inventory=dict(type='str', required=False, choices=['manual', 'automatic']), + inventory=dict(type="str", required=False, choices=["manual", "automatic"]), # when type is link_to_template or unlink_from_template - templates=dict(type='list', required=False) + templates=dict(type="list", required=False, elements="str") ), required_if=[ - ['type', 'remote_command', ['command_type']], - ['type', 'remote_command', ['run_on_groups', 'run_on_hosts'], True], - ['command_type', 'custom_script', ['command', 'execute_on']], - ['command_type', 'ipmi', ['command']], - ['command_type', 'ssh', ['command', 'ssh_auth_type']], - ['ssh_auth_type', 'password', ['username', 'password']], - ['ssh_auth_type', 'public_key', ['username', 'ssh_privatekey_file', 'ssh_publickey_file']], - ['command_type', 'telnet', ['command', 'username', 'password']], - ['command_type', 'global_script', ['script_name']], - ['type', 'add_to_host_group', ['host_groups']], - ['type', 'remove_from_host_group', ['host_groups']], - ['type', 'link_to_template', ['templates']], - ['type', 'unlink_from_template', ['templates']], - ['type', 'set_host_inventory_mode', ['inventory']], - ['type', 'send_message', ['send_to_users', 'send_to_groups'], True] + ["type", "remote_command", ["command_type"]], + ["type", "remote_command", ["run_on_groups", "run_on_hosts"], True], + ["command_type", "custom_script", ["command", "execute_on"]], + ["command_type", "ipmi", ["command"]], + ["command_type", "ssh", ["command", "ssh_auth_type"]], + ["ssh_auth_type", "password", ["username", "password"]], + ["ssh_auth_type", "public_key", ["username", "ssh_privatekey_file", "ssh_publickey_file"]], + ["command_type", "telnet", ["command", "username", "password"]], + ["command_type", "global_script", ["script_name"]], + ["type", "add_to_host_group", ["host_groups"]], + ["type", "remove_from_host_group", ["host_groups"]], + ["type", "link_to_template", ["templates"]], + ["type", "unlink_from_template", ["templates"]], + ["type", "set_host_inventory_mode", ["inventory"]], + ["type", "send_message", ["send_to_users", "send_to_groups"], True] ] ), recovery_operations=dict( - type='list', + type="list", required=False, default=[], - elements='dict', + elements="dict", options=dict( type=dict( - type='str', + type="str", required=True, choices=[ - 'send_message', - 'remote_command', - 'notify_all_involved' + "send_message", + "remote_command", + "notify_all_involved" ] ), # when type is remote_command command_type=dict( - type='str', + type="str", required=False, choices=[ - 'custom_script', - 'ipmi', - 'ssh', - 'telnet', - 'global_script' + "custom_script", + "ipmi", + "ssh", + "telnet", + "global_script" ] ), - command=dict(type='str', required=False), + command=dict(type="str", required=False), execute_on=dict( - type='str', + type="str", required=False, - choices=['agent', 'server', 'proxy'] + choices=["agent", "server", "proxy"] ), - password=dict(type='str', required=False, no_log=True), - port=dict(type='int', required=False), - run_on_groups=dict(type='list', required=False), - run_on_hosts=dict(type='list', required=False), - script_name=dict(type='str', required=False), - ssh_auth_type=dict(type='str', required=False, choices=['password', 'public_key']), - ssh_privatekey_file=dict(type='str', required=False), - ssh_publickey_file=dict(type='str', required=False), - username=dict(type='str', required=False), + password=dict(type="str", required=False, no_log=True), + port=dict(type="int", required=False), + run_on_groups=dict(type="list", required=False, elements="str"), + run_on_hosts=dict(type="list", required=False, elements="str"), + script_name=dict(type="str", required=False), + ssh_auth_type=dict(type="str", required=False, choices=["password", "public_key"]), + ssh_privatekey_file=dict(type="str", required=False), + ssh_publickey_file=dict(type="str", required=False), + username=dict(type="str", required=False), # when type is send_message - media_type=dict(type='str', required=False), - subject=dict(type='str', required=False), - message=dict(type='str', required=False), - send_to_groups=dict(type='list', required=False), - send_to_users=dict(type='list', required=False), + media_type=dict(type="str", required=False, default="all"), + subject=dict(type="str", required=False), + op_message=dict(type="str", required=False), + send_to_groups=dict(type="list", required=False, elements="str"), + send_to_users=dict(type="list", required=False, elements="str"), ), required_if=[ - ['type', 'remote_command', ['command_type']], - ['type', 'remote_command', [ - 'run_on_groups', - 'run_on_hosts' + ["type", "remote_command", ["command_type"]], + ["type", "remote_command", [ + "run_on_groups", + "run_on_hosts" ], True], - ['command_type', 'custom_script', [ - 'command', - 'execute_on' + ["command_type", "custom_script", [ + "command", + "execute_on" ]], - ['command_type', 'ipmi', ['command']], - ['command_type', 'ssh', ['command', 'ssh_auth_type']], - ['ssh_auth_type', 'password', ['username', 'password']], - ['ssh_auth_type', 'public_key', ['username', 'ssh_privatekey_file', 'ssh_publickey_file']], - ['command_type', 'telnet', ['command', 'username', 'password']], - ['command_type', 'global_script', ['script_name']], - ['type', 'send_message', ['send_to_users', 'send_to_groups'], True] + ["command_type", "ipmi", ["command"]], + ["command_type", "ssh", ["command", "ssh_auth_type"]], + ["ssh_auth_type", "password", ["username", "password"]], + ["ssh_auth_type", "public_key", ["username", "ssh_privatekey_file", "ssh_publickey_file"]], + ["command_type", "telnet", ["command", "username", "password"]], + ["command_type", "global_script", ["script_name"]], + ["type", "send_message", ["send_to_users", "send_to_groups"], True] ] ), acknowledge_operations=dict( - type='list', + type="list", required=False, default=[], - elements='dict', - aliases=['update_operations'], + elements="dict", + aliases=["update_operations"], options=dict( type=dict( - type='str', + type="str", required=True, choices=[ - 'send_message', - 'remote_command', - 'notify_all_involved' + "send_message", + "remote_command", + "notify_all_involved" ] ), # when type is remote_command command_type=dict( - type='str', + type="str", required=False, choices=[ - 'custom_script', - 'ipmi', - 'ssh', - 'telnet', - 'global_script' + "custom_script", + "ipmi", + "ssh", + "telnet", + "global_script" ] ), - command=dict(type='str', required=False), + command=dict(type="str", required=False), execute_on=dict( - type='str', + type="str", required=False, - choices=['agent', 'server', 'proxy'] + choices=["agent", "server", "proxy"] ), - password=dict(type='str', required=False, no_log=True), - port=dict(type='int', required=False), - run_on_groups=dict(type='list', required=False), - run_on_hosts=dict(type='list', required=False), - script_name=dict(type='str', required=False), - ssh_auth_type=dict(type='str', required=False, choices=['password', 'public_key']), - ssh_privatekey_file=dict(type='str', required=False), - ssh_publickey_file=dict(type='str', required=False), - username=dict(type='str', required=False), + password=dict(type="str", required=False, no_log=True), + port=dict(type="int", required=False), + run_on_groups=dict(type="list", required=False, elements="str"), + run_on_hosts=dict(type="list", required=False, elements="str"), + script_name=dict(type="str", required=False), + ssh_auth_type=dict(type="str", required=False, choices=["password", "public_key"]), + ssh_privatekey_file=dict(type="str", required=False), + ssh_publickey_file=dict(type="str", required=False), + username=dict(type="str", required=False), # when type is send_message - media_type=dict(type='str', required=False), - subject=dict(type='str', required=False), - message=dict(type='str', required=False), - send_to_groups=dict(type='list', required=False), - send_to_users=dict(type='list', required=False), + media_type=dict(type="str", required=False, default="all"), + subject=dict(type="str", required=False), + op_message=dict(type="str", required=False), + send_to_groups=dict(type="list", required=False, elements="str"), + send_to_users=dict(type="list", required=False, elements="str"), ), required_if=[ - ['type', 'remote_command', ['command_type']], - ['type', 'remote_command', [ - 'run_on_groups', - 'run_on_hosts' + ["type", "remote_command", ["command_type"]], + ["type", "remote_command", [ + "run_on_groups", + "run_on_hosts" ], True], - ['command_type', 'custom_script', [ - 'command', - 'execute_on' + ["command_type", "custom_script", [ + "command", + "execute_on" ]], - ['command_type', 'ipmi', ['command']], - ['command_type', 'ssh', ['command', 'ssh_auth_type']], - ['ssh_auth_type', 'password', ['username', 'password']], - ['ssh_auth_type', 'public_key', ['username', 'ssh_privatekey_file', 'ssh_publickey_file']], - ['command_type', 'telnet', ['command', 'username', 'password']], - ['command_type', 'global_script', ['script_name']], - ['type', 'send_message', ['send_to_users', 'send_to_groups'], True] + ["command_type", "ipmi", ["command"]], + ["command_type", "ssh", ["command", "ssh_auth_type"]], + ["ssh_auth_type", "password", ["username", "password"]], + ["ssh_auth_type", "public_key", ["username", "ssh_privatekey_file", "ssh_publickey_file"]], + ["command_type", "telnet", ["command", "username", "password"]], + ["command_type", "global_script", ["script_name"]], + ["type", "send_message", ["send_to_users", "send_to_groups"], True] ] ), - pause_symptoms=dict(type='bool', required=False, default=True) + pause_symptoms=dict(type="bool", required=False, default=True), + notify_if_canceled=dict(type="bool", required=False, default=True) )) module = AnsibleModule( argument_spec=argument_spec, required_if=[ - ['state', 'present', [ - 'event_source' + ["state", "present", [ + "event_source" ]] ], supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - name = module.params['name'] - esc_period = module.params['esc_period'] - event_source = module.params['event_source'] - state = module.params['state'] - status = module.params['status'] - pause_in_maintenance = module.params['pause_in_maintenance'] - default_message = module.params['default_message'] - default_subject = module.params['default_subject'] - recovery_default_message = module.params['recovery_default_message'] - recovery_default_subject = module.params['recovery_default_subject'] - acknowledge_default_message = module.params['acknowledge_default_message'] - acknowledge_default_subject = module.params['acknowledge_default_subject'] - conditions = module.params['conditions'] - formula = module.params['formula'] - eval_type = module.params['eval_type'] - operations = module.params['operations'] - recovery_operations = module.params['recovery_operations'] - acknowledge_operations = module.params['acknowledge_operations'] - pause_symptoms = module.params['pause_symptoms'] + name = module.params["name"] + esc_period = module.params["esc_period"] + event_source = module.params["event_source"] + state = module.params["state"] + status = module.params["status"] + pause_in_maintenance = module.params["pause_in_maintenance"] + conditions = module.params["conditions"] + formula = module.params["formula"] + eval_type = module.params["eval_type"] + operations = module.params["operations"] + recovery_operations = module.params["recovery_operations"] + acknowledge_operations = module.params["acknowledge_operations"] + pause_symptoms = module.params["pause_symptoms"] + notify_if_canceled = module.params["notify_if_canceled"] zapi_wrapper = Zapi(module) action = Action(module) @@ -2028,7 +2224,7 @@ def main(): fltr = Filter(module, zapi_wrapper) if action_exists: - action_id = zapi_wrapper.get_action_by_name(name)['actionid'] + action_id = zapi_wrapper.get_action_by_name(name)["actionid"] if state == "absent": result = action.delete_action(action_id) module.exit_json(changed=True, msg="Action Deleted: %s, ID: %s" % (name, result)) @@ -2040,24 +2236,16 @@ def main(): esc_period=esc_period, status=status, pause_in_maintenance=pause_in_maintenance, - default_message=default_message, - default_subject=default_subject, - recovery_default_message=recovery_default_message, - recovery_default_subject=recovery_default_subject, - acknowledge_default_message=acknowledge_default_message, - acknowledge_default_subject=acknowledge_default_subject, operations=ops.construct_the_data(operations, event_source), recovery_operations=recovery_ops.construct_the_data(recovery_operations), - conditions=fltr.construct_the_data(eval_type, formula, conditions) + conditions=fltr.construct_the_data(eval_type, formula, conditions), + notify_if_canceled=notify_if_canceled ) - if LooseVersion(zapi_wrapper._zbx_api_version) >= LooseVersion('6.4'): - kwargs['pause_symptoms'] = pause_symptoms + if LooseVersion(zapi_wrapper._zbx_api_version) >= LooseVersion("6.4"): + kwargs["pause_symptoms"] = pause_symptoms - if LooseVersion(zapi_wrapper._zbx_api_version) >= LooseVersion('6.0'): - kwargs[argument_spec['acknowledge_operations']['aliases'][0]] = acknowledge_ops.construct_the_data(acknowledge_operations) - else: - kwargs['acknowledge_operations'] = acknowledge_ops.construct_the_data(acknowledge_operations) + kwargs[argument_spec["acknowledge_operations"]["aliases"][0]] = acknowledge_ops.construct_the_data(acknowledge_operations) difference = action.check_difference(**kwargs) @@ -2079,28 +2267,20 @@ def main(): esc_period=esc_period, status=status, pause_in_maintenance=pause_in_maintenance, - default_message=default_message, - default_subject=default_subject, - recovery_default_message=recovery_default_message, - recovery_default_subject=recovery_default_subject, - acknowledge_default_message=acknowledge_default_message, - acknowledge_default_subject=acknowledge_default_subject, operations=ops.construct_the_data(operations, event_source), recovery_operations=recovery_ops.construct_the_data(recovery_operations), - conditions=fltr.construct_the_data(eval_type, formula, conditions) + conditions=fltr.construct_the_data(eval_type, formula, conditions), + notify_if_canceled=notify_if_canceled ) - if LooseVersion(zapi_wrapper._zbx_api_version) >= LooseVersion('6.0'): - kwargs[argument_spec['acknowledge_operations']['aliases'][0]] = acknowledge_ops.construct_the_data(acknowledge_operations) - else: - kwargs['acknowledge_operations'] = acknowledge_ops.construct_the_data(acknowledge_operations) + kwargs[argument_spec["acknowledge_operations"]["aliases"][0]] = acknowledge_ops.construct_the_data(acknowledge_operations) - if LooseVersion(zapi_wrapper._zbx_api_version) >= LooseVersion('6.4'): - kwargs['pause_symptoms'] = pause_symptoms + if LooseVersion(zapi_wrapper._zbx_api_version) >= LooseVersion("6.4"): + kwargs["pause_symptoms"] = pause_symptoms action_id = action.add_action(**kwargs) module.exit_json(changed=True, msg="Action created: %s, ID: %s" % (name, action_id)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_api_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_api_info.py new file mode 100644 index 000000000..5941408e9 --- /dev/null +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_api_info.py @@ -0,0 +1,108 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2022, ONODERA Masaru <masaru-onodera@ieee.org> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: zabbix_api_info + +short_description: Retrieve Zabbix API info + +description: + - This module allows you to retrieve Zabbix api info. + +author: + - ONODERA Masaru(@masa-orca) + +requirements: + - "python >= 3.9" + +version_added: 2.1.0 + +extends_documentation_fragment: + - community.zabbix.zabbix +''' + +EXAMPLES = ''' +# If you want to use Username and Password to be authenticated by Zabbix Server +- name: Set credentials to access Zabbix Server API + ansible.builtin.set_fact: + ansible_user: Admin + ansible_httpapi_pass: zabbix + +# If you want to use API token to be authenticated by Zabbix Server +# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens +- name: Set API token + ansible.builtin.set_fact: + ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 + +- name: Retrieve API information + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_api_info: + register: zbx_api_info +''' + +RETURN = ''' +api: + description: Summaries of Zabbix API info + returned: success + type: dict + contains: + version: + description: API version + type: str + sample: 6.0.18 +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.compat.version import LooseVersion + +from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase +import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils + + +class ApiInfo(ZabbixBase): + def __init__(self, module, zbx=None, zapi_wrapper=None): + super(ApiInfo, self).__init__(module, zbx, zapi_wrapper) + if LooseVersion(self._zbx_api_version) < LooseVersion('2.2.0'): + module.fail_json(msg="This module doesn't support Zabbix versions lower than 2.2.0") + + def get_api_info(self): + if self._module.check_mode: + self._module.exit_json(changed=False) + try: + api = { + 'version': self._zbx_api_version + } + self._module.exit_json(api=api) + except Exception as e: + self._module.fail_json(msg="Failed to retrieve API info: %s" % e) + + +def main(): + argument_spec = zabbix_utils.zabbix_common_argument_spec() + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True + ) + + api_info = ApiInfo(module) + api_info.get_api_info() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_authentication.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_authentication.py index 51fb3e5b9..f8eaf8e19 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_authentication.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_authentication.py @@ -5,10 +5,11 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: zabbix_authentication @@ -21,7 +22,7 @@ author: - ONODERA Masaru(@masa-orca) requirements: - - "python >= 2.6" + - "python >= 3.9" version_added: 1.6.0 @@ -257,24 +258,21 @@ options: type: list elements: str -notes: - - Zabbix 5.4 version and higher are supported. - extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Update all authentication setting (Zabbix <= 6.0) @@ -285,9 +283,9 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form @@ -296,20 +294,20 @@ EXAMPLES = ''' - any http_case_sensitive: true ldap_configured: true - ldap_host: 'ldap://localhost' + ldap_host: "ldap://localhost" ldap_port: 389 - ldap_base_dn: 'ou=Users,ou=system' - ldap_search_attribute: 'uid' - ldap_bind_dn: 'uid=ldap_search,ou=system' + ldap_base_dn: "ou=Users,ou=system" + ldap_search_attribute: "uid" + ldap_bind_dn: "uid=ldap_search,ou=system" ldap_case_sensitive: true - ldap_bind_password: 'password' + ldap_bind_password: "password" saml_auth_enabled: true - saml_idp_entityid: '' - saml_sso_url: 'https://localhost/SAML2/SSO' - saml_slo_url: 'https://localhost/SAML2/SLO' - saml_username_attribute: 'uid' - saml_sp_entityid: 'https://localhost' - saml_nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity' + saml_idp_entityid: "" + saml_sso_url: "https://localhost/SAML2/SSO" + saml_slo_url: "https://localhost/SAML2/SLO" + saml_username_attribute: "uid" + saml_sp_entityid: "https://localhost" + saml_nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity" saml_sign_messages: true saml_sign_assertions: true saml_sign_authn_requests: true @@ -333,9 +331,9 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form @@ -346,12 +344,12 @@ EXAMPLES = ''' ldap_configured: true ldap_case_sensitive: true saml_auth_enabled: true - saml_idp_entityid: '' - saml_sso_url: 'https://localhost/SAML2/SSO' - saml_slo_url: 'https://localhost/SAML2/SLO' - saml_username_attribute: 'uid' - saml_sp_entityid: 'https://localhost' - saml_nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity' + saml_idp_entityid: "" + saml_sso_url: "https://localhost/SAML2/SSO" + saml_slo_url: "https://localhost/SAML2/SLO" + saml_username_attribute: "uid" + saml_sp_entityid: "https://localhost" + saml_nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity" saml_sign_messages: true saml_sign_assertions: true saml_sign_authn_requests: true @@ -375,9 +373,9 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form @@ -386,6 +384,7 @@ EXAMPLES = ''' - any http_case_sensitive: true ldap_auth_enabled: true + ldap_userdirectory: TestUserDirectory ldap_case_sensitive: true saml_auth_enabled: true saml_case_sensitive: true @@ -399,15 +398,15 @@ EXAMPLES = ''' - contain_digits - contain_special_characters - avoid_easy_to_guess -''' +""" -RETURN = ''' +RETURN = """ msg: description: The result of the operation returned: success type: str - sample: 'Successfully update authentication setting' -''' + sample: "Successfully update authentication setting" +""" from ansible.module_utils.basic import AnsibleModule @@ -417,251 +416,291 @@ import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabb class Authentication(ZabbixBase): - def __init__(self, module, zbx=None, zapi_wrapper=None): - super(Authentication, self).__init__(module, zbx, zapi_wrapper) - if LooseVersion(self._zbx_api_version) < LooseVersion('5.4.0'): - module.fail_json(msg="This module doesn't support Zabbix versions lower than 5.4.0") # get authentication setting def get_authentication(self): try: - return self._zapi.authentication.get({'output': 'extend'}) + return self._zapi.authentication.get({"output": "extend"}) except Exception as e: self._module.fail_json(msg="Failed to get authentication setting: %s" % e) # update authentication setting def update_authentication( - self, - current_authentication, - authentication_type, - http_auth_enabled, - http_login_form, - http_strip_domains, - http_case_sensitive, - ldap_configured, - ldap_auth_enabled, - ldap_host, - ldap_port, - ldap_base_dn, - ldap_search_attribute, - ldap_bind_dn, - ldap_case_sensitive, - ldap_bind_password, - ldap_userdirectory, - saml_auth_enabled, - saml_idp_entityid, - saml_sso_url, - saml_slo_url, - saml_username_attribute, - saml_sp_entityid, - saml_nameid_format, - saml_sign_messages, - saml_sign_assertions, - saml_sign_authn_requests, - saml_sign_logout_requests, - saml_sign_logout_responses, - saml_encrypt_nameid, - saml_encrypt_assertions, - saml_case_sensitive, - passwd_min_length, - passwd_check_rules, - ldap_jit_status, - saml_jit_status, - jit_provision_interval, - disabled_usrgroup): + self, + current_authentication, + authentication_type, + http_auth_enabled, + http_login_form, + http_strip_domains, + http_case_sensitive, + ldap_configured, + ldap_auth_enabled, + ldap_host, + ldap_port, + ldap_base_dn, + ldap_search_attribute, + ldap_bind_dn, + ldap_case_sensitive, + ldap_bind_password, + ldap_userdirectory, + saml_auth_enabled, + saml_idp_entityid, + saml_sso_url, + saml_slo_url, + saml_username_attribute, + saml_sp_entityid, + saml_nameid_format, + saml_sign_messages, + saml_sign_assertions, + saml_sign_authn_requests, + saml_sign_logout_requests, + saml_sign_logout_responses, + saml_encrypt_nameid, + saml_encrypt_assertions, + saml_case_sensitive, + passwd_min_length, + passwd_check_rules, + ldap_jit_status, + saml_jit_status, + jit_provision_interval, + disabled_usrgroup, + ): try: params = {} if authentication_type: - params['authentication_type'] = str(zabbix_utils.helper_to_numeric_value( - ['internal', 'ldap'], - authentication_type - )) + params["authentication_type"] = str( + zabbix_utils.helper_to_numeric_value( + ["internal", "ldap"], authentication_type + ) + ) if isinstance(http_auth_enabled, bool): - params['http_auth_enabled'] = str(int(http_auth_enabled)) + params["http_auth_enabled"] = str(int(http_auth_enabled)) if http_login_form: - params['http_login_form'] = str(zabbix_utils.helper_to_numeric_value( - ['zabbix_login_form', 'http_login_form'], - http_login_form - )) + params["http_login_form"] = str( + zabbix_utils.helper_to_numeric_value( + ["zabbix_login_form", "http_login_form"], http_login_form + ) + ) if http_strip_domains: - params['http_strip_domains'] = ','.join(http_strip_domains) + params["http_strip_domains"] = ",".join(http_strip_domains) if isinstance(http_case_sensitive, bool): - params['http_case_sensitive'] = str(int(http_case_sensitive)) + params["http_case_sensitive"] = str(int(http_case_sensitive)) - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): if isinstance(ldap_configured, bool): - params['ldap_configured'] = str(int(ldap_configured)) + params["ldap_configured"] = str(int(ldap_configured)) else: if isinstance(ldap_auth_enabled, bool): - params['ldap_auth_enabled'] = str(int(ldap_auth_enabled)) + params["ldap_auth_enabled"] = str(int(ldap_auth_enabled)) - if LooseVersion(self._zbx_api_version) < LooseVersion('6.2.0'): + if LooseVersion(self._zbx_api_version) < LooseVersion("6.2"): if ldap_host: - params['ldap_host'] = ldap_host + params["ldap_host"] = ldap_host if ldap_port: - params['ldap_port'] = str(ldap_port) + params["ldap_port"] = str(ldap_port) if ldap_base_dn: - params['ldap_base_dn'] = ldap_base_dn + params["ldap_base_dn"] = ldap_base_dn if ldap_search_attribute: - params['ldap_search_attribute'] = ldap_search_attribute + params["ldap_search_attribute"] = ldap_search_attribute if ldap_bind_dn: - params['ldap_bind_dn'] = ldap_bind_dn + params["ldap_bind_dn"] = ldap_bind_dn if ldap_bind_password: - params['ldap_bind_password'] = ldap_bind_password + params["ldap_bind_password"] = ldap_bind_password else: if ldap_userdirectory: - directory = self._zapi.userdirectory.get({'search': {'name': ldap_userdirectory}}) + directory = self._zapi.userdirectory.get( + {"search": {"name": ldap_userdirectory}} + ) if not directory: - self._module.fail_json(msg="Canot find user directory with name: %s" % ldap_userdirectory) - params['ldap_userdirectoryid'] = directory[0]['userdirectoryid'] + self._module.fail_json( + msg="Canot find user directory with name: %s" + % ldap_userdirectory + ) + params["ldap_userdirectoryid"] = directory[0]["userdirectoryid"] if isinstance(ldap_case_sensitive, bool): - params['ldap_case_sensitive'] = str(int(ldap_case_sensitive)) + params["ldap_case_sensitive"] = str(int(ldap_case_sensitive)) if isinstance(saml_auth_enabled, bool): - params['saml_auth_enabled'] = str(int(saml_auth_enabled)) + params["saml_auth_enabled"] = str(int(saml_auth_enabled)) - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): if saml_idp_entityid: - params['saml_idp_entityid'] = saml_idp_entityid + params["saml_idp_entityid"] = saml_idp_entityid if saml_sso_url: - params['saml_sso_url'] = saml_sso_url + params["saml_sso_url"] = saml_sso_url if saml_slo_url: - params['saml_slo_url'] = saml_slo_url + params["saml_slo_url"] = saml_slo_url if saml_username_attribute: - params['saml_username_attribute'] = saml_username_attribute + params["saml_username_attribute"] = saml_username_attribute if saml_sp_entityid: - params['saml_sp_entityid'] = saml_sp_entityid + params["saml_sp_entityid"] = saml_sp_entityid if saml_nameid_format: - params['saml_nameid_format'] = saml_nameid_format + params["saml_nameid_format"] = saml_nameid_format if isinstance(saml_sign_messages, bool): - params['saml_sign_messages'] = str(int(saml_sign_messages)) + params["saml_sign_messages"] = str(int(saml_sign_messages)) if isinstance(saml_sign_assertions, bool): - params['saml_sign_assertions'] = str(int(saml_sign_assertions)) + params["saml_sign_assertions"] = str(int(saml_sign_assertions)) if isinstance(saml_sign_authn_requests, bool): - params['saml_sign_authn_requests'] = str(int(saml_sign_authn_requests)) + params["saml_sign_authn_requests"] = str( + int(saml_sign_authn_requests) + ) if isinstance(saml_sign_logout_requests, bool): - params['saml_sign_logout_requests'] = str(int(saml_sign_logout_requests)) + params["saml_sign_logout_requests"] = str( + int(saml_sign_logout_requests) + ) if isinstance(saml_sign_logout_responses, bool): - params['saml_sign_logout_responses'] = str(int(saml_sign_logout_responses)) + params["saml_sign_logout_responses"] = str( + int(saml_sign_logout_responses) + ) if isinstance(saml_encrypt_nameid, bool): - params['saml_encrypt_nameid'] = str(int(saml_encrypt_nameid)) + params["saml_encrypt_nameid"] = str(int(saml_encrypt_nameid)) if isinstance(saml_encrypt_assertions, bool): - params['saml_encrypt_assertions'] = str(int(saml_encrypt_assertions)) + params["saml_encrypt_assertions"] = str( + int(saml_encrypt_assertions) + ) if isinstance(saml_case_sensitive, bool): - params['saml_case_sensitive'] = str(int(saml_case_sensitive)) + params["saml_case_sensitive"] = str(int(saml_case_sensitive)) else: if isinstance(ldap_jit_status, bool): - params['ldap_jit_status'] = str(int(ldap_jit_status)) + params["ldap_jit_status"] = str(int(ldap_jit_status)) if isinstance(saml_jit_status, bool): - params['saml_jit_status'] = str(int(saml_jit_status)) + params["saml_jit_status"] = str(int(saml_jit_status)) if isinstance(jit_provision_interval, str): - params['jit_provision_interval'] = jit_provision_interval + params["jit_provision_interval"] = jit_provision_interval if isinstance(disabled_usrgroup, str): - usrgrpids = self._zapi.usergroup.get({'filter': {'name': disabled_usrgroup}}) + usrgrpids = self._zapi.usergroup.get( + {"filter": {"name": disabled_usrgroup}} + ) if not usrgrpids: - self._module.fail_json('User group "%s" cannot be found' % disabled_usrgroup) - params['disabled_usrgrpid'] = str(int(usrgrpids[0]['usrgrpid'])) + self._module.fail_json( + "User group '%s' cannot be found" % disabled_usrgroup + ) + params["disabled_usrgrpid"] = str(int(usrgrpids[0]["usrgrpid"])) if (ldap_jit_status or saml_jit_status) and not disabled_usrgroup: - self._module.fail_json('"disabled_usrgroup" must be provided if "ldap_jit_status" or "saml_jit_status" enabled') + self._module.fail_json( + "'disabled_usrgroup' must be provided if 'ldap_jit_status' or 'saml_jit_status' enabled" + ) if passwd_min_length: - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - self._module.warn('passwd_min_length is ignored with Zabbix 5.4.') - elif passwd_min_length < 1 or passwd_min_length > 70: + if passwd_min_length < 1 or passwd_min_length > 70: self._module.fail_json(msg="Please set 0-70 to passwd_min_length.") else: - params['passwd_min_length'] = str(passwd_min_length) + params["passwd_min_length"] = str(passwd_min_length) if passwd_check_rules: - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - self._module.warn('passwd_check_rules is ignored with Zabbix 5.4.') - else: - passwd_check_rules_values = [ - 'contain_uppercase_and_lowercase_letters', - 'contain_digits', - 'contain_special_characters', - 'avoid_easy_to_guess' - ] - params['passwd_check_rules'] = 0 - if isinstance(passwd_check_rules, str): - if passwd_check_rules not in passwd_check_rules_values: - self._module.fail_json(msg="%s is invalid value for passwd_check_rules." % passwd_check_rules) - params['passwd_check_rules'] += 2 ** zabbix_utils.helper_to_numeric_value( - passwd_check_rules_values, passwd_check_rules + passwd_check_rules_values = [ + "contain_uppercase_and_lowercase_letters", + "contain_digits", + "contain_special_characters", + "avoid_easy_to_guess", + ] + params["passwd_check_rules"] = 0 + if isinstance(passwd_check_rules, str): + if passwd_check_rules not in passwd_check_rules_values: + self._module.fail_json( + msg="%s is invalid value for passwd_check_rules." + % passwd_check_rules ) - elif isinstance(passwd_check_rules, list): - for _passwd_check_rules_value in passwd_check_rules: - if _passwd_check_rules_value not in passwd_check_rules_values: - self._module.fail_json(msg="%s is invalid value for passwd_check_rules." % _passwd_check_rules_value) - params['passwd_check_rules'] += 2 ** zabbix_utils.helper_to_numeric_value( + params[ + "passwd_check_rules" + ] += 2 ** zabbix_utils.helper_to_numeric_value( + passwd_check_rules_values, passwd_check_rules + ) + elif isinstance(passwd_check_rules, list): + for _passwd_check_rules_value in passwd_check_rules: + if ( + _passwd_check_rules_value + not in passwd_check_rules_values + ): + self._module.fail_json( + msg="%s is invalid value for passwd_check_rules." + % _passwd_check_rules_value + ) + params[ + "passwd_check_rules" + ] += 2 ** zabbix_utils.helper_to_numeric_value( passwd_check_rules_values, _passwd_check_rules_value ) - params['passwd_check_rules'] = str(params['passwd_check_rules']) + params["passwd_check_rules"] = str(params["passwd_check_rules"]) future_authentication = current_authentication.copy() future_authentication.update(params) - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): - if (current_authentication['ldap_configured'] == '0' - and future_authentication['ldap_configured'] == '1'): - if LooseVersion(self._zbx_api_version) < LooseVersion('6.2.0'): - if (not ldap_host - or not ldap_port - or not ldap_search_attribute - or not ldap_base_dn): + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): + if ( + current_authentication["ldap_configured"] == "0" + and future_authentication["ldap_configured"] == "1" + ): + if LooseVersion(self._zbx_api_version) < LooseVersion("6.2"): + if ( + not ldap_host + or not ldap_port + or not ldap_search_attribute + or not ldap_base_dn + ): self._module.fail_json( msg="Please set ldap_host, ldap_search_attribute and ldap_base_dn when you change a value of ldap_configured to true." ) else: if not ldap_userdirectory: - self._module.fail_json(msg="Please set ldap_userdirectory when you change a value of ldap_configured to true.") + self._module.fail_json( + msg="Please set ldap_userdirectory when you change a value of ldap_configured to true." + ) else: - if (current_authentication['ldap_auth_enabled'] == "0" - and future_authentication['ldap_auth_enabled'] == "1"): + if ( + current_authentication["ldap_auth_enabled"] == "0" + and future_authentication["ldap_auth_enabled"] == "1" + ): if not ldap_userdirectory: - self._module.fail_json(msg="Please set ldap_userdirectory when you change a value of ldap_auth_enabled to true.") - - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): - if (current_authentication['saml_auth_enabled'] == '0' - and future_authentication['saml_auth_enabled'] == '1' - and not saml_idp_entityid - and not saml_sso_url - and not saml_username_attribute - and not saml_sp_entityid): + self._module.fail_json( + msg="Please set ldap_userdirectory when you change a value of ldap_auth_enabled to true." + ) + + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): + if ( + current_authentication["saml_auth_enabled"] == "0" + and future_authentication["saml_auth_enabled"] == "1" + and not saml_idp_entityid + and not saml_sso_url + and not saml_username_attribute + and not saml_sp_entityid + ): self._module.fail_json( - msg=' '.join([ - "Please set saml_idp_entityid, saml_sso_url, saml_username_attribute and saml_sp_entityid", - "when you change a value of saml_auth_enabled to true." - ]) + msg=" ".join( + [ + "Please set saml_idp_entityid, saml_sso_url, saml_username_attribute and saml_sp_entityid", + "when you change a value of saml_auth_enabled to true.", + ] + ) ) if future_authentication != current_authentication: @@ -669,100 +708,101 @@ class Authentication(ZabbixBase): self._module.exit_json(changed=True) self._zapi.authentication.update(params) - self._module.exit_json(changed=True, result="Successfully update authentication setting") + self._module.exit_json( + changed=True, result="Successfully update authentication setting" + ) else: - self._module.exit_json(changed=False, result="Authentication setting is already up to date") + self._module.exit_json( + changed=False, result="Authentication setting is already up to date" + ) except Exception as e: - self._module.fail_json(msg="Failed to update authentication setting, Exception: %s" % e) + self._module.fail_json( + msg="Failed to update authentication setting, Exception: %s" % e + ) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() - argument_spec.update(dict( - authentication_type=dict(type='str', choices=['internal', 'ldap']), - http_auth_enabled=dict(type='bool'), - http_login_form=dict(type='str', choices=['zabbix_login_form', 'http_login_form']), - http_strip_domains=dict(type='list', elements='str'), - http_case_sensitive=dict(type='bool'), - ldap_configured=dict(type='bool'), - ldap_auth_enabled=dict(type='bool'), - ldap_host=dict(type='str'), - ldap_port=dict(type='int'), - ldap_base_dn=dict(type='str'), - ldap_search_attribute=dict(type='str'), - ldap_bind_dn=dict(type='str'), - ldap_case_sensitive=dict(type='bool'), - ldap_bind_password=dict(type='str', no_log=True), - ldap_userdirectory=dict(type='str'), - ldap_jit_status=dict(type='bool'), - saml_auth_enabled=dict(type='bool'), - saml_idp_entityid=dict(type='str'), - saml_sso_url=dict(type='str'), - saml_slo_url=dict(type='str'), - saml_username_attribute=dict(type='str'), - saml_sp_entityid=dict(type='str'), - saml_nameid_format=dict(type='str'), - saml_sign_messages=dict(type='bool'), - saml_sign_assertions=dict(type='bool'), - saml_sign_authn_requests=dict(type='bool'), - saml_sign_logout_requests=dict(type='bool'), - saml_sign_logout_responses=dict(type='bool'), - saml_encrypt_nameid=dict(type='bool'), - saml_encrypt_assertions=dict(type='bool'), - saml_case_sensitive=dict(type='bool'), - saml_jit_status=dict(type='bool'), - jit_provision_interval=dict(type='str', default='1h'), - disabled_usrgroup=dict(type='str'), - passwd_min_length=dict(type='int', no_log=False), - passwd_check_rules=dict(type='list', elements='str', no_log=False) - )) - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True + argument_spec.update( + dict( + authentication_type=dict(type="str", choices=["internal", "ldap"]), + http_auth_enabled=dict(type="bool"), + http_login_form=dict( + type="str", choices=["zabbix_login_form", "http_login_form"] + ), + http_strip_domains=dict(type="list", elements="str"), + http_case_sensitive=dict(type="bool"), + ldap_configured=dict(type="bool"), + ldap_auth_enabled=dict(type="bool"), + ldap_host=dict(type="str"), + ldap_port=dict(type="int"), + ldap_base_dn=dict(type="str"), + ldap_search_attribute=dict(type="str"), + ldap_bind_dn=dict(type="str"), + ldap_case_sensitive=dict(type="bool"), + ldap_bind_password=dict(type="str", no_log=True), + ldap_userdirectory=dict(type="str"), + ldap_jit_status=dict(type="bool"), + saml_auth_enabled=dict(type="bool"), + saml_idp_entityid=dict(type="str"), + saml_sso_url=dict(type="str"), + saml_slo_url=dict(type="str"), + saml_username_attribute=dict(type="str"), + saml_sp_entityid=dict(type="str"), + saml_nameid_format=dict(type="str"), + saml_sign_messages=dict(type="bool"), + saml_sign_assertions=dict(type="bool"), + saml_sign_authn_requests=dict(type="bool"), + saml_sign_logout_requests=dict(type="bool"), + saml_sign_logout_responses=dict(type="bool"), + saml_encrypt_nameid=dict(type="bool"), + saml_encrypt_assertions=dict(type="bool"), + saml_case_sensitive=dict(type="bool"), + saml_jit_status=dict(type="bool"), + jit_provision_interval=dict(type="str", default="1h"), + disabled_usrgroup=dict(type="str"), + passwd_min_length=dict(type="int", no_log=False), + passwd_check_rules=dict(type="list", elements="str", no_log=False), + ) ) - - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - authentication_type = module.params['authentication_type'] - http_auth_enabled = module.params['http_auth_enabled'] - http_login_form = module.params['http_login_form'] - http_strip_domains = module.params['http_strip_domains'] - http_case_sensitive = module.params['http_case_sensitive'] - ldap_configured = module.params['ldap_configured'] - ldap_auth_enabled = module.params['ldap_auth_enabled'] - ldap_host = module.params['ldap_host'] - ldap_port = module.params['ldap_port'] - ldap_base_dn = module.params['ldap_base_dn'] - ldap_search_attribute = module.params['ldap_search_attribute'] - ldap_bind_dn = module.params['ldap_bind_dn'] - ldap_case_sensitive = module.params['ldap_case_sensitive'] - ldap_bind_password = module.params['ldap_bind_password'] - ldap_userdirectory = module.params['ldap_userdirectory'] - saml_auth_enabled = module.params['saml_auth_enabled'] - saml_idp_entityid = module.params['saml_idp_entityid'] - saml_sso_url = module.params['saml_sso_url'] - saml_slo_url = module.params['saml_slo_url'] - saml_username_attribute = module.params['saml_username_attribute'] - saml_sp_entityid = module.params['saml_sp_entityid'] - saml_nameid_format = module.params['saml_nameid_format'] - saml_sign_messages = module.params['saml_sign_messages'] - saml_sign_assertions = module.params['saml_sign_assertions'] - saml_sign_authn_requests = module.params['saml_sign_authn_requests'] - saml_sign_logout_requests = module.params['saml_sign_logout_requests'] - saml_sign_logout_responses = module.params['saml_sign_logout_responses'] - saml_encrypt_nameid = module.params['saml_encrypt_nameid'] - saml_encrypt_assertions = module.params['saml_encrypt_assertions'] - saml_case_sensitive = module.params['saml_case_sensitive'] - passwd_min_length = module.params['passwd_min_length'] - passwd_check_rules = module.params['passwd_check_rules'] - ldap_jit_status = module.params['ldap_jit_status'] - saml_jit_status = module.params['saml_jit_status'] - jit_provision_interval = module.params['jit_provision_interval'] - disabled_usrgroup = module.params['disabled_usrgroup'] + module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + + authentication_type = module.params["authentication_type"] + http_auth_enabled = module.params["http_auth_enabled"] + http_login_form = module.params["http_login_form"] + http_strip_domains = module.params["http_strip_domains"] + http_case_sensitive = module.params["http_case_sensitive"] + ldap_configured = module.params["ldap_configured"] + ldap_auth_enabled = module.params["ldap_auth_enabled"] + ldap_host = module.params["ldap_host"] + ldap_port = module.params["ldap_port"] + ldap_base_dn = module.params["ldap_base_dn"] + ldap_search_attribute = module.params["ldap_search_attribute"] + ldap_bind_dn = module.params["ldap_bind_dn"] + ldap_case_sensitive = module.params["ldap_case_sensitive"] + ldap_bind_password = module.params["ldap_bind_password"] + ldap_userdirectory = module.params["ldap_userdirectory"] + saml_auth_enabled = module.params["saml_auth_enabled"] + saml_idp_entityid = module.params["saml_idp_entityid"] + saml_sso_url = module.params["saml_sso_url"] + saml_slo_url = module.params["saml_slo_url"] + saml_username_attribute = module.params["saml_username_attribute"] + saml_sp_entityid = module.params["saml_sp_entityid"] + saml_nameid_format = module.params["saml_nameid_format"] + saml_sign_messages = module.params["saml_sign_messages"] + saml_sign_assertions = module.params["saml_sign_assertions"] + saml_sign_authn_requests = module.params["saml_sign_authn_requests"] + saml_sign_logout_requests = module.params["saml_sign_logout_requests"] + saml_sign_logout_responses = module.params["saml_sign_logout_responses"] + saml_encrypt_nameid = module.params["saml_encrypt_nameid"] + saml_encrypt_assertions = module.params["saml_encrypt_assertions"] + saml_case_sensitive = module.params["saml_case_sensitive"] + passwd_min_length = module.params["passwd_min_length"] + passwd_check_rules = module.params["passwd_check_rules"] + ldap_jit_status = module.params["ldap_jit_status"] + saml_jit_status = module.params["saml_jit_status"] + jit_provision_interval = module.params["jit_provision_interval"] + disabled_usrgroup = module.params["disabled_usrgroup"] authentication = Authentication(module) @@ -804,9 +844,9 @@ def main(): ldap_jit_status, saml_jit_status, jit_provision_interval, - disabled_usrgroup + disabled_usrgroup, ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_autoregister.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_autoregister.py index c8bf35538..c00f52cbe 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_autoregister.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_autoregister.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: zabbix_autoregister @@ -22,7 +22,7 @@ author: - ONODERA Masaru(@masa-orca) requirements: - - "python >= 2.6" + - "python >= 3.9" version_added: 1.6.0 @@ -47,7 +47,6 @@ options: type: str notes: - - Only Zabbix >= 4.4 is supported. - This module returns changed=true when any value is set in I(tls_psk_identity) or I(tls_psk) as Zabbix API will not return any sensitive information back for module to compare. - Please note that this module configures B(global Zabbix Server settings). @@ -57,19 +56,19 @@ notes: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Update autoregistration @@ -80,16 +79,13 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_autoregister: - server_url: "http://zabbix.example.com/zabbix/" - login_user: Admin - login_password: secret tls_accept: - unsecure - tls_with_psk - tls_psk_identity: 'PSK 001' + tls_psk_identity: "PSK 001" tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" - name: Set unsecure to tls_accept @@ -100,42 +96,32 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_autoregister: - server_url: "http://zabbix.example.com/zabbix/" - login_user: Admin - login_password: secret tls_accept: unsecure -''' +""" -RETURN = ''' +RETURN = """ msg: description: The result of the operation returned: success type: str - sample: 'Successfully updated global autoregistration setting' -''' + sample: "Successfully updated global autoregistration setting" +""" from ansible.module_utils.basic import AnsibleModule - from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion - import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils class Autoregistration(ZabbixBase): - def __init__(self, module, zbx=None, zapi_wrapper=None): - super(Autoregistration, self).__init__(module, zbx, zapi_wrapper) - if LooseVersion(self._zbx_api_version) < LooseVersion('4.4.0'): - module.fail_json(msg="This module doesn't support Zabbix versions lower than 4.4.0") # get autoregistration def get_autoregistration(self): try: - return self._zapi.autoregistration.get({"output": 'extend'}) + return self._zapi.autoregistration.get({"output": "extend"}) except Exception as e: self._module.fail_json(msg="Failed to get autoregistration: %s" % e) @@ -143,38 +129,38 @@ class Autoregistration(ZabbixBase): def update_autoregistration(self, current_setting, tls_accept, tls_psk_identity, tls_psk): tls_accept_values = [ None, - 'unsecure', - 'tls_with_psk' + "unsecure", + "tls_with_psk" ] params = {} try: if isinstance(tls_accept, str): - params['tls_accept'] = zabbix_utils.helper_to_numeric_value( + params["tls_accept"] = zabbix_utils.helper_to_numeric_value( tls_accept_values, tls_accept ) elif isinstance(tls_accept, list): - params['tls_accept'] = 0 + params["tls_accept"] = 0 for _tls_accept_value in tls_accept: - params['tls_accept'] += zabbix_utils.helper_to_numeric_value( + params["tls_accept"] += zabbix_utils.helper_to_numeric_value( tls_accept_values, _tls_accept_value ) else: self._module.fail_json(msg="Value of tls_accept must be list or string.") if tls_psk_identity: - params['tls_psk_identity'] = tls_psk_identity + params["tls_psk_identity"] = tls_psk_identity if tls_psk: - params['tls_psk'] = tls_psk + params["tls_psk"] = tls_psk - current_tls_accept = int(current_setting['tls_accept']) - if (current_tls_accept == tls_accept_values.index('unsecure') - and params['tls_accept'] >= tls_accept_values.index('tls_with_psk')): + current_tls_accept = int(current_setting["tls_accept"]) + if (current_tls_accept == tls_accept_values.index("unsecure") + and params["tls_accept"] >= tls_accept_values.index("tls_with_psk")): if not tls_psk_identity or not tls_psk: self._module.fail_json(msg="Please set tls_psk_identity and tls_psk.") if (not tls_psk_identity and not tls_psk - and params['tls_accept'] == current_tls_accept): + and params["tls_accept"] == current_tls_accept): self._module.exit_json(changed=False, result="Autoregistration is already up to date") if self._module.check_mode: @@ -192,32 +178,26 @@ def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( tls_accept=dict( - type='list', - elements='str', + type="list", + elements="str", required=True ), - tls_psk_identity=dict(type='str', required=False, no_log=True), - tls_psk=dict(type='str', required=False, no_log=True), + tls_psk_identity=dict(type="str", required=False, no_log=True), + tls_psk=dict(type="str", required=False, no_log=True), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - tls_accept = module.params['tls_accept'] - tls_psk_identity = module.params['tls_psk_identity'] - tls_psk = module.params['tls_psk'] + tls_accept = module.params["tls_accept"] + tls_psk_identity = module.params["tls_psk_identity"] + tls_psk = module.params["tls_psk"] autoregistration_class_obj = Autoregistration(module) current_setting = autoregistration_class_obj.get_autoregistration() autoregistration_class_obj.update_autoregistration(current_setting, tls_accept, tls_psk_identity, tls_psk) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_discovery_rule.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_discovery_rule.py index 11b2f7c7f..2296f3db8 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_discovery_rule.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_discovery_rule.py @@ -7,7 +7,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_discovery_rule short_description: Create/delete/update Zabbix discovery rules @@ -18,7 +18,7 @@ description: author: - "Tobias Birkefeld (@tcraxs)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: state: description: @@ -46,22 +46,22 @@ options: description: - Type of check. type: str - choices: ['SSH', - 'LDAP', - 'SMTP', - 'FTP', - 'HTTP', - 'POP', - 'NNTP', - 'IMAP', - 'TCP', - 'Zabbix', - 'SNMPv1', - 'SNMPv2', - 'ICMP', - 'SNMPv3', - 'HTTPS', - 'Telnet'] + choices: ["SSH", + "LDAP", + "SMTP", + "FTP", + "HTTP", + "POP", + "NNTP", + "IMAP", + "TCP", + "Zabbix", + "SNMPv1", + "SNMPv2", + "ICMP", + "SNMPv3", + "HTTPS", + "Telnet"] ports: description: - One or several port ranges to check separated by commas. Used for all checks except for ICMP. @@ -173,23 +173,22 @@ options: type: str default: "enabled" choices: ["enabled", "disabled"] -notes: - - Only Zabbix >= 4.0 is supported. + extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 # Base create discovery rule example @@ -201,7 +200,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_discovery_rule: name: ACME @@ -224,7 +223,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_discovery_rule: name: ACME @@ -255,35 +254,35 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_discovery_rule: name: ACME state: absent -''' +""" -RETURN = r''' +RETURN = r""" state: description: Discovery rule state at the end of execution. returned: on success type: str - sample: 'present' + sample: "present" drule: description: Discovery rule name. returned: on success type: str - sample: 'ACME' + sample: "ACME" druleid: description: Discovery rule id. returned: on success type: str - sample: '42' + sample: "42" msg: description: The result of the operation returned: always type: str - sample: 'Discovery rule created: ACME, ID: 42' -''' + sample: "Discovery rule created: ACME, ID: 42" +""" from ansible.module_utils.basic import AnsibleModule @@ -312,72 +311,71 @@ class Dchecks(ZabbixBase): constructed_data = [] for check in _dchecks: constructed_check = { - 'type': zabbix_utils.helper_to_numeric_value([ - 'SSH', - 'LDAP', - 'SMTP', - 'FTP', - 'HTTP', - 'POP', - 'NNTP', - 'IMAP', - 'TCP', - 'Zabbix', - 'SNMPv1', - 'SNMPv2', - 'ICMP', - 'SNMPv3', - 'HTTPS', - 'Telnet'], check.get('type') + "type": zabbix_utils.helper_to_numeric_value([ + "SSH", + "LDAP", + "SMTP", + "FTP", + "HTTP", + "POP", + "NNTP", + "IMAP", + "TCP", + "Zabbix", + "SNMPv1", + "SNMPv2", + "ICMP", + "SNMPv3", + "HTTPS", + "Telnet"], check.get("type") ), - 'uniq': int(check.get('uniq')) + "uniq": int(check.get("uniq")) } - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.4'): - constructed_check.update({ - 'host_source': zabbix_utils.helper_to_numeric_value([ - 'None', - 'DNS', - 'IP', - 'discovery'], check.get('host_source') - ), - 'name_source': zabbix_utils.helper_to_numeric_value([ - 'None', - 'DNS', - 'IP', - 'discovery'], check.get('name_source') - ) - }) - if constructed_check['type'] in (0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15): - constructed_check['ports'] = check.get('ports') - if constructed_check['type'] == 9: - constructed_check['ports'] = check.get('ports') - constructed_check['key_'] = check.get('key') - if constructed_check['type'] in (10, 11): - constructed_check['ports'] = check.get('ports') - constructed_check['snmp_community'] = check.get('snmp_community') - constructed_check['key_'] = check.get('key') - if constructed_check['type'] == 13: - constructed_check['ports'] = check.get('ports') - constructed_check['key_'] = check.get('key') - constructed_check['snmpv3_contextname'] = check.get('snmpv3_contextname') - constructed_check['snmpv3_securityname'] = check.get('snmpv3_securityname') - constructed_check['snmpv3_securitylevel'] = zabbix_utils.helper_to_numeric_value([ - 'noAuthNoPriv', - 'authNoPriv', - 'authPriv'], check.get('snmpv3_securitylevel') + constructed_check.update({ + "host_source": zabbix_utils.helper_to_numeric_value([ + "None", + "DNS", + "IP", + "discovery"], check.get("host_source") + ), + "name_source": zabbix_utils.helper_to_numeric_value([ + "None", + "DNS", + "IP", + "discovery"], check.get("name_source") + ) + }) + if constructed_check["type"] in (0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15): + constructed_check["ports"] = check.get("ports") + if constructed_check["type"] == 9: + constructed_check["ports"] = check.get("ports") + constructed_check["key_"] = check.get("key") + if constructed_check["type"] in (10, 11): + constructed_check["ports"] = check.get("ports") + constructed_check["snmp_community"] = check.get("snmp_community") + constructed_check["key_"] = check.get("key") + if constructed_check["type"] == 13: + constructed_check["ports"] = check.get("ports") + constructed_check["key_"] = check.get("key") + constructed_check["snmpv3_contextname"] = check.get("snmpv3_contextname") + constructed_check["snmpv3_securityname"] = check.get("snmpv3_securityname") + constructed_check["snmpv3_securitylevel"] = zabbix_utils.helper_to_numeric_value([ + "noAuthNoPriv", + "authNoPriv", + "authPriv"], check.get("snmpv3_securitylevel") ) - if constructed_check['snmpv3_securitylevel'] in (1, 2): - constructed_check['snmpv3_authprotocol'] = zabbix_utils.helper_to_numeric_value([ - 'MD5', - 'SHA'], check.get('snmpv3_authprotocol') + if constructed_check["snmpv3_securitylevel"] in (1, 2): + constructed_check["snmpv3_authprotocol"] = zabbix_utils.helper_to_numeric_value([ + "MD5", + "SHA"], check.get("snmpv3_authprotocol") ) - constructed_check['snmpv3_authpassphrase'] = check.get('snmpv3_authpassphrase') - if constructed_check['snmpv3_securitylevel'] == 2: - constructed_check['snmpv3_privprotocol'] = zabbix_utils.helper_to_numeric_value([ - 'DES', - 'AES'], check.get('snmpv3_privprotocol') + constructed_check["snmpv3_authpassphrase"] = check.get("snmpv3_authpassphrase") + if constructed_check["snmpv3_securitylevel"] == 2: + constructed_check["snmpv3_privprotocol"] = zabbix_utils.helper_to_numeric_value([ + "DES", + "AES"], check.get("snmpv3_privprotocol") ) - constructed_check['snmpv3_privpassphrase'] = check.get('snmpv3_privpassphrase') + constructed_check["snmpv3_privpassphrase"] = check.get("snmpv3_privpassphrase") constructed_data.append(constructed_check) return zabbix_utils.helper_cleanup_data(constructed_data) @@ -392,9 +390,9 @@ class DiscoveryRule(ZabbixBase): """ try: _drule = self._zapi.drule.get({ - 'output': 'extend', - 'selectDChecks': 'extend', - 'filter': {'name': [name]} + "output": "extend", + "selectDChecks": "extend", + "filter": {"name": [name]} }) if len(_drule) > 0: return _drule @@ -411,9 +409,9 @@ class DiscoveryRule(ZabbixBase): """ try: drule_list = self._zapi.drule.get({ - 'output': 'extend', - 'selectDChecks': 'extend', - 'filter': {'name': [name]} + "output": "extend", + "selectDChecks": "extend", + "filter": {"name": [name]} }) if len(drule_list) < 1: self._module.fail_json(msg="Discovery rule not found: %s" % name) @@ -431,9 +429,9 @@ class DiscoveryRule(ZabbixBase): """ try: proxy_list = self._zapi.proxy.get({ - 'output': 'extend', - 'selectInterface': 'extend', - 'filter': {'host': [proxy_name]} + "output": "extend", + "selectInterface": "extend", + "filter": {"host": [proxy_name]} }) if len(proxy_list) < 1: self._module.fail_json(msg="Proxy not found: %s" % proxy_name) @@ -450,17 +448,17 @@ class DiscoveryRule(ZabbixBase): dict: dictionary of specified parameters """ _params = { - 'name': kwargs['name'], - 'iprange': ','.join(kwargs['iprange']), - 'delay': kwargs['delay'], - 'status': zabbix_utils.helper_to_numeric_value([ - 'enabled', - 'disabled'], kwargs['status'] + "name": kwargs["name"], + "iprange": ",".join(kwargs["iprange"]), + "delay": kwargs["delay"], + "status": zabbix_utils.helper_to_numeric_value([ + "enabled", + "disabled"], kwargs["status"] ), - 'dchecks': kwargs['dchecks'] + "dchecks": kwargs["dchecks"] } - if kwargs['proxy']: - _params['proxy_hostid'] = self.get_proxy_by_proxy_name(kwargs['proxy'])['proxyid'] + if kwargs["proxy"]: + _params["proxy_hostid"] = self.get_proxy_by_proxy_name(kwargs["proxy"])["proxyid"] return _params def check_difference(self, **kwargs): @@ -470,13 +468,13 @@ class DiscoveryRule(ZabbixBase): Returns: dict: dictionary of differences """ - existing_drule = zabbix_utils.helper_convert_unicode_to_str(self.check_if_drule_exists(kwargs['name'])[0]) + existing_drule = zabbix_utils.helper_convert_unicode_to_str(self.check_if_drule_exists(kwargs["name"])[0]) parameters = zabbix_utils.helper_convert_unicode_to_str(self._construct_parameters(**kwargs)) change_parameters = {} - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): - if existing_drule['nextcheck']: - existing_drule.pop('nextcheck') - _diff = zabbix_utils.helper_cleanup_data(compare_dictionaries(parameters, existing_drule, change_parameters)) + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): + if existing_drule["nextcheck"]: + existing_drule.pop("nextcheck") + _diff = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(parameters, existing_drule, change_parameters)) return _diff def update_drule(self, **kwargs): @@ -488,11 +486,11 @@ class DiscoveryRule(ZabbixBase): """ try: if self._module.check_mode: - self._module.exit_json(msg="Discovery rule would be updated if check mode was not specified: ID %s" % kwargs['drule_id'], changed=True) - kwargs['druleid'] = kwargs.pop('drule_id') + self._module.exit_json(msg="Discovery rule would be updated if check mode was not specified: ID %s" % kwargs["drule_id"], changed=True) + kwargs["druleid"] = kwargs.pop("drule_id") return self._zapi.drule.update(kwargs) except Exception as e: - self._module.fail_json(msg="Failed to update discovery rule ID '%s': %s" % (kwargs['drule_id'], e)) + self._module.fail_json(msg="Failed to update discovery rule ID '%s': %s" % (kwargs["drule_id"], e)) def add_drule(self, **kwargs): """Add discovery rule @@ -506,9 +504,9 @@ class DiscoveryRule(ZabbixBase): self._module.exit_json(msg="Discovery rule would be added if check mode was not specified", changed=True) parameters = self._construct_parameters(**kwargs) drule_list = self._zapi.drule.create(parameters) - return drule_list['druleids'][0] + return drule_list["druleids"][0] except Exception as e: - self._module.fail_json(msg="Failed to create discovery rule %s: %s" % (kwargs['name'], e)) + self._module.fail_json(msg="Failed to create discovery rule %s: %s" % (kwargs["name"], e)) def delete_drule(self, drule_id): """Delete discovery rule. @@ -525,159 +523,90 @@ class DiscoveryRule(ZabbixBase): self._module.fail_json(msg="Failed to delete discovery rule '%s': %s" % (drule_id, e)) -def compare_lists(l1, l2, diff_dict): - """ - Compares l1 and l2 lists and adds the items that are different - to the diff_dict dictionary. - Used in recursion with compare_dictionaries() function. - Args: - l1: first list to compare - l2: second list to compare - diff_dict: dictionary to store the difference - Returns: - dict: items that are different - """ - if len(l1) != len(l2): - diff_dict.append(l1) - return diff_dict - for i, item in enumerate(l1): - if isinstance(item, dict): - diff_dict.insert(i, {}) - diff_dict[i] = compare_dictionaries(item, l2[i], diff_dict[i]) - else: - if item != l2[i]: - diff_dict.append(item) - while {} in diff_dict: - diff_dict.remove({}) - return diff_dict - - -def compare_dictionaries(d1, d2, diff_dict): - """ - Compares d1 and d2 dictionaries and adds the items that are different - to the diff_dict dictionary. - Used in recursion with compare_lists() function. - Args: - d1: first dictionary to compare - d2: second dictionary to compare - diff_dict: dictionary to store the difference - Returns: - dict: items that are different - """ - for k, v in d1.items(): - if k not in d2: - diff_dict[k] = v - continue - if isinstance(v, dict): - diff_dict[k] = {} - compare_dictionaries(v, d2[k], diff_dict[k]) - if diff_dict[k] == {}: - del diff_dict[k] - else: - diff_dict[k] = v - elif isinstance(v, list): - diff_dict[k] = [] - compare_lists(v, d2[k], diff_dict[k]) - if diff_dict[k] == []: - del diff_dict[k] - else: - diff_dict[k] = v - else: - if v != d2[k]: - diff_dict[k] = v - return diff_dict - - def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update( - name=dict(type='str', required=True), - iprange=dict(type='list', required=False, elements='str'), + name=dict(type="str", required=True), + iprange=dict(type="list", required=False, elements="str"), dchecks=dict( - type='list', + type="list", required=False, - aliases=['dcheck'], - elements='dict', + aliases=["dcheck"], + elements="dict", options=dict( - type=dict(type='str', choices=[ - 'SSH', - 'LDAP', - 'SMTP', - 'FTP', - 'HTTP', - 'POP', - 'NNTP', - 'IMAP', - 'TCP', - 'Zabbix', - 'SNMPv1', - 'SNMPv2', - 'ICMP', - 'SNMPv3', - 'HTTPS', - 'Telnet'] + type=dict(type="str", choices=[ + "SSH", + "LDAP", + "SMTP", + "FTP", + "HTTP", + "POP", + "NNTP", + "IMAP", + "TCP", + "Zabbix", + "SNMPv1", + "SNMPv2", + "ICMP", + "SNMPv3", + "HTTPS", + "Telnet"] ), - ports=dict(type='str'), - key=dict(type='str', no_log=False), - snmp_community=dict(type='str'), - snmpv3_authpassphrase=dict(type='str', no_log=True), - snmpv3_authprotocol=dict(type='str', choices=['MD5', 'SHA']), - snmpv3_contextname=dict(type='str'), - snmpv3_privpassphrase=dict(type='str', no_log=True), - snmpv3_privprotocol=dict(type='str', choices=['DES', 'AES']), - snmpv3_securitylevel=dict(type='str', choices=['noAuthNoPriv', 'authNoPriv', 'authPriv']), - snmpv3_securityname=dict(type='str'), - uniq=dict(type='bool', default=False), - host_source=dict(type='str', choices=['DNS', 'IP', 'discovery'], default='DNS'), - name_source=dict(type='str', choices=['None', 'DNS', 'IP', 'discovery'], default='None') + ports=dict(type="str"), + key=dict(type="str", no_log=False), + snmp_community=dict(type="str"), + snmpv3_authpassphrase=dict(type="str", no_log=True), + snmpv3_authprotocol=dict(type="str", choices=["MD5", "SHA"]), + snmpv3_contextname=dict(type="str"), + snmpv3_privpassphrase=dict(type="str", no_log=True), + snmpv3_privprotocol=dict(type="str", choices=["DES", "AES"]), + snmpv3_securitylevel=dict(type="str", choices=["noAuthNoPriv", "authNoPriv", "authPriv"]), + snmpv3_securityname=dict(type="str"), + uniq=dict(type="bool", default=False), + host_source=dict(type="str", choices=["DNS", "IP", "discovery"], default="DNS"), + name_source=dict(type="str", choices=["None", "DNS", "IP", "discovery"], default="None") ), required_if=[ - ['type', 'SSH', ['ports']], - ['type', 'LDAP', ['ports']], - ['type', 'SMTP', ['ports']], - ['type', 'FTP', ['ports']], - ['type', 'HTTP', ['ports']], - ['type', 'POP', ['ports']], - ['type', 'NNTP', ['ports']], - ['type', 'IMAP', ['ports']], - ['type', 'TCP', ['ports']], - ['type', 'Zabbix', ['ports', 'key']], - ['type', 'SNMPv1', ['ports', 'key', 'snmp_community']], - ['type', 'SNMPv2', ['ports', 'key', 'snmp_community']], - ['type', 'SNMPv3', ['ports', 'key']], - ['type', 'HTTPS', ['ports']], - ['type', 'Telnet', ['ports']], - ['snmpv3_securitylevel', 'authPriv', ['snmpv3_privpassphrase']] + ["type", "SSH", ["ports"]], + ["type", "LDAP", ["ports"]], + ["type", "SMTP", ["ports"]], + ["type", "FTP", ["ports"]], + ["type", "HTTP", ["ports"]], + ["type", "POP", ["ports"]], + ["type", "NNTP", ["ports"]], + ["type", "IMAP", ["ports"]], + ["type", "TCP", ["ports"]], + ["type", "Zabbix", ["ports", "key"]], + ["type", "SNMPv1", ["ports", "key", "snmp_community"]], + ["type", "SNMPv2", ["ports", "key", "snmp_community"]], + ["type", "SNMPv3", ["ports", "key"]], + ["type", "HTTPS", ["ports"]], + ["type", "Telnet", ["ports"]], + ["snmpv3_securitylevel", "authPriv", ["snmpv3_privpassphrase"]] ] ), - delay=dict(type='str', required=False, default='1h'), - proxy=dict(type='str', required=False, default=None), - status=dict(type='str', default="enabled", choices=["enabled", "disabled"]), - state=dict(type='str', default='present', choices=['present', 'absent']) + delay=dict(type="str", required=False, default="1h"), + proxy=dict(type="str", required=False, default=None), + status=dict(type="str", default="enabled", choices=["enabled", "disabled"]), + state=dict(type="str", default="present", choices=["present", "absent"]) ) module = AnsibleModule( argument_spec=argument_spec, required_if=[ - ['state', 'present', ['name', 'iprange', 'dchecks']], - ['state', 'absent', ['name']], + ["state", "present", ["name", "iprange", "dchecks"]], + ["state", "absent", ["name"]], ], supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - state = module.params['state'] - name = module.params['name'] - iprange = module.params['iprange'] - dchecks = module.params['dchecks'] - delay = module.params['delay'] - proxy = module.params['proxy'] - status = module.params['status'] + state = module.params["state"] + name = module.params["name"] + iprange = module.params["iprange"] + dchecks = module.params["dchecks"] + delay = module.params["delay"] + proxy = module.params["proxy"] + status = module.params["status"] drule = DiscoveryRule(module) zbx = drule._zapi @@ -686,7 +615,7 @@ def main(): drule_exists = drule.check_if_drule_exists(name) if drule_exists: - drule_id = drule.get_drule_by_drule_name(name)['druleid'] + drule_id = drule.get_drule_by_drule_name(name)["druleid"] if state == "absent": drule.delete_drule(drule_id) module.exit_json(changed=True, state=state, drule=name, druleid=drule_id, msg="Discovery Rule deleted: %s, ID: %s" % (name, drule_id)) @@ -724,5 +653,5 @@ def main(): module.exit_json(changed=True, state=state, drule=name, druleid=drule_id, msg="Discovery Rule created: %s, ID: %s" % (name, drule_id)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_globalmacro.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_globalmacro.py index d0221223b..111c80c55 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_globalmacro.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_globalmacro.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_globalmacro short_description: Create/update/delete Zabbix Global macros @@ -21,7 +21,7 @@ author: - Dean Hailin Song (!UNKNOWN) - Timothy Test (@ttestscripting) requirements: - - "python >= 2.6" + - "python >= 3.9" options: macro_name: description: @@ -46,42 +46,41 @@ options: macro_description: description: - Text Description of the global macro. - - Works only with Zabbix >= 4.4 and is silently ignored in lower versions type: str - default: '' + default: "" state: description: - State of the macro. - On C(present), it will create if macro does not exist or update the macro if the associated data is different. - On C(absent) will remove a macro if it exists. required: false - choices: ['present', 'absent'] + choices: ["present", "absent"] type: str default: "present" force: description: - Only updates an existing macro if set to C(yes). - default: 'yes' + default: "yes" type: bool notes: - - This module returns changed=true when I(macro_type=secret) with Zabbix >= 5.0. + - This module returns changed=true when I(macro_type=secret). extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create new global macro or update an existing macro's value @@ -92,7 +91,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_globalmacro: macro_name: EXAMPLE.MACRO @@ -109,7 +108,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_globalmacro: macro_name: "{$EXAMPLE.MACRO}" @@ -121,7 +120,7 @@ EXAMPLES = r''' community.zabbix.zabbix_globalmacro: macro_name: "{$EXAMPLE.MACRO}" state: absent -''' +""" RETURN = r""" """ @@ -130,7 +129,6 @@ RETURN = r""" from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils @@ -139,8 +137,8 @@ class GlobalMacro(ZabbixBase): # get global macro def get_global_macro(self, macro_name): try: - all_global_macro_list = self._zapi.usermacro.get({"globalmacro": 'true'}) - global_macro_list = [d for d in all_global_macro_list if d['macro'] == macro_name] + all_global_macro_list = self._zapi.usermacro.get({"globalmacro": "true"}) + global_macro_list = [d for d in all_global_macro_list if d["macro"] == macro_name] if len(global_macro_list) > 0: return global_macro_list[0] return None @@ -152,61 +150,30 @@ class GlobalMacro(ZabbixBase): try: if self._module.check_mode: self._module.exit_json(changed=True) - if LooseVersion(self._zbx_api_version) < LooseVersion('4.4.0'): - self._zapi.usermacro.createglobal({'macro': macro_name, 'value': macro_value}) - self._module.exit_json(changed=True, result="Successfully added global macro %s" % macro_name) - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.4.0'): - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0.0'): - if LooseVersion(self._zbx_api_version) < LooseVersion('5.2.0'): - if macro_type == '2': - macro_type = '0' - self._zapi.usermacro.createglobal({'macro': macro_name, 'value': macro_value, 'type': macro_type, 'description': macro_description}) - self._module.exit_json(changed=True, result="Successfully added global macro %s" % macro_name) - else: - self._zapi.usermacro.createglobal({'macro': macro_name, 'value': macro_value, 'description': macro_description}) - self._module.exit_json(changed=True, result="Successfully added global macro %s" % macro_name) + self._zapi.usermacro.createglobal({"macro": macro_name, "value": macro_value, "type": macro_type, "description": macro_description}) + self._module.exit_json(changed=True, result="Successfully added global macro %s" % macro_name) except Exception as e: self._module.fail_json(msg="Failed to create global macro %s: %s" % (macro_name, e)) # update global macro def update_global_macro(self, global_macro_obj, macro_name, macro_value, macro_type, macro_description): - global_macro_id = global_macro_obj['globalmacroid'] + global_macro_id = global_macro_obj["globalmacroid"] try: - if LooseVersion(self._zbx_api_version) < LooseVersion('4.4.0'): - if global_macro_obj['macro'] == macro_name and global_macro_obj['value'] == macro_value: + if global_macro_obj["type"] == "0" or global_macro_obj["type"] == "2": + if (global_macro_obj["macro"] == macro_name and global_macro_obj["value"] == macro_value + and global_macro_obj["type"] == macro_type and global_macro_obj["description"] == macro_description): self._module.exit_json(changed=False, result="Global macro %s already up to date" % macro_name) - if self._module.check_mode: - self._module.exit_json(changed=True) - self._zapi.usermacro.updateglobal({'globalmacroid': global_macro_id, 'macro': macro_name, 'value': macro_value}) - self._module.exit_json(changed=True, result="Successfully updated global macro %s" % macro_name) - elif LooseVersion(self._zbx_api_version) >= LooseVersion('5.0.0'): - if LooseVersion(self._zbx_api_version) < LooseVersion('5.2.0'): - if macro_type == '2': - macro_type = '0' - if global_macro_obj['type'] == '0' or global_macro_obj['type'] == '2': - if (global_macro_obj['macro'] == macro_name and global_macro_obj['value'] == macro_value - and global_macro_obj['type'] == macro_type and global_macro_obj['description'] == macro_description): - self._module.exit_json(changed=False, result="Global macro %s already up to date" % macro_name) - if self._module.check_mode: - self._module.exit_json(changed=True) - self._zapi.usermacro.updateglobal({'globalmacroid': global_macro_id, 'macro': macro_name, - 'value': macro_value, 'type': macro_type, 'description': macro_description}) - self._module.exit_json(changed=True, result="Successfully updated global macro %s" % macro_name) - else: - if (global_macro_obj['macro'] == macro_name and global_macro_obj['value'] == macro_value - and global_macro_obj['description'] == macro_description): - self._module.exit_json(changed=False, result="Global macro %s already up to date" % macro_name) - if self._module.check_mode: - self._module.exit_json(changed=True) - self._zapi.usermacro.updateglobal({'globalmacroid': global_macro_id, 'macro': macro_name, - 'value': macro_value, 'description': macro_description}) - self._module.exit_json(changed=True, result="Successfully updated global macro %s" % macro_name) + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.usermacro.updateglobal({"globalmacroid": global_macro_id, "macro": macro_name, + "value": macro_value, "type": macro_type, "description": macro_description}) + self._module.exit_json(changed=True, result="Successfully updated global macro %s" % macro_name) except Exception as e: self._module.fail_json(msg="Failed to update global macro %s: %s" % (macro_name, e)) # delete global macro def delete_global_macro(self, global_macro_obj, macro_name): - global_macro_id = global_macro_obj['globalmacroid'] + global_macro_id = global_macro_obj["globalmacroid"] try: if self._module.check_mode: self._module.exit_json(changed=True) @@ -218,16 +185,16 @@ class GlobalMacro(ZabbixBase): def normalize_macro_name(macro_name): # Zabbix handles macro names in upper case characters - if ':' in macro_name: - macro_name = ':'.join([macro_name.split(':')[0].upper(), ':'.join(macro_name.split(':')[1:])]) + if ":" in macro_name: + macro_name = ":".join([macro_name.split(":")[0].upper(), ":".join(macro_name.split(":")[1:])]) else: macro_name = macro_name.upper() # Valid format for macro is {$MACRO} - if not macro_name.startswith('{$'): - macro_name = '{$' + macro_name - if not macro_name.endswith('}'): - macro_name = macro_name + '}' + if not macro_name.startswith("{$"): + macro_name = "{$" + macro_name + if not macro_name.endswith("}"): + macro_name = macro_name + "}" return macro_name @@ -235,48 +202,42 @@ def normalize_macro_name(macro_name): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - macro_name=dict(type='str', required=True), - macro_value=dict(type='str', required=False, no_log=True), - macro_type=dict(type='str', default='text', choices=['text', 'secret', 'vault']), - macro_description=dict(type='str', default=''), - state=dict(type='str', default='present', choices=['present', 'absent']), - force=dict(type='bool', default=True) + macro_name=dict(type="str", required=True), + macro_value=dict(type="str", required=False, no_log=True), + macro_type=dict(type="str", default="text", choices=["text", "secret", "vault"]), + macro_description=dict(type="str", default=""), + state=dict(type="str", default="present", choices=["present", "absent"]), + force=dict(type="bool", default=True) )) module = AnsibleModule( argument_spec=argument_spec, required_if=[ - ['state', 'present', ['macro_value']] + ["state", "present", ["macro_value"]] ], supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - macro_name = normalize_macro_name(module.params['macro_name']) - macro_value = module.params['macro_value'] - macro_type = module.params['macro_type'] - macro_value = module.params['macro_value'] - macro_description = module.params['macro_description'] - state = module.params['state'] - force = module.params['force'] - - if macro_type == 'text': - macro_type = '0' - elif macro_type == 'secret': - macro_type = '1' - elif macro_type == 'vault': - macro_type = '2' + macro_name = normalize_macro_name(module.params["macro_name"]) + macro_value = module.params["macro_value"] + macro_type = module.params["macro_type"] + macro_value = module.params["macro_value"] + macro_description = module.params["macro_description"] + state = module.params["state"] + force = module.params["force"] + + if macro_type == "text": + macro_type = "0" + elif macro_type == "secret": + macro_type = "1" + elif macro_type == "vault": + macro_type = "2" global_macro_class_obj = GlobalMacro(module) if macro_name: global_macro_obj = global_macro_class_obj.get_global_macro(macro_name) - if state == 'absent': + if state == "absent": if not global_macro_obj: module.exit_json(changed=False, msg="Global Macro %s does not exist" % macro_name) else: @@ -293,5 +254,5 @@ def main(): module.exit_json(changed=False, result="Global macro %s already exists and force is set to no" % macro_name) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_group.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_group.py index 0426f9336..3eb39ab24 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_group.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_group.py @@ -47,14 +47,14 @@ notes: EXAMPLES = r''' # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 # Base create host groups example @@ -94,17 +94,6 @@ EXAMPLES = r''' ''' -import traceback - -try: - from zabbix_api import Already_Exists - - HAS_ZABBIX_API = True - ZBX_IMP_ERR = Exception() -except ImportError: - ZBX_IMP_ERR = traceback.format_exc() - HAS_ZABBIX_API = False - from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase @@ -119,13 +108,10 @@ class HostGroup(ZabbixBase): for group_name in group_names: result = self._zapi.hostgroup.get({'filter': {'name': group_name}}) if not result: - try: - if self._module.check_mode: - self._module.exit_json(changed=True) - self._zapi.hostgroup.create({'name': group_name}) - group_add_list.append(group_name) - except Already_Exists: - return group_add_list + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.hostgroup.create({'name': group_name}) + group_add_list.append(group_name) return group_add_list except Exception as e: self._module.fail_json(msg="Failed to create host group(s): %s" % e) @@ -153,7 +139,7 @@ class HostGroup(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - host_groups=dict(type='list', required=True, aliases=['host_group']), + host_groups=dict(type='list', required=True, aliases=['host_group'], elements='str'), state=dict(type='str', default="present", choices=['present', 'absent']), )) module = AnsibleModule( @@ -161,12 +147,6 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password']: - if p in module.params and module.params[p] and module.params[p]: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - host_groups = module.params['host_groups'] state = module.params['state'] diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_group_events_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_group_events_info.py new file mode 100644 index 000000000..e41cab26f --- /dev/null +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_group_events_info.py @@ -0,0 +1,283 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# built by Martin Eiswirth (@meis4h) on top of the work by Stéphane Travassac (@stravassac) on zabbix_host_events_info.py +# and Michael Miko (@RedWhiteMiko) on zabbix_group_info.py +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +from __future__ import (absolute_import, division, print_function) + +__metaclass__ = type + +RETURN = """ +--- +triggers_ok: + description: Zabbix Triggers in OK state + returned: On success + type: complex + contains: + comments: + description: Additional description of the trigger + type: str + description: + description: Name of the trigger + type: str + error: + description: Error text if there have been any problems when updating the state of the trigger + type: str + expression: + description: Reduced trigger expression + type: str + flags: + description: Origin of the trigger + type: int + lastchange: + description: Time when the trigger last changed its state (timestamp) + type: int + priority: + description: Severity of the trigger + type: int + state: + description: State of the trigger + type: int + status: + description: Whether the trigger is enabled or disabled + type: int + templateid: + description: ID of the parent template trigger + type: int + triggerid: + description: ID of the trigger + type: int + type: + description: Whether the trigger can generate multiple problem events + type: int + url: + description: URL associated with the trigger + type: str + value: + description: Whether the trigger is in OK or problem state + type: int +triggers_problem: + description: Zabbix Triggers in problem state. See trigger and event objects in API documentation of your zabbix version for more + returned: On success + type: complex + contains: + comments: + description: Additional description of the trigger + type: str + description: + description: Name of the trigger + type: str + error: + description: Error text if there have been any problems when updating the state of the trigger + type: str + expression: + description: Reduced trigger expression + type: str + flags: + description: Origin of the trigger + type: int + last_event: + description: last event informations + type: complex + contains: + acknowledged: + description: If set to true return only acknowledged events + type: int + acknowledges: + description: acknowledges informations + type: complex + contains: + alias: + description: Account who acknowledge + type: str + clock: + description: Time when the event was created (timestamp) + type: int + message: + description: Text of the acknowledgement message + type: str + clock: + description: Time when the event was created (timestamp) + type: int + eventid: + description: ID of the event + type: int + value: + description: State of the related object + type: int + lastchange: + description: Time when the trigger last changed its state (timestamp) + type: int + priority: + description: Severity of the trigger + type: int + state: + description: State of the trigger + type: int + status: + description: Whether the trigger is enabled or disabled + type: int + templateid: + description: ID of the parent template trigger + type: int + triggerid: + description: ID of the trigger + type: int + type: + description: Whether the trigger can generate multiple problem events + type: int + url: + description: URL associated with the trigger + type: str + value: + description: Whether the trigger is in OK or problem state + type: int +""" + +DOCUMENTATION = """ +--- +module: zabbix_group_events_info +short_description: Get all triggers about a Zabbix group +description: + - This module allows you to check the state of triggers of all hosts in a Zabbix hostgroup. +author: + - "Martin Eiswirth (@meis4h)" +requirements: + - "python >= 3.9" +options: + hostgroup_name: + description: + - Name of the hostgroup in Zabbix. + required: true + type: list + elements: str + trigger_severity: + description: + - Zabbix severity for search filter + default: average + required: false + choices: + - not_classified + - information + - warning + - average + - high + - disaster + type: str +extends_documentation_fragment: +- community.zabbix.zabbix + +""" + +EXAMPLES = """ +# If you want to use Username and Password to be authenticated by Zabbix Server +- name: Set credentials to access Zabbix Server API + set_fact: + ansible_user: Admin + ansible_httpapi_pass: zabbix + +# If you want to use API token to be authenticated by Zabbix Server +# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens +- name: Set API token + set_fact: + ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 + +- name: Fail if alert active in hostgroup + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_group_events_info: + hostgroup_name: "{{ inventory_hostname }}" + register: zbx_hostgroup + delegate_to: localhost +- fail: + msg: "Active alert in zabbix" + when: zbx_hostgroup["triggers_problem"] | length > 0 +""" + + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase +import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils + + +class Host(ZabbixBase): + def get_group_ids_by_group_names(self, group_names): + group_list = self._zapi.hostgroup.get({"output": "extend", "filter": {"name": group_names}}) + if len(group_list) < 1: + self._module.fail_json(msg="Hostgroup not found: %s" % group_names) + return group_list + + def get_triggers_by_group_id_in_problem_state(self, group_id, trigger_severity): + """ Get triggers in problem state from a groupid""" + output = "extend" + triggers_list = self._zapi.trigger.get({"output": output, "groupids": group_id, + "min_severity": trigger_severity}) + return triggers_list + + def get_last_event_by_trigger_id(self, triggers_id): + """ Get the last event from triggerid""" + output = ["eventid", "clock", "acknowledged", "value"] + select_acknowledges = ["clock", "alias", "message"] + event = self._zapi.event.get({"output": output, "objectids": triggers_id, + "select_acknowledges": select_acknowledges, "limit": 1, "sortfield": "clock", + "sortorder": "DESC"}) + return event[0] + + +def main(): + argument_spec = zabbix_utils.zabbix_common_argument_spec() + argument_spec.update(dict( + hostgroup_name=dict(type="list", required=True, elements="str"), + trigger_severity=dict( + type="str", + required=False, + default="average", + choices=["not_classified", "information", "warning", "average", "high", "disaster"]), + )) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True + ) + + trigger_severity_map = {"not_classified": 0, "information": 1, "warning": 2, "average": 3, "high": 4, "disaster": 5} + trigger_severity = trigger_severity_map[module.params["trigger_severity"]] + + hostgroup_name = module.params["hostgroup_name"] + + host = Host(module) + host_groups = host.get_group_ids_by_group_names(hostgroup_name) + triggers = [] + + for host_group in host_groups: + host_group_id = host_group["groupid"] + host_group_triggers = host.get_triggers_by_group_id_in_problem_state(host_group_id, trigger_severity) + triggers = triggers + host_group_triggers + + triggers_ok = [] + triggers_problem = [] + for trigger in triggers: + # tGet last event for trigger with problem value = 1 + # https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/object + if int(trigger["value"]) == 1: + event = host.get_last_event_by_trigger_id(trigger["triggerid"]) + trigger["last_event"] = event + triggers_problem.append(trigger) + else: + triggers_ok.append(trigger) + + module.exit_json(ok=True, host_groups=host_groups, triggers_ok=triggers_ok, triggers_problem=triggers_problem) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_group_facts.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_group_facts.py deleted file mode 100644 index b3f693052..000000000 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_group_facts.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) me@mimiko.me -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -from __future__ import absolute_import, division, print_function -__metaclass__ = type - - -RETURN = r''' ---- -host_groups: - description: List of Zabbix groups. - returned: success - type: dict - sample: [ { "flags": "0", "groupid": "33", "internal": "0", "name": "Hostgruup A" } ] -''' - -DOCUMENTATION = r''' ---- -module: zabbix_group_info -short_description: Gather information about Zabbix hostgroup -description: - - This module allows you to search for Zabbix hostgroup entries. - - This module was called C(zabbix_group_facts) before Ansible 2.9. The usage did not change. -author: - - "Michael Miko (@RedWhiteMiko)" -requirements: - - "python >= 2.6" -options: - hostgroup_name: - description: - - Name of the hostgroup in Zabbix. - - hostgroup is the unique identifier used and cannot be updated using this module. - required: true - type: list - elements: str - -extends_documentation_fragment: -- community.zabbix.zabbix -''' - -EXAMPLES = r''' -# If you want to use Username and Password to be authenticated by Zabbix Server -- name: Set credentials to access Zabbix Server API - set_fact: - ansible_user: Admin - ansible_httpapi_pass: zabbix - -# If you want to use API token to be authenticated by Zabbix Server -# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens -- name: Set API token - set_fact: - ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - -- name: Get hostgroup info - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_group_info: - hostgroup_name: - - ExampleHostgroup - timeout: 10 -''' - -from ansible.module_utils.basic import AnsibleModule - -from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils - - -class Host(ZabbixBase): - def get_group_ids_by_group_names(self, group_names): - group_list = self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': group_names}}) - if len(group_list) < 1: - self._module.fail_json(msg="Hostgroup not found: %s" % group_names) - return group_list - - -def main(): - argument_spec = zabbix_utils.zabbix_common_argument_spec() - argument_spec.update(dict( - hostgroup_name=dict(type='list', required=True), - )) - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True - ) - - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - if module._name == 'zabbix_group_facts': - module.deprecate("The 'zabbix_group_facts' module has been renamed to 'zabbix_group_info'", - collection_name="community.zabbix", version='2.0.0') # was 2.13 - - hostgroup_name = module.params['hostgroup_name'] - - host = Host(module) - host_groups = host.get_group_ids_by_group_names(hostgroup_name) - module.exit_json(host_groups=host_groups) - - -if __name__ == '__main__': - main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_group_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_group_info.py index b3f693052..02784c366 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_group_info.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_group_info.py @@ -8,16 +8,16 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -RETURN = r''' +RETURN = r""" --- host_groups: description: List of Zabbix groups. returned: success type: dict sample: [ { "flags": "0", "groupid": "33", "internal": "0", "name": "Hostgruup A" } ] -''' +""" -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_group_info short_description: Gather information about Zabbix hostgroup @@ -27,7 +27,7 @@ description: author: - "Michael Miko (@RedWhiteMiko)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: hostgroup_name: description: @@ -39,19 +39,19 @@ options: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Get hostgroup info @@ -62,13 +62,12 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_group_info: hostgroup_name: - ExampleHostgroup - timeout: 10 -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -78,7 +77,7 @@ import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabb class Host(ZabbixBase): def get_group_ids_by_group_names(self, group_names): - group_list = self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': group_names}}) + group_list = self._zapi.hostgroup.get({"output": "extend", "filter": {"name": group_names}}) if len(group_list) < 1: self._module.fail_json(msg="Hostgroup not found: %s" % group_names) return group_list @@ -87,29 +86,19 @@ class Host(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - hostgroup_name=dict(type='list', required=True), + hostgroup_name=dict(type="list", required=True, elements="str"), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - if module._name == 'zabbix_group_facts': - module.deprecate("The 'zabbix_group_facts' module has been renamed to 'zabbix_group_info'", - collection_name="community.zabbix", version='2.0.0') # was 2.13 - - hostgroup_name = module.params['hostgroup_name'] + hostgroup_name = module.params["hostgroup_name"] host = Host(module) host_groups = host.get_group_ids_by_group_names(hostgroup_name) module.exit_json(host_groups=host_groups) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_host.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_host.py index c43742378..22e14d17d 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_host.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_host.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_host short_description: Create/update/delete Zabbix hosts @@ -21,7 +21,7 @@ author: - Werner Dijkerman (@dj-wasabi) - Eike Frost (@eikef) requirements: - - "python >= 2.6" + - "python >= 3.9" options: host_name: description: @@ -51,27 +51,27 @@ options: inventory_mode: description: - Configure the inventory mode. - choices: ['automatic', 'manual', 'disabled'] + choices: ["automatic", "manual", "disabled"] type: str inventory_zabbix: description: - Add Facts for a zabbix inventory (e.g. Tag) (see example below). - Please review the interface documentation for more information on the supported properties - - U(https://www.zabbix.com/documentation/3.2/manual/api/reference/host/object#host_inventory) + - U(https://www.zabbix.com/documentation/current/en/manual/api/reference/host/object#host-inventory) type: dict status: description: - Monitoring status of the host. - choices: ['enabled', 'disabled'] - default: 'enabled' + choices: ["enabled", "disabled"] + default: "enabled" type: str state: description: - State of the host. - On C(present), it will create if host does not exist or update the host if the associated data is different. - On C(absent) will remove a host if it exists. - choices: ['present', 'absent'] - default: 'present' + choices: ["present", "absent"] + default: "present" type: str proxy: description: @@ -83,7 +83,7 @@ options: description: - List of interfaces to be created for the host (see example below). - For more information, review host interface documentation at - - U(https://www.zabbix.com/documentation/4.0/manual/api/reference/hostinterface/object) + - U(https://www.zabbix.com/documentation/current/en/manual/api/reference/hostinterface/object#host-interface) default: [] suboptions: type: @@ -95,7 +95,7 @@ options: - 2 = snmp - 3 = ipmi - 4 = jmx - choices: ['agent', '1', 'snmp', '2', 'ipmi', '3', 'jmx', '4'] + choices: ["agent", "1", "snmp", "2", "ipmi", "3", "jmx", "4"] required: true main: type: int @@ -127,26 +127,15 @@ options: description: - Port used by host interface. - If not specified, default port for each type of interface is used - - 10050 if I(type='agent') - - 161 if I(type='snmp') - - 623 if I(type='ipmi') - - 12345 if I(type='jmx') - bulk: - type: int - description: - - Whether to use bulk SNMP requests. - - Only valid when interface I(type='snmp'). - - 0 (don't use bulk requests), 1 (use bulk requests) - - Works only with Zabbix <= 4.4 and is silently ignored in higher versions. - - Use I(details) with Zabbix >= 5.0. - choices: [0, 1] - default: 1 + - 10050 if I(type="agent") + - 161 if I(type="snmp") + - 623 if I(type="ipmi") + - 12345 if I(type="jmx") details: type: dict description: - Additional details for SNMP host interfaces. - - Required when I(type='snmp'). - - Works only with Zabbix >= 5.0. + - Required when I(type="snmp"). default: {} suboptions: version: @@ -168,17 +157,17 @@ options: description: - SNMPv1 and SNMPv2 community string. - Required when I(version=1) or I(version=2). - default: '' + default: "" securityname: type: str description: - SNMPv3 security name. - default: '' + default: "" contextname: type: str description: - SNMPv3 context name. - default: '' + default: "" securitylevel: type: int description: @@ -200,7 +189,7 @@ options: description: - SNMPv3 authentication passphrase. - Used when I(securitylevel=1)(authNoPriv) or I(securitylevel=2)(AuthPriv). - default: '' + default: "" privprotocol: type: int description: @@ -215,12 +204,11 @@ options: description: - SNMPv3 privacy passphrase. - Used when I(securitylevel=2)(AuthPriv). - default: '' + default: "" tls_connect: description: - Specifies what encryption to use for outgoing connections. - Possible values, 1 (no encryption), 2 (PSK), 4 (certificate). - - Works only with >= Zabbix 3.0 type: int tls_accept: description: @@ -228,7 +216,6 @@ options: - The tls_accept parameter accepts values of 1 to 7 - Possible values, 1 (no encryption), 2 (PSK), 4 (certificate). - Values can be combined. - - Works only with >= Zabbix 3.0 type: int tls_psk_identity: description: @@ -241,25 +228,22 @@ options: description: - PSK value is a hard to guess string of hexadecimal digits. - The preshared key, at least 32 hex digits. Required if either I(tls_connect) or I(tls_accept) has PSK enabled. - - Works only with >= Zabbix 3.0 - - Using this parameter with Zabbix >= 5.4 makes this module non-idempotent. + - Using this parameter makes this module non-idempotent. type: str ca_cert: description: - Required certificate issuer. - - Works only with >= Zabbix 3.0 aliases: [ tls_issuer ] type: str tls_subject: description: - Required certificate subject. - - Works only with >= Zabbix 3.0 type: str ipmi_authtype: description: - IPMI authentication algorithm. - Please review the Host object documentation for more information on the supported properties - - 'https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object' + - "https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object" - Possible values are, C(0) (none), C(1) (MD2), C(2) (MD5), C(4) (straight), C(5) (OEM), C(6) (RMCP+), with -1 being the API default. - Please note that the Zabbix API will treat absent settings as default when updating @@ -270,7 +254,7 @@ options: description: - IPMI privilege level. - Please review the Host object documentation for more information on the supported properties - - 'https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object' + - "https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object" - Possible values are C(1) (callback), C(2) (user), C(3) (operator), C(4) (admin), C(5) (OEM), with C(2) being the API default. - also see the last note in the I(ipmi_authtype) documentation @@ -289,7 +273,7 @@ options: description: - Overwrite the host configuration, even if already present. type: bool - default: 'yes' + default: "yes" macros: description: - List of user macros to assign to the zabbix host. @@ -311,14 +295,12 @@ options: description: description: - Description of the user macro. - - Works only with >= Zabbix 4.4. type: str required: false - default: '' + default: "" type: description: - Type of the macro. - - Works only with >= Zabbix 5.0. - Since value is not returned by API for secret macros, there is no reliable way to detect changes in the content of secret macro value. - To update secret macro value, please update description alongside it so it passes @@ -331,7 +313,6 @@ options: tags: description: - List of host tags to assign to the zabbix host. - - Works only with >= Zabbix 4.2. - Providing I(tags=[]) with I(force=yes) will clean all of the tags from the host. type: list elements: dict @@ -345,25 +326,25 @@ options: description: - Value of the host tag. type: str - default: '' + default: "" aliases: [ host_tags ] extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create a new host or rewrite an existing host's info @@ -374,7 +355,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu become: false delegate_to: zabbix-example-fqdn.org# you can use delegate_to or task level ansible_host like next example community.zabbix.zabbix_host: @@ -417,7 +398,7 @@ EXAMPLES = r''' port: "12345" proxy: a.zabbix.proxy macros: - - macro: '{$EXAMPLEMACRO}' + - macro: "{$EXAMPLEMACRO}" value: ExampleMacroValue - macro: EXAMPLEMACRO2 value: ExampleMacroValue2 @@ -435,7 +416,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org # you can use task level ansible_host or delegate_to like in previous example become: false community.zabbix.zabbix_host: @@ -447,7 +428,7 @@ EXAMPLES = r''' tls_connect: 2 tls_psk: 123456789abcdef123456789abcdef12 force: false -''' +""" import copy @@ -455,7 +436,6 @@ import copy from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils @@ -463,13 +443,13 @@ import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabb class Host(ZabbixBase): # exist host def is_host_exist(self, host_name): - result = self._zapi.host.get({'filter': {'host': host_name}}) + result = self._zapi.host.get({"filter": {"host": host_name}}) return result # check if host group exists def check_host_group_exist(self, group_names): for group_name in group_names: - result = self._zapi.hostgroup.get({'filter': {'name': group_name}}) + result = self._zapi.hostgroup.get({"filter": {"name": group_name}}) if not result: self._module.fail_json(msg="Hostgroup not found: %s" % group_name) return True @@ -479,11 +459,11 @@ class Host(ZabbixBase): if template_list is None or len(template_list) == 0: return template_ids for template in template_list: - template_list = self._zapi.template.get({'output': 'extend', 'filter': {'host': template}}) + template_list = self._zapi.template.get({"output": "extend", "filter": {"host": template}}) if len(template_list) < 1: self._module.fail_json(msg="Template not found: %s" % template) else: - template_id = template_list[0]['templateid'] + template_id = template_list[0]["templateid"] template_ids.append(template_id) return template_ids @@ -493,83 +473,88 @@ class Host(ZabbixBase): try: if self._module.check_mode: self._module.exit_json(changed=True) - parameters = {'host': host_name, 'interfaces': interfaces, 'groups': group_ids, 'status': status} + parameters = {"host": host_name, "interfaces": interfaces, "groups": group_ids, "status": status} if proxy_id: - parameters['proxy_hostid'] = proxy_id + parameters["proxy_hostid"] = proxy_id if visible_name: - parameters['name'] = visible_name + parameters["name"] = visible_name if tls_connect: - parameters['tls_connect'] = tls_connect + parameters["tls_connect"] = tls_connect if tls_accept: - parameters['tls_accept'] = tls_accept + parameters["tls_accept"] = tls_accept if tls_psk_identity is not None: - parameters['tls_psk_identity'] = tls_psk_identity + parameters["tls_psk_identity"] = tls_psk_identity if tls_psk is not None: - parameters['tls_psk'] = tls_psk + parameters["tls_psk"] = tls_psk if tls_issuer is not None: - parameters['tls_issuer'] = tls_issuer + parameters["tls_issuer"] = tls_issuer if tls_subject is not None: - parameters['tls_subject'] = tls_subject + parameters["tls_subject"] = tls_subject if description: - parameters['description'] = description + parameters["description"] = description if ipmi_authtype is not None: - parameters['ipmi_authtype'] = ipmi_authtype + parameters["ipmi_authtype"] = ipmi_authtype if ipmi_privilege is not None: - parameters['ipmi_privilege'] = ipmi_privilege + parameters["ipmi_privilege"] = ipmi_privilege if ipmi_username is not None: - parameters['ipmi_username'] = ipmi_username + parameters["ipmi_username"] = ipmi_username if ipmi_password is not None: - parameters['ipmi_password'] = ipmi_password + parameters["ipmi_password"] = ipmi_password if macros is not None: - parameters['macros'] = macros + parameters["macros"] = macros if tags is not None: - parameters['tags'] = tags + parameters["tags"] = tags host_list = self._zapi.host.create(parameters) if len(host_list) >= 1: - return host_list['hostids'][0] + return host_list["hostids"][0] except Exception as e: self._module.fail_json(msg="Failed to create host %s: %s" % (host_name, e)) def update_host(self, host_name, group_ids, status, host_id, interfaces, exist_interface_list, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, - tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, macros, tags): + tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, macros, tags, discovered_host): try: if self._module.check_mode: self._module.exit_json(changed=True) - parameters = {'hostid': host_id, 'groups': group_ids, 'status': status} - if proxy_id >= 0: - parameters['proxy_hostid'] = proxy_id - if visible_name: - parameters['name'] = visible_name - if tls_connect: - parameters['tls_connect'] = tls_connect - if tls_accept: - parameters['tls_accept'] = tls_accept - if tls_psk_identity: - parameters['tls_psk_identity'] = tls_psk_identity - if tls_psk: - parameters['tls_psk'] = tls_psk - if tls_issuer: - parameters['tls_issuer'] = tls_issuer - if tls_subject: - parameters['tls_subject'] = tls_subject - if description: - parameters['description'] = description - if ipmi_authtype: - parameters['ipmi_authtype'] = ipmi_authtype - if ipmi_privilege: - parameters['ipmi_privilege'] = ipmi_privilege - if ipmi_username: - parameters['ipmi_username'] = ipmi_username - if ipmi_password: - parameters['ipmi_password'] = ipmi_password + if discovered_host: + # The host was discovered via Discovery Rule + parameters = {"hostid": host_id, "status": status} + else: + # A "plain" host + parameters = {"hostid": host_id, "groups": group_ids, "status": status} + if proxy_id >= 0: + parameters["proxy_hostid"] = proxy_id + if visible_name: + parameters["name"] = visible_name + if tls_connect: + parameters["tls_connect"] = tls_connect + if tls_accept: + parameters["tls_accept"] = tls_accept + if tls_psk_identity: + parameters["tls_psk_identity"] = tls_psk_identity + if tls_psk: + parameters["tls_psk"] = tls_psk + if tls_issuer: + parameters["tls_issuer"] = tls_issuer + if tls_subject: + parameters["tls_subject"] = tls_subject + if description: + parameters["description"] = description + if ipmi_authtype: + parameters["ipmi_authtype"] = ipmi_authtype + if ipmi_privilege: + parameters["ipmi_privilege"] = ipmi_privilege + if ipmi_username: + parameters["ipmi_username"] = ipmi_username + if ipmi_password: + parameters["ipmi_password"] = ipmi_password + if interfaces: + parameters["interfaces"] = interfaces if macros is not None: - parameters['macros'] = macros + parameters["macros"] = macros if tags is not None: - parameters['tags'] = tags - if interfaces: - parameters['interfaces'] = interfaces + parameters["tags"] = tags self._zapi.host.update(parameters) except Exception as e: @@ -586,49 +571,42 @@ class Host(ZabbixBase): # get host by host name def get_host_by_host_name(self, host_name): params = { - 'output': 'extend', - 'selectInventory': 'extend', - 'selectMacros': 'extend', - 'filter': { - 'host': [host_name] + "output": [ + "inventory_mode", + "hostid", + "proxy_hostid", + "host", + "status", + "lastaccess", + "ipmi_authtype", + "ipmi_privilege", + "ipmi_username", + "ipmi_password", + "maintenanceid", + "maintenance_status", + "maintenance_type", + "maintenance_from", + "name", + "flags", + "templateid", + "description", + "tls_connect", + "tls_accept", + "tls_issuer", + "tls_subject", + "proxy_address", + "auto_compress", + "custom_interfaces", + "uuid" + ], + "selectInventory": "extend", + "selectMacros": "extend", + "selectTags": ["tag", "value"], + "filter": { + "host": [host_name] } } - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.2.0'): - params.update({'selectTags': ['tag', 'value']}) - - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.4.0'): - params.update({ - 'output': [ - "inventory_mode", - "hostid", - "proxy_hostid", - "host", - "status", - "lastaccess", - "ipmi_authtype", - "ipmi_privilege", - "ipmi_username", - "ipmi_password", - "maintenanceid", - "maintenance_status", - "maintenance_type", - "maintenance_from", - "name", - "flags", - "templateid", - "description", - "tls_connect", - "tls_accept", - "tls_issuer", - "tls_subject", - "proxy_address", - "auto_compress", - "custom_interfaces", - "uuid" - ] - }) - host_list = self._zapi.host.get(params) if len(host_list) < 1: self._module.fail_json(msg="Host not found: %s" % host_name) @@ -637,27 +615,27 @@ class Host(ZabbixBase): # get proxyid by proxy name def get_proxyid_by_proxy_name(self, proxy_name): - proxy_list = self._zapi.proxy.get({'output': 'extend', 'filter': {'host': [proxy_name]}}) + proxy_list = self._zapi.proxy.get({"output": "extend", "filter": {"host": [proxy_name]}}) if len(proxy_list) < 1: self._module.fail_json(msg="Proxy not found: %s" % proxy_name) else: - return int(proxy_list[0]['proxyid']) + return int(proxy_list[0]["proxyid"]) # get group ids by group names def get_group_ids_by_group_names(self, group_names): if self.check_host_group_exist(group_names): - return self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': group_names}}) + return self._zapi.hostgroup.get({"output": "extend", "filter": {"name": group_names}}) # get host groups ids by host id def get_group_ids_by_host_id(self, host_id): - return self._zapi.hostgroup.get({'output': 'extend', 'hostids': host_id}) + return self._zapi.hostgroup.get({"output": "extend", "hostids": host_id}) # get host templates by host id def get_host_templates_by_host_id(self, host_id): template_ids = [] - template_list = self._zapi.template.get({'output': 'extend', 'hostids': host_id}) + template_list = self._zapi.template.get({"output": "extend", "hostids": host_id}) for template in template_list: - template_ids.append(template['templateid']) + template_ids.append(template["templateid"]) return template_ids def construct_host_interfaces(self, interfaces): @@ -671,45 +649,40 @@ class Host(ZabbixBase): and ip is any IP address found on interface of type agent (printing purposes only). """ ip = "" - interface_types = {'agent': 1, 'snmp': 2, 'ipmi': 3, 'jmx': 4} - type_to_port = {1: '10050', 2: '161', 3: '623', 4: '12345'} + interface_types = {"agent": 1, "snmp": 2, "ipmi": 3, "jmx": 4} + type_to_port = {1: "10050", 2: "161", 3: "623", 4: "12345"} for interface in interfaces: - if interface['type'] in list(interface_types.keys()): - interface['type'] = interface_types[interface['type']] + if interface["type"] in list(interface_types.keys()): + interface["type"] = interface_types[interface["type"]] else: - interface['type'] = int(interface['type']) + interface["type"] = int(interface["type"]) - if interface['type'] == 1: - ip = interface.get('ip', '') + if interface["type"] == 1: + ip = interface.get("ip", "") - for key in ['ip', 'dns']: + for key in ["ip", "dns"]: if key not in interface or interface[key] is None: - interface[key] = '' - - if 'port' not in interface or interface['port'] is None: - interface['port'] = type_to_port.get(interface['type'], '') + interface[key] = "" - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0.0'): - if 'bulk' in interface: - del interface['bulk'] + if "port" not in interface or interface["port"] is None: + interface["port"] = type_to_port.get(interface["type"], "") - # Not handled in argument_spec with required_if since only SNMP interfaces are using details - if interface['type'] == 2: - if not interface['details']: - self._module.fail_json(msg='Option "details" required for SNMP interface {0}'.format(interface)) + if "bulk" in interface: + del interface["bulk"] - i_details = interface['details'] - if i_details['version'] < 3 and not i_details.get('community', False): - self._module.fail_json( - msg='Option "community" is required in "details" for SNMP interface {0}'.format(interface)) + # Not handled in argument_spec with required_if since only SNMP interfaces are using details + if interface["type"] == 2: + if not interface["details"]: + self._module.fail_json(msg="Option 'details' required for SNMP interface {0}".format(interface)) - else: - interface['details'] = {} + i_details = interface["details"] + if i_details["version"] < 3 and not i_details.get("community", False): + self._module.fail_json( + msg="Option 'community' is required in 'details' for SNMP interface {0}".format(interface)) else: - if 'details' in interface: - del interface['details'] + interface["details"] = {} return (interfaces, ip) @@ -735,7 +708,7 @@ class Host(ZabbixBase): # get the status of host by host def get_host_status_by_host(self, host): - return host['status'] + return host["status"] # check all the properties before link or clear template def check_all_properties(self, host_id, group_ids, status, interfaces, template_ids, @@ -744,8 +717,8 @@ class Host(ZabbixBase): tls_issuer, tls_subject, tls_connect, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, macros, tags): # get the existing host's groups - exist_host_groups = sorted(self.get_group_ids_by_host_id(host_id), key=lambda k: k['groupid']) - if sorted(group_ids, key=lambda k: k['groupid']) != exist_host_groups: + exist_host_groups = sorted(self.get_group_ids_by_host_id(host_id), key=lambda k: k["groupid"]) + if sorted(group_ids, key=lambda k: k["groupid"]) != exist_host_groups: return True # get the existing status @@ -762,97 +735,82 @@ class Host(ZabbixBase): if set(list(template_ids)) != set(exist_template_ids): return True - if int(host['proxy_hostid']) != int(proxy_id): + if int(host["proxy_hostid"]) != int(proxy_id): return True # Check whether the visible_name has changed; Zabbix defaults to the technical hostname if not set. if visible_name: - if host['name'] != visible_name: + if host["name"] != visible_name: return True # Only compare description if it is given as a module parameter if description: - if host['description'] != description: + if host["description"] != description: return True if inventory_mode: - if LooseVersion(self._zbx_api_version) <= LooseVersion('4.4.0'): - if host['inventory']: - if int(host['inventory']['inventory_mode']) != self.inventory_mode_numeric(inventory_mode): - return True - elif inventory_mode != 'disabled': - return True - else: - if int(host['inventory_mode']) != self.inventory_mode_numeric(inventory_mode): - return True + if int(host["inventory_mode"]) != self.inventory_mode_numeric(inventory_mode): + return True if inventory_zabbix: - proposed_inventory = copy.deepcopy(host['inventory']) + proposed_inventory = copy.deepcopy(host["inventory"]) proposed_inventory.update(inventory_zabbix) - if proposed_inventory != host['inventory']: + if proposed_inventory != host["inventory"]: return True - if tls_accept is not None and 'tls_accept' in host: - if int(host['tls_accept']) != tls_accept: + if tls_accept is not None and "tls_accept" in host: + if int(host["tls_accept"]) != tls_accept: return True - if LooseVersion(self._zbx_api_version) < LooseVersion('5.4'): - if tls_psk_identity is not None and 'tls_psk_identity' in host: - if host['tls_psk_identity'] != tls_psk_identity: - return True - if tls_psk is not None and 'tls_psk' in host: - if host['tls_psk'] != tls_psk: - return True - else: - # in Zabbix >= 5.4 these parameters are write-only and are not returned in host.get response - if tls_psk_identity is not None or tls_psk is not None: - return True + # in Zabbix >= 5.4 these parameters are write-only and are not returned in host.get response + if tls_psk_identity is not None or tls_psk is not None: + return True - if tls_issuer is not None and 'tls_issuer' in host: - if host['tls_issuer'] != tls_issuer: + if tls_issuer is not None and "tls_issuer" in host: + if host["tls_issuer"] != tls_issuer: return True - if tls_subject is not None and 'tls_subject' in host: - if host['tls_subject'] != tls_subject: + if tls_subject is not None and "tls_subject" in host: + if host["tls_subject"] != tls_subject: return True - if tls_connect is not None and 'tls_connect' in host: - if int(host['tls_connect']) != tls_connect: + if tls_connect is not None and "tls_connect" in host: + if int(host["tls_connect"]) != tls_connect: return True if ipmi_authtype is not None: - if int(host['ipmi_authtype']) != ipmi_authtype: + if int(host["ipmi_authtype"]) != ipmi_authtype: return True if ipmi_privilege is not None: - if int(host['ipmi_privilege']) != ipmi_privilege: + if int(host["ipmi_privilege"]) != ipmi_privilege: return True if ipmi_username is not None: - if host['ipmi_username'] != ipmi_username: + if host["ipmi_username"] != ipmi_username: return True if ipmi_password is not None: - if host['ipmi_password'] != ipmi_password: + if host["ipmi_password"] != ipmi_password: return True - # hostmacroid and hostid are present in every item of host['macros'] and need to be removed - if macros is not None and 'macros' in host: + # hostmacroid and hostid are present in every item of host["macros"] and need to be removed + if macros is not None and "macros" in host: t_macros = copy.deepcopy(macros) # make copy to prevent change in original data - for macro in host['macros']: - macro.pop('hostid', False) - macro.pop('hostmacroid', False) + for macro in host["macros"]: + macro.pop("hostid", False) + macro.pop("hostmacroid", False) diff = [] - zabbix_utils.helper_compare_lists(t_macros, host['macros'], diff) + zabbix_utils.helper_compare_lists(t_macros, host["macros"], diff) if diff != []: return True - if tags is not None and 'tags' in host: - if sorted(tags, key=lambda k: k['tag']) != sorted(host['tags'], key=lambda k: k['tag']): + if tags is not None and "tags" in host: + if sorted(tags, key=lambda k: k["tag"]) != sorted(host["tags"], key=lambda k: k["tag"]): return True return False # link or clear template of the host def link_or_clear_template(self, host_id, template_id_list, tls_connect, tls_accept, tls_psk_identity, tls_psk, - tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): + tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, discovered_host): # get host's exist template ids exist_template_id_list = self.get_host_templates_by_host_id(host_id) @@ -863,20 +821,25 @@ class Host(ZabbixBase): # get unlink and clear templates templates_clear = exist_template_ids.difference(template_ids) templates_clear_list = list(templates_clear) - request_str = {'hostid': host_id, 'templates': template_id_list, 'templates_clear': templates_clear_list, - 'ipmi_authtype': ipmi_authtype, 'ipmi_privilege': ipmi_privilege, 'ipmi_username': ipmi_username, 'ipmi_password': ipmi_password} - if tls_connect: - request_str['tls_connect'] = tls_connect - if tls_accept: - request_str['tls_accept'] = tls_accept - if tls_psk_identity is not None: - request_str['tls_psk_identity'] = tls_psk_identity - if tls_psk is not None: - request_str['tls_psk'] = tls_psk - if tls_issuer is not None: - request_str['tls_issuer'] = tls_issuer - if tls_subject is not None: - request_str['tls_subject'] = tls_subject + if discovered_host: + # The host was discovered via Discovery Rule + request_str = {"hostid": host_id, "templates": template_id_list, "templates_clear": templates_clear_list} + else: + # A "plain" host + request_str = {"hostid": host_id, "templates": template_id_list, "templates_clear": templates_clear_list, + "ipmi_authtype": ipmi_authtype, "ipmi_privilege": ipmi_privilege, "ipmi_username": ipmi_username, "ipmi_password": ipmi_password} + if tls_connect: + request_str["tls_connect"] = tls_connect + if tls_accept: + request_str["tls_accept"] = tls_accept + if tls_psk_identity is not None: + request_str["tls_psk_identity"] = tls_psk_identity + if tls_psk is not None: + request_str["tls_psk"] = tls_psk + if tls_issuer is not None: + request_str["tls_issuer"] = tls_issuer + if tls_subject is not None: + request_str["tls_subject"] = tls_subject try: if self._module.check_mode: self._module.exit_json(changed=True) @@ -903,7 +866,7 @@ class Host(ZabbixBase): inventory_mode = self.inventory_mode_numeric(inventory_mode) # watch for - https://support.zabbix.com/browse/ZBX-6033 - request_str = {'hostid': host_id, 'inventory_mode': inventory_mode} + request_str = {"hostid": host_id, "inventory_mode": inventory_mode} try: if self._module.check_mode: self._module.exit_json(changed=True) @@ -916,7 +879,7 @@ class Host(ZabbixBase): if not inventory: return - request_str = {'hostid': host_id, 'inventory': inventory} + request_str = {"hostid": host_id, "inventory": inventory} try: if self._module.check_mode: self._module.exit_json(changed=True) @@ -930,30 +893,30 @@ def update_exist_interfaces_with_defaults(exist_interfaces): new_exist_interfaces = [] default_interface = { - 'main': '0', - 'useip': '0', - 'ip': '', - 'dns': '', - 'port': '' + "main": "0", + "useip": "0", + "ip": "", + "dns": "", + "port": "" } default_interface_details = { - 'version': 2, - 'bulk': 1, - 'community': '', - 'securityname': '', - 'contextname': '', - 'securitylevel': 0, - 'authprotocol': 0, - 'authpassphrase': '', - 'privprotocol': 0, - 'privpassphrase': '' + "version": 2, + "bulk": 1, + "community": "", + "securityname": "", + "contextname": "", + "securitylevel": 0, + "authprotocol": 0, + "authpassphrase": "", + "privprotocol": 0, + "privpassphrase": "" } for interface in exist_interfaces: new_interface = default_interface.copy() new_interface.update(interface) - new_interface['details'] = default_interface_details.copy() - if 'details' in interface: - new_interface['details'].update(interface['details']) + new_interface["details"] = default_interface_details.copy() + if "details" in interface: + new_interface["details"].update(interface["details"]) new_exist_interfaces.append(new_interface) return new_exist_interfaces @@ -961,16 +924,16 @@ def update_exist_interfaces_with_defaults(exist_interfaces): def normalize_macro_name(macro_name): # Zabbix handles macro names in upper case characters - if ':' in macro_name: - macro_name = ':'.join([macro_name.split(':')[0].upper(), ':'.join(macro_name.split(':')[1:])]) + if ":" in macro_name: + macro_name = ":".join([macro_name.split(":")[0].upper(), ":".join(macro_name.split(":")[1:])]) else: macro_name = macro_name.upper() # Valid format for macro is {$MACRO} - if not macro_name.startswith('{$'): - macro_name = '{$' + macro_name - if not macro_name.endswith('}'): - macro_name = macro_name + '}' + if not macro_name.startswith("{$"): + macro_name = "{$" + macro_name + if not macro_name.endswith("}"): + macro_name = macro_name + "}" return macro_name @@ -978,79 +941,78 @@ def normalize_macro_name(macro_name): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - host_name=dict(type='str', required=True), - host_groups=dict(type='list', required=False), - link_templates=dict(type='list', required=False), - status=dict(type='str', default="enabled", choices=['enabled', 'disabled']), - state=dict(type='str', default="present", choices=['present', 'absent']), - inventory_mode=dict(type='str', required=False, choices=['automatic', 'manual', 'disabled']), - ipmi_authtype=dict(type='int', default=None), - ipmi_privilege=dict(type='int', default=None), - ipmi_username=dict(type='str', required=False, default=None), - ipmi_password=dict(type='str', required=False, default=None, no_log=True), - tls_connect=dict(type='int', required=False), - tls_accept=dict(type='int', required=False), - tls_psk_identity=dict(type='str', required=False), - tls_psk=dict(type='str', required=False, no_log=True), - ca_cert=dict(type='str', required=False, aliases=['tls_issuer']), - tls_subject=dict(type='str', required=False), - inventory_zabbix=dict(type='dict', required=False), + host_name=dict(type="str", required=True), + host_groups=dict(type="list", required=False, elements="str"), + link_templates=dict(type="list", required=False, elements="str"), + status=dict(type="str", default="enabled", choices=["enabled", "disabled"]), + state=dict(type="str", default="present", choices=["present", "absent"]), + inventory_mode=dict(type="str", required=False, choices=["automatic", "manual", "disabled"]), + ipmi_authtype=dict(type="int", default=None), + ipmi_privilege=dict(type="int", default=None), + ipmi_username=dict(type="str", required=False, default=None), + ipmi_password=dict(type="str", required=False, default=None, no_log=True), + tls_connect=dict(type="int", required=False), + tls_accept=dict(type="int", required=False), + tls_psk_identity=dict(type="str", required=False), + tls_psk=dict(type="str", required=False, no_log=True), + ca_cert=dict(type="str", required=False, aliases=["tls_issuer"]), + tls_subject=dict(type="str", required=False), + inventory_zabbix=dict(type="dict", required=False), interfaces=dict( - type='list', - elements='dict', + type="list", + elements="dict", default=[], options=dict( - type=dict(type='str', required=True, choices=['agent', '1', 'snmp', '2', 'ipmi', '3', 'jmx', '4']), - main=dict(type='int', choices=[0, 1], default=0), - useip=dict(type='int', choices=[0, 1], default=0), - ip=dict(type='str'), - dns=dict(type='str'), - port=dict(type='str'), - bulk=dict(type='int', choices=[0, 1], default=1), + type=dict(type="str", required=True, choices=["agent", "1", "snmp", "2", "ipmi", "3", "jmx", "4"]), + main=dict(type="int", choices=[0, 1], default=0), + useip=dict(type="int", choices=[0, 1], default=0), + ip=dict(type="str"), + dns=dict(type="str"), + port=dict(type="str"), details=dict( - type='dict', + type="dict", default={}, options=dict( - version=dict(type='int', choices=[1, 2, 3], default=2), - bulk=dict(type='int', choices=[0, 1], default=1), - community=dict(type='str', default=''), - securityname=dict(type='str', default=''), - contextname=dict(type='str', default=''), - securitylevel=dict(type='int', choices=[0, 1, 2], default=0), - authprotocol=dict(type='int', choices=[0, 1, 2, 3, 4, 5], default=0), - authpassphrase=dict(type='str', default='', no_log=True), - privprotocol=dict(type='int', choices=[0, 1, 2, 3, 4, 5], default=0), - privpassphrase=dict(type='str', default='', no_log=True) + version=dict(type="int", choices=[1, 2, 3], default=2), + bulk=dict(type="int", choices=[0, 1], default=1), + community=dict(type="str", default=""), + securityname=dict(type="str", default=""), + contextname=dict(type="str", default=""), + securitylevel=dict(type="int", choices=[0, 1, 2], default=0), + authprotocol=dict(type="int", choices=[0, 1, 2, 3, 4, 5], default=0), + authpassphrase=dict(type="str", default="", no_log=True), + privprotocol=dict(type="int", choices=[0, 1, 2, 3, 4, 5], default=0), + privpassphrase=dict(type="str", default="", no_log=True) ) ) ), required_if=[ - ['useip', 0, ['dns']], - ['useip', 1, ['ip']] + ["useip", 0, ["dns"]], + ["useip", 1, ["ip"]] ] ), - force=dict(type='bool', default=True), - proxy=dict(type='str', required=False), - visible_name=dict(type='str', required=False), - description=dict(type='str', required=False), + force=dict(type="bool", default=True), + proxy=dict(type="str", required=False), + visible_name=dict(type="str", required=False), + description=dict(type="str", required=False), macros=dict( - type='list', - elements='dict', - aliases=['user_macros'], + type="list", + elements="dict", + aliases=["user_macros"], options=dict( - macro=dict(type='str', required=True), - value=dict(type='str', required=True), - description=dict(type='str', default=''), - type=dict(type='str', default='text', choices=['text', 'secret']) + macro=dict(type="str", required=True), + value=dict(type="str", required=True), + description=dict(type="str", default=""), + type=dict(type="str", default="text", choices=["text", "secret"]) ) ), tags=dict( - type='list', - elements='dict', - aliases=['host_tags'], + type="list", + elements="dict", + aliases=["host_tags"], options=dict( - tag=dict(type='str', required=True), - value=dict(type='str', default='') + tag=dict(type="str", required=True), + value=dict(type="str", default="") ) ) )) @@ -1059,36 +1021,30 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - host_name = module.params['host_name'] - visible_name = module.params['visible_name'] - description = module.params['description'] - host_groups = module.params['host_groups'] - link_templates = module.params['link_templates'] - inventory_mode = module.params['inventory_mode'] - ipmi_authtype = module.params['ipmi_authtype'] - ipmi_privilege = module.params['ipmi_privilege'] - ipmi_username = module.params['ipmi_username'] - ipmi_password = module.params['ipmi_password'] - tls_connect = module.params['tls_connect'] - tls_accept = module.params['tls_accept'] - tls_psk_identity = module.params['tls_psk_identity'] - tls_psk = module.params['tls_psk'] - tls_issuer = module.params['ca_cert'] - tls_subject = module.params['tls_subject'] - inventory_zabbix = module.params['inventory_zabbix'] - status = module.params['status'] - state = module.params['state'] - interfaces = module.params['interfaces'] - force = module.params['force'] - proxy = module.params['proxy'] - macros = module.params['macros'] - tags = module.params['tags'] + host_name = module.params["host_name"] + visible_name = module.params["visible_name"] + description = module.params["description"] + host_groups = module.params["host_groups"] + link_templates = module.params["link_templates"] + inventory_mode = module.params["inventory_mode"] + ipmi_authtype = module.params["ipmi_authtype"] + ipmi_privilege = module.params["ipmi_privilege"] + ipmi_username = module.params["ipmi_username"] + ipmi_password = module.params["ipmi_password"] + tls_connect = module.params["tls_connect"] + tls_accept = module.params["tls_accept"] + tls_psk_identity = module.params["tls_psk_identity"] + tls_psk = module.params["tls_psk"] + tls_issuer = module.params["ca_cert"] + tls_subject = module.params["tls_subject"] + inventory_zabbix = module.params["inventory_zabbix"] + status = module.params["status"] + state = module.params["state"] + interfaces = module.params["interfaces"] + force = module.params["force"] + proxy = module.params["proxy"] + macros = module.params["macros"] + tags = module.params["tags"] # convert enabled to 0; disabled to 1 status = 1 if status == "disabled" else 0 @@ -1109,20 +1065,13 @@ def main(): if macros: # convert macros to zabbix native format - {$MACRO} for macro in macros: - macro['macro'] = normalize_macro_name(macro['macro']) + macro["macro"] = normalize_macro_name(macro["macro"]) - if LooseVersion(host._zbx_api_version) <= LooseVersion('4.4.0'): - if 'description' in macro: - macro.pop('description', False) - - if 'type' in macro: - if LooseVersion(host._zbx_api_version) < LooseVersion('5.0.0'): - macro.pop('type') - else: - if macro['type'] == 'text': - macro['type'] = '0' - elif macro['type'] == 'secret': - macro['type'] = '1' + if "type" in macro: + if macro["type"] == "text": + macro["type"] = "0" + elif macro["type"] == "secret": + macro["type"] = "1" # Use proxy specified, or set to 0 if proxy: @@ -1136,11 +1085,12 @@ def main(): if is_host_exist: # get host id by host name zabbix_host_obj = host.get_host_by_host_name(host_name) - host_id = zabbix_host_obj['hostid'] + host_id = zabbix_host_obj["hostid"] + discovered_host = zabbix_host_obj["flags"] == '4' # If proxy is not specified as a module parameter, use the existing setting if proxy is None: - proxy_id = int(zabbix_host_obj['proxy_hostid']) + proxy_id = int(zabbix_host_obj["proxy_hostid"]) if state == "absent": # remove host @@ -1153,29 +1103,29 @@ def main(): group_ids = host.get_group_ids_by_host_id(host_id) # get existing host's interfaces - exist_interfaces = host._zapi.hostinterface.get({'output': 'extend', 'hostids': host_id}) - exist_interfaces.sort(key=lambda x: int(x['interfaceid'])) + exist_interfaces = host._zapi.hostinterface.get({"output": "extend", "hostids": host_id}) + exist_interfaces.sort(key=lambda x: int(x["interfaceid"])) exist_interfaces = update_exist_interfaces_with_defaults(exist_interfaces) # Convert integer parameters from strings to ints for idx, interface in enumerate(copy.deepcopy(exist_interfaces)): for key in tuple(interface.keys()): # fix values for properties - if key in ['useip', 'main', 'type', 'bulk']: + if key in ["useip", "main", "type", "bulk"]: exist_interfaces[idx][key] = int(interface[key]) - elif key == 'details': + elif key == "details": if not interface[key]: exist_interfaces[idx][key] = {} else: for d_key in interface[key].keys(): - if d_key in ['version', 'bulk', 'securitylevel', 'authprotocol', 'privprotocol']: + if d_key in ["version", "bulk", "securitylevel", "authprotocol", "privprotocol"]: exist_interfaces[idx][key][d_key] = int(interface[key][d_key]) interfaces_copy = copy.deepcopy(interfaces) found_in_interfaces = [] for idx, interface in enumerate(copy.deepcopy(exist_interfaces)): - interfaceid = interface['interfaceid'] - hostid = interface['hostid'] + interfaceid = interface["interfaceid"] + hostid = interface["hostid"] if not interfaces_copy: # Whe no interfaces specified, copy existing interfaces @@ -1183,8 +1133,8 @@ def main(): continue # Find already configured interfaces in requested interfaces and compile final list of - # interfaces in 'interfaces' variable. Every element of the list defines one interface. - # If an element has 'interfaceid' field then Zabbix will update existing interface otherwise + # interfaces in "interfaces" variable. Every element of the list defines one interface. + # If an element has "interfaceid" field then Zabbix will update existing interface otherwise # a new interface will be added. found = False for idx1, iface in enumerate(interfaces_copy): @@ -1193,8 +1143,8 @@ def main(): if diff_dict == {}: found = True found_in_interfaces.append(iface) - interfaces[idx1]['interfaceid'] = interfaceid - interfaces[idx1]['hostid'] = hostid + interfaces[idx1]["interfaceid"] = interfaceid + interfaces[idx1]["hostid"] = hostid break if not found: @@ -1203,10 +1153,10 @@ def main(): else: # if force == True overwrite existing interfaces with provided interfaces with the same type for idx1, iface in enumerate(interfaces_copy): - if interface['type'] == iface['type'] and iface not in found_in_interfaces: + if interface["type"] == iface["type"] and iface not in found_in_interfaces: found_in_interfaces.append(iface) - interfaces[idx1]['interfaceid'] = interfaceid - interfaces[idx1]['hostid'] = hostid + interfaces[idx1]["interfaceid"] = interfaceid + interfaces[idx1]["hostid"] = hostid break if not force or link_templates is None: @@ -1218,12 +1168,12 @@ def main(): group_ids.append(group_id) # Macros not present in host.update will be removed if we dont copy them when force=no - if macros is not None and 'macros' in zabbix_host_obj.keys(): - existing_macros = zabbix_host_obj['macros'] + if macros is not None and "macros" in zabbix_host_obj.keys(): + existing_macros = zabbix_host_obj["macros"] for macro in existing_macros: - macro.pop('hostmacroid', None) - macro.pop('hostid', None) - macro.pop('automatic', None) + macro.pop("hostmacroid", None) + macro.pop("hostid", None) + macro.pop("automatic", None) found = False for idx1, prov_macro in enumerate(macros): diff_dict = {} @@ -1237,11 +1187,11 @@ def main(): macros.append(macro) # Tags not present in host.update will be removed if we dont copy them when force=no - if tags is not None and 'tags' in zabbix_host_obj.keys(): - provided_tags = [t['tag'] for t in tags] - existing_tags = zabbix_host_obj['tags'] + if tags is not None and "tags" in zabbix_host_obj.keys(): + provided_tags = [t["tag"] for t in tags] + existing_tags = zabbix_host_obj["tags"] for tag in existing_tags: - if tag['tag'] not in provided_tags: + if tag["tag"] not in provided_tags: tags.append(tag) # update host @@ -1254,11 +1204,11 @@ def main(): host.update_host( host_name, group_ids, status, host_id, interfaces, exist_interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, - ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, macros, tags) + ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, macros, tags, discovered_host) host.link_or_clear_template( host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, - tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) + tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, discovered_host) host.update_inventory_mode(host_id, inventory_mode) host.update_inventory_zabbix(host_id, inventory_zabbix) @@ -1270,6 +1220,8 @@ def main(): module.exit_json(changed=False) else: + discovered_host = False + if state == "absent": # the host is already deleted. module.exit_json(changed=False) @@ -1277,10 +1229,6 @@ def main(): if not group_ids: module.fail_json(msg="Specify at least one group for creating host '%s'." % host_name) - if not interfaces or (interfaces and len(interfaces) == 0): - if LooseVersion(host._zbx_api_version) < LooseVersion('5.2.0'): - module.fail_json(msg="Specify at least one interface for creating host '%s'." % host_name) - # create host host_id = host.add_host( host_name, group_ids, status, interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, @@ -1289,7 +1237,7 @@ def main(): host.link_or_clear_template( host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, - ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) + ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password, discovered_host) host.update_inventory_mode(host_id, inventory_mode) host.update_inventory_zabbix(host_id, inventory_zabbix) @@ -1298,5 +1246,5 @@ def main(): host_name, ip, link_templates)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_host_events_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_host_events_info.py index eb22ce23c..fde86bc12 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_host_events_info.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_host_events_info.py @@ -9,7 +9,7 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -RETURN = ''' +RETURN = """ --- triggers_ok: description: Host Zabbix Triggers in OK state @@ -134,20 +134,20 @@ triggers_problem: value: description: Whether the trigger is in OK or problem state type: int -''' +""" -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: zabbix_host_events_info short_description: Get all triggers about a Zabbix host description: - This module allows you to see if a Zabbix host have no active alert to make actions on it. - For this case use module Ansible 'fail' to exclude host in trouble. + For this case use module Ansible "fail" to exclude host in trouble. - Length of "triggers_ok" allow if template's triggers exist for Zabbix Host author: - "Stéphane Travassac (@stravassac)" requirements: - - "python >= 2.7" + - "python >= 3.9" options: host_identifier: description: @@ -180,19 +180,19 @@ options: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: exclude machine if alert active on it @@ -203,18 +203,17 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_host_events_info: host_identifier: "{{inventory_hostname}}" host_id_type: "hostname" - timeout: 120 register: zbx_host delegate_to: localhost - fail: msg: "machine alert in zabbix" - when: zbx_host['triggers_problem']|length > 0 -''' + when: zbx_host["triggers_problem"]|length > 0 +""" from ansible.module_utils.basic import AnsibleModule @@ -227,8 +226,8 @@ class Host(ZabbixBase): def get_host(self, host_identifier, host_inventory, search_key): """ Get host by hostname|visible_name|hostid """ host = self._zapi.host.get( - {'output': 'extend', 'selectParentTemplates': ['name'], 'filter': {search_key: host_identifier}, - 'selectInventory': host_inventory}) + {"output": "extend", "selectParentTemplates": ["name"], "filter": {search_key: host_identifier}, + "selectInventory": host_inventory}) if len(host) < 1: self._module.fail_json(msg="Host not found: %s" % host_identifier) else: @@ -236,18 +235,17 @@ class Host(ZabbixBase): def get_triggers_by_host_id_in_problem_state(self, host_id, trigger_severity): """ Get triggers in problem state from a hostid""" - # https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get - output = 'extend' - triggers_list = self._zapi.trigger.get({'output': output, 'hostids': host_id, - 'min_severity': trigger_severity}) + output = "extend" + triggers_list = self._zapi.trigger.get({"output": output, "hostids": host_id, + "min_severity": trigger_severity}) return triggers_list def get_last_event_by_trigger_id(self, triggers_id): """ Get the last event from triggerid""" - output = ['eventid', 'clock', 'acknowledged', 'value'] - select_acknowledges = ['clock', 'alias', 'message'] - event = self._zapi.event.get({'output': output, 'objectids': triggers_id, - 'select_acknowledges': select_acknowledges, "limit": 1, "sortfield": "clock", + output = ["eventid", "clock", "acknowledged", "value"] + select_acknowledges = ["clock", "alias", "message"] + event = self._zapi.event.get({"output": output, "objectids": triggers_id, + "select_acknowledges": select_acknowledges, "limit": 1, "sortfield": "clock", "sortorder": "DESC"}) return event[0] @@ -255,48 +253,42 @@ class Host(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - host_identifier=dict(type='str', required=True), + host_identifier=dict(type="str", required=True), host_id_type=dict( - default='hostname', - type='str', - choices=['hostname', 'visible_name', 'hostid']), + default="hostname", + type="str", + choices=["hostname", "visible_name", "hostid"]), trigger_severity=dict( - type='str', + type="str", required=False, - default='average', - choices=['not_classified', 'information', 'warning', 'average', 'high', 'disaster']), + default="average", + choices=["not_classified", "information", "warning", "average", "high", "disaster"]), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) + trigger_severity_map = {"not_classified": 0, "information": 1, "warning": 2, "average": 3, "high": 4, "disaster": 5} + host_id = module.params["host_identifier"] + host_id_type = module.params["host_id_type"] + trigger_severity = trigger_severity_map[module.params["trigger_severity"]] - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - trigger_severity_map = {'not_classified': 0, 'information': 1, 'warning': 2, 'average': 3, 'high': 4, 'disaster': 5} - host_id = module.params['host_identifier'] - host_id_type = module.params['host_id_type'] - trigger_severity = trigger_severity_map[module.params['trigger_severity']] - - host_inventory = 'hostid' + host_inventory = "hostid" host = Host(module) - if host_id_type == 'hostname': - zabbix_host = host.get_host(host_id, host_inventory, 'host') - host_id = zabbix_host['hostid'] + if host_id_type == "hostname": + zabbix_host = host.get_host(host_id, host_inventory, "host") + host_id = zabbix_host["hostid"] - elif host_id_type == 'visible_name': - zabbix_host = host.get_host(host_id, host_inventory, 'name') - host_id = zabbix_host['hostid'] + elif host_id_type == "visible_name": + zabbix_host = host.get_host(host_id, host_inventory, "name") + host_id = zabbix_host["hostid"] - elif host_id_type == 'hostid': - ''' check hostid exist''' - zabbix_host = host.get_host(host_id, host_inventory, 'hostid') + elif host_id_type == "hostid": + # check hostid exist + zabbix_host = host.get_host(host_id, host_inventory, "hostid") triggers = host.get_triggers_by_host_id_in_problem_state(host_id, trigger_severity) @@ -305,9 +297,9 @@ def main(): for trigger in triggers: # tGet last event for trigger with problem value = 1 # https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/object - if int(trigger['value']) == 1: - event = host.get_last_event_by_trigger_id(trigger['triggerid']) - trigger['last_event'] = event + if int(trigger["value"]) == 1: + event = host.get_last_event_by_trigger_id(trigger["triggerid"]) + trigger["last_event"] = event triggers_problem.append(trigger) else: triggers_ok.append(trigger) @@ -315,5 +307,5 @@ def main(): module.exit_json(ok=True, triggers_ok=triggers_ok, triggers_problem=triggers_problem) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_host_facts.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_host_facts.py deleted file mode 100644 index 58e3343ab..000000000 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_host_facts.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) me@mimiko.me -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - - -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - - -RETURN = r''' ---- -hosts: - description: List of Zabbix hosts. See https://www.zabbix.com/documentation/4.0/manual/api/reference/host/get for list of host values. - returned: success - type: dict - sample: [ { "available": "1", "description": "", "disable_until": "0", "error": "", "flags": "0", "groups": ["1"], "host": "Host A", ... } ] -''' - -DOCUMENTATION = r''' ---- -module: zabbix_host_info -short_description: Gather information about Zabbix host -description: - - This module allows you to search for Zabbix host entries. - - This module was called C(zabbix_host_facts) before Ansible 2.9. The usage did not change. -author: - - "Michael Miko (@RedWhiteMiko)" -requirements: - - "python >= 2.6" -options: - host_name: - description: - - Name of the host in Zabbix. - - host_name is the unique identifier used and cannot be updated using this module. - - Required when I(host_ip) is not used. - required: false - type: str - default: '' - host_ip: - description: - - Host interface IP of the host in Zabbix. - - Required when I(host_name) is not used. - required: false - type: list - elements: str - default: [] - exact_match: - description: - - Find the exact match - type: bool - default: no - remove_duplicate: - description: - - Remove duplicate host from host result - type: bool - default: yes - host_inventory: - description: - - List of host inventory keys to display in result. - - Whole host inventory is retrieved if keys are not specified. - type: list - elements: str - required: false - default: [] -extends_documentation_fragment: -- community.zabbix.zabbix - -''' - -EXAMPLES = r''' -# If you want to use Username and Password to be authenticated by Zabbix Server -- name: Set credentials to access Zabbix Server API - set_fact: - ansible_user: Admin - ansible_httpapi_pass: zabbix - -# If you want to use API token to be authenticated by Zabbix Server -# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens -- name: Set API token - set_fact: - ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - -- name: Get host info - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_host_info: - host_name: ExampleHost - host_ip: 127.0.0.1 - timeout: 10 - exact_match: no - remove_duplicate: yes - -- name: Reduce host inventory information to provided keys - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_host_info: - host_name: ExampleHost - host_inventory: - - os - - tag - host_ip: 127.0.0.1 - timeout: 10 - exact_match: no - remove_duplicate: yes -''' - - -from ansible.module_utils.basic import AnsibleModule - -from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils - - -class Host(ZabbixBase): - def get_hosts_by_host_name(self, host_name, exact_match, host_inventory): - """ Get host by host name """ - search_key = 'search' - if exact_match: - search_key = 'filter' - host_list = self._zapi.host.get({ - 'output': 'extend', - 'selectParentTemplates': ['name'], - search_key: {'host': [host_name]}, - 'selectInventory': host_inventory, - 'selectGroups': 'extend', - 'selectTags': 'extend', - 'selectMacros': 'extend' - }) - if len(host_list) < 1: - self._module.fail_json(msg="Host not found: %s" % host_name) - else: - return host_list - - def get_hosts_by_ip(self, host_ips, host_inventory): - """ Get host by host ip(s) """ - hostinterfaces = self._zapi.hostinterface.get({ - 'output': 'extend', - 'filter': { - 'ip': host_ips - } - }) - if len(hostinterfaces) < 1: - self._module.fail_json(msg="Host not found: %s" % host_ips) - host_list = [] - for hostinterface in hostinterfaces: - host = self._zapi.host.get({ - 'output': 'extend', - 'selectGroups': 'extend', - 'selectParentTemplates': ['name'], - 'hostids': hostinterface['hostid'], - 'selectInventory': host_inventory, - 'selectTags': 'extend', - 'selectMacros': 'extend' - }) - host[0]['hostinterfaces'] = hostinterface - host_list.append(host[0]) - return host_list - - def delete_duplicate_hosts(self, hosts): - """ Delete duplicated hosts """ - unique_hosts = [] - listed_hostnames = [] - for zabbix_host in hosts: - if zabbix_host['name'] in listed_hostnames: - continue - unique_hosts.append(zabbix_host) - listed_hostnames.append(zabbix_host['name']) - return unique_hosts - - -def main(): - argument_spec = zabbix_utils.zabbix_common_argument_spec() - argument_spec.update(dict( - host_name=dict(type='str', default='', required=False), - host_ip=dict(type='list', default=[], required=False), - exact_match=dict(type='bool', required=False, default=False), - remove_duplicate=dict(type='bool', required=False, default=True), - host_inventory=dict(type='list', default=[], required=False) - )) - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True - ) - if module._name == 'zabbix_host_facts': - module.deprecate("The 'zabbix_host_facts' module has been renamed to 'zabbix_host_info'", - collection_name="community.zabbix", version='2.0.0') # was 2.13 - - zabbix_utils.require_creds_params(module) - - host_name = module.params['host_name'] - host_ips = module.params['host_ip'] - exact_match = module.params['exact_match'] - is_remove_duplicate = module.params['remove_duplicate'] - host_inventory = module.params['host_inventory'] - - if not host_inventory: - host_inventory = 'extend' - - host = Host(module) - - if host_name: - hosts = host.get_hosts_by_host_name(host_name, exact_match, host_inventory) - if is_remove_duplicate: - hosts = host.delete_duplicate_hosts(hosts) - extended_hosts = [] - for zabbix_host in hosts: - zabbix_host['hostinterfaces'] = host._zapi.hostinterface.get({ - 'output': 'extend', 'hostids': zabbix_host['hostid'] - }) - extended_hosts.append(zabbix_host) - module.exit_json(ok=True, hosts=extended_hosts) - - elif host_ips: - extended_hosts = host.get_hosts_by_ip(host_ips, host_inventory) - if is_remove_duplicate: - hosts = host.delete_duplicate_hosts(extended_hosts) - module.exit_json(ok=True, hosts=extended_hosts) - else: - module.exit_json(ok=False, hosts=[], result="No Host present") - - -if __name__ == '__main__': - main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_host_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_host_info.py index 58e3343ab..92c185227 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_host_info.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_host_info.py @@ -9,16 +9,16 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -RETURN = r''' +RETURN = r""" --- hosts: description: List of Zabbix hosts. See https://www.zabbix.com/documentation/4.0/manual/api/reference/host/get for list of host values. returned: success type: dict sample: [ { "available": "1", "description": "", "disable_until": "0", "error": "", "flags": "0", "groups": ["1"], "host": "Host A", ... } ] -''' +""" -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_host_info short_description: Gather information about Zabbix host @@ -28,16 +28,17 @@ description: author: - "Michael Miko (@RedWhiteMiko)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: host_name: description: - Name of the host in Zabbix. - host_name is the unique identifier used and cannot be updated using this module. - Required when I(host_ip) is not used. + - If neither host_name nor host_ip specified then all the hosts configured in Zabbix returned. required: false type: str - default: '' + default: "" host_ip: description: - Host interface IP of the host in Zabbix. @@ -67,19 +68,19 @@ options: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Get host info @@ -90,12 +91,11 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_host_info: host_name: ExampleHost host_ip: 127.0.0.1 - timeout: 10 exact_match: no remove_duplicate: yes @@ -107,7 +107,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_host_info: host_name: ExampleHost @@ -115,10 +115,9 @@ EXAMPLES = r''' - os - tag host_ip: 127.0.0.1 - timeout: 10 exact_match: no remove_duplicate: yes -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -130,17 +129,17 @@ import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabb class Host(ZabbixBase): def get_hosts_by_host_name(self, host_name, exact_match, host_inventory): """ Get host by host name """ - search_key = 'search' + search_key = "search" if exact_match: - search_key = 'filter' + search_key = "filter" host_list = self._zapi.host.get({ - 'output': 'extend', - 'selectParentTemplates': ['name'], - search_key: {'host': [host_name]}, - 'selectInventory': host_inventory, - 'selectGroups': 'extend', - 'selectTags': 'extend', - 'selectMacros': 'extend' + "output": "extend", + "selectParentTemplates": ["name"], + search_key: {"host": [host_name]}, + "selectInventory": host_inventory, + "selectGroups": "extend", + "selectTags": "extend", + "selectMacros": "extend" }) if len(host_list) < 1: self._module.fail_json(msg="Host not found: %s" % host_name) @@ -150,9 +149,9 @@ class Host(ZabbixBase): def get_hosts_by_ip(self, host_ips, host_inventory): """ Get host by host ip(s) """ hostinterfaces = self._zapi.hostinterface.get({ - 'output': 'extend', - 'filter': { - 'ip': host_ips + "output": "extend", + "filter": { + "ip": host_ips } }) if len(hostinterfaces) < 1: @@ -160,15 +159,15 @@ class Host(ZabbixBase): host_list = [] for hostinterface in hostinterfaces: host = self._zapi.host.get({ - 'output': 'extend', - 'selectGroups': 'extend', - 'selectParentTemplates': ['name'], - 'hostids': hostinterface['hostid'], - 'selectInventory': host_inventory, - 'selectTags': 'extend', - 'selectMacros': 'extend' + "output": "extend", + "selectGroups": "extend", + "selectParentTemplates": ["name"], + "hostids": hostinterface["hostid"], + "selectInventory": host_inventory, + "selectTags": "extend", + "selectMacros": "extend" }) - host[0]['hostinterfaces'] = hostinterface + host[0]["hostinterfaces"] = hostinterface host_list.append(host[0]) return host_list @@ -177,51 +176,46 @@ class Host(ZabbixBase): unique_hosts = [] listed_hostnames = [] for zabbix_host in hosts: - if zabbix_host['name'] in listed_hostnames: + if zabbix_host["name"] in listed_hostnames: continue unique_hosts.append(zabbix_host) - listed_hostnames.append(zabbix_host['name']) + listed_hostnames.append(zabbix_host["name"]) return unique_hosts def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - host_name=dict(type='str', default='', required=False), - host_ip=dict(type='list', default=[], required=False), - exact_match=dict(type='bool', required=False, default=False), - remove_duplicate=dict(type='bool', required=False, default=True), - host_inventory=dict(type='list', default=[], required=False) + host_name=dict(type="str", default="", required=False), + host_ip=dict(type="list", default=[], required=False, elements="str"), + exact_match=dict(type="bool", required=False, default=False), + remove_duplicate=dict(type="bool", required=False, default=True), + host_inventory=dict(type="list", default=[], required=False, elements="str") )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - if module._name == 'zabbix_host_facts': - module.deprecate("The 'zabbix_host_facts' module has been renamed to 'zabbix_host_info'", - collection_name="community.zabbix", version='2.0.0') # was 2.13 - zabbix_utils.require_creds_params(module) - - host_name = module.params['host_name'] - host_ips = module.params['host_ip'] - exact_match = module.params['exact_match'] - is_remove_duplicate = module.params['remove_duplicate'] - host_inventory = module.params['host_inventory'] + host_name = module.params["host_name"] + host_ips = module.params["host_ip"] + exact_match = module.params["exact_match"] + is_remove_duplicate = module.params["remove_duplicate"] + host_inventory = module.params["host_inventory"] if not host_inventory: - host_inventory = 'extend' + host_inventory = "extend" host = Host(module) - if host_name: + if host_name != "" or (host_name == "" and len(host_ips) == 0): hosts = host.get_hosts_by_host_name(host_name, exact_match, host_inventory) if is_remove_duplicate: hosts = host.delete_duplicate_hosts(hosts) extended_hosts = [] for zabbix_host in hosts: - zabbix_host['hostinterfaces'] = host._zapi.hostinterface.get({ - 'output': 'extend', 'hostids': zabbix_host['hostid'] + zabbix_host["hostinterfaces"] = host._zapi.hostinterface.get({ + "output": "extend", "hostids": zabbix_host["hostid"] }) extended_hosts.append(zabbix_host) module.exit_json(ok=True, hosts=extended_hosts) @@ -235,5 +229,5 @@ def main(): module.exit_json(ok=False, hosts=[], result="No Host present") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_hostmacro.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_hostmacro.py index 1fed5d889..802a00559 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_hostmacro.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_hostmacro.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_hostmacro short_description: Create/update/delete Zabbix host macros @@ -18,7 +18,7 @@ author: - "Cove (@cove)" - Dean Hailin Song (!UNKNOWN) requirements: - - "python >= 2.6" + - "python >= 3.9" options: host_name: description: @@ -40,42 +40,45 @@ options: description: - Type of the host macro. - text (default) - - secret (Works only with Zabbix >= 5.0) - - vault (Works only with Zabbix >= 5.2) required: false - choices: ['text', 'secret', 'vault'] - default: 'text' + choices: ["text", "secret", "vault"] + default: "text" + macro_description: + description: + - Text Description of the global macro. + type: str + default: "" state: description: - State of the macro. - On C(present), it will create if macro does not exist or update the macro if the associated data is different. - On C(absent) will remove a macro if it exists. required: false - choices: ['present', 'absent'] + choices: ["present", "absent"] type: str default: "present" force: description: - Only updates an existing macro if set to C(yes). - default: 'yes' + default: "yes" type: bool extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create new host macro or update an existing macro's value @@ -86,12 +89,13 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_hostmacro: host_name: ExampleHost macro_name: EXAMPLE.MACRO macro_value: Example value + macro_description: Example description state: present # Values with curly brackets need to be quoted otherwise they will be interpreted as a dictionary @@ -103,12 +107,13 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_hostmacro: host_name: ExampleHost macro_name: "{$EXAMPLE.MACRO}" macro_value: Example value + macro_description: Example description state: present - name: Delete existing host macro @@ -119,19 +124,18 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_hostmacro: host_name: ExampleHost macro_name: "{$EXAMPLE.MACRO}" state: absent -''' +""" from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils @@ -140,11 +144,11 @@ class HostMacro(ZabbixBase): # get host id by host name def get_host_id(self, host_name): try: - host_list = self._zapi.host.get({'output': 'extend', 'filter': {'host': host_name}}) + host_list = self._zapi.host.get({"output": "extend", "filter": {"host": host_name}}) if len(host_list) < 1: self._module.fail_json(msg="Host not found: %s" % host_name) else: - host_id = host_list[0]['hostid'] + host_id = host_list[0]["hostid"] return host_id except Exception as e: self._module.fail_json(msg="Failed to get the host %s id: %s." % (host_name, e)) @@ -153,7 +157,7 @@ class HostMacro(ZabbixBase): def get_host_macro(self, macro_name, host_id): try: host_macro_list = self._zapi.usermacro.get( - {"output": "extend", "selectSteps": "extend", 'hostids': [host_id], 'filter': {'macro': macro_name}}) + {"output": "extend", "selectSteps": "extend", "hostids": [host_id], "filter": {"macro": macro_name}}) if len(host_macro_list) > 0: return host_macro_list[0] return None @@ -161,43 +165,34 @@ class HostMacro(ZabbixBase): self._module.fail_json(msg="Failed to get host macro %s: %s" % (macro_name, e)) # create host macro - def create_host_macro(self, macro_name, macro_value, macro_type, host_id): + def create_host_macro(self, macro_name, macro_value, macro_type, macro_description, host_id): try: if self._module.check_mode: self._module.exit_json(changed=True) - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0'): - self._zapi.usermacro.create({'hostid': host_id, 'macro': macro_name, 'value': macro_value, 'type': macro_type}) - else: - self._zapi.usermacro.create({'hostid': host_id, 'macro': macro_name, 'value': macro_value}) + self._zapi.usermacro.create({"hostid": host_id, "macro": macro_name, "value": macro_value, "type": macro_type, "description": macro_description}) self._module.exit_json(changed=True, result="Successfully added host macro %s" % macro_name) except Exception as e: self._module.fail_json(msg="Failed to create host macro %s: %s" % (macro_name, e)) # update host macro - def update_host_macro(self, host_macro_obj, macro_name, macro_value, macro_type): - host_macro_id = host_macro_obj['hostmacroid'] - if host_macro_obj['macro'] == macro_name: - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0'): - # no change only when macro type == 0. when type = 1 or 2 zabbix will not output value of it. - if host_macro_obj['type'] == '0' and macro_type == '0' and host_macro_obj['value'] == macro_value: - self._module.exit_json(changed=False, result="Host macro %s already up to date" % macro_name) - else: - if host_macro_obj['value'] == macro_value: - self._module.exit_json(changed=False, result="Host macro %s already up to date" % macro_name) + def update_host_macro(self, host_macro_obj, macro_name, macro_value, macro_type, macro_description): + host_macro_id = host_macro_obj["hostmacroid"] + if host_macro_obj["macro"] == macro_name: + # no change only when macro type == 0. when type = 1 or 2 zabbix will not output value of it. + if (host_macro_obj["type"] == "0" and macro_type == "0" and host_macro_obj["value"] == macro_value + and host_macro_obj["description"] == macro_description): + self._module.exit_json(changed=False, result="Host macro %s already up to date" % macro_name) try: if self._module.check_mode: self._module.exit_json(changed=True) - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0'): - self._zapi.usermacro.update({'hostmacroid': host_macro_id, 'value': macro_value, 'type': macro_type}) - else: - self._zapi.usermacro.update({'hostmacroid': host_macro_id, 'value': macro_value}) + self._zapi.usermacro.update({"hostmacroid": host_macro_id, "value": macro_value, "type": macro_type, "description": macro_description}) self._module.exit_json(changed=True, result="Successfully updated host macro %s" % macro_name) except Exception as e: self._module.fail_json(msg="Failed to update host macro %s: %s" % (macro_name, e)) # delete host macro def delete_host_macro(self, host_macro_obj, macro_name): - host_macro_id = host_macro_obj['hostmacroid'] + host_macro_id = host_macro_obj["hostmacroid"] try: if self._module.check_mode: self._module.exit_json(changed=True) @@ -209,16 +204,16 @@ class HostMacro(ZabbixBase): def normalize_macro_name(macro_name): # Zabbix handles macro names in upper case characters - if ':' in macro_name: - macro_name = ':'.join([macro_name.split(':')[0].upper(), ':'.join(macro_name.split(':')[1:])]) + if ":" in macro_name: + macro_name = ":".join([macro_name.split(":")[0].upper(), ":".join(macro_name.split(":")[1:])]) else: macro_name = macro_name.upper() # Valid format for macro is {$MACRO} - if not macro_name.startswith('{$'): - macro_name = '{$' + macro_name - if not macro_name.endswith('}'): - macro_name = macro_name + '}' + if not macro_name.startswith("{$"): + macro_name = "{$" + macro_name + if not macro_name.endswith("}"): + macro_name = macro_name + "}" return macro_name @@ -226,38 +221,34 @@ def normalize_macro_name(macro_name): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - host_name=dict(type='str', required=True), - macro_name=dict(type='str', required=True), - macro_value=dict(type='str', required=False), - macro_type=dict(type='str', default='text', choices=['text', 'secret', 'vault']), - state=dict(type='str', default='present', choices=['present', 'absent']), - force=dict(type='bool', default=True) + host_name=dict(type="str", required=True), + macro_name=dict(type="str", required=True), + macro_value=dict(type="str", required=False), + macro_type=dict(type="str", default="text", choices=["text", "secret", "vault"]), + macro_description=dict(type="str", default=""), + state=dict(type="str", default="present", choices=["present", "absent"]), + force=dict(type="bool", default=True) )) module = AnsibleModule( argument_spec=argument_spec, required_if=[ - ['state', 'present', ['macro_value']] + ["state", "present", ["macro_value"]] ], supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - host_name = module.params['host_name'] - macro_name = normalize_macro_name(module.params['macro_name']) - macro_value = module.params['macro_value'] - state = module.params['state'] - force = module.params['force'] - if module.params['macro_type'] == 'secret': - macro_type = '1' - elif module.params['macro_type'] == 'vault': - macro_type = '2' + host_name = module.params["host_name"] + macro_name = normalize_macro_name(module.params["macro_name"]) + macro_value = module.params["macro_value"] + macro_description = module.params["macro_description"] + state = module.params["state"] + force = module.params["force"] + if module.params["macro_type"] == "secret": + macro_type = "1" + elif module.params["macro_type"] == "vault": + macro_type = "2" else: - macro_type = '0' + macro_type = "0" host_macro_class_obj = HostMacro(module) @@ -265,7 +256,7 @@ def main(): host_id = host_macro_class_obj.get_host_id(host_name) host_macro_obj = host_macro_class_obj.get_host_macro(macro_name, host_id) - if state == 'absent': + if state == "absent": if not host_macro_obj: module.exit_json(changed=False, msg="Host Macro %s does not exist" % macro_name) else: @@ -274,13 +265,13 @@ def main(): else: if not host_macro_obj: # create host macro - host_macro_class_obj.create_host_macro(macro_name, macro_value, macro_type, host_id) + host_macro_class_obj.create_host_macro(macro_name, macro_value, macro_type, macro_description, host_id) elif force: # update host macro - host_macro_class_obj.update_host_macro(host_macro_obj, macro_name, macro_value, macro_type) + host_macro_class_obj.update_host_macro(host_macro_obj, macro_name, macro_value, macro_type, macro_description) else: module.exit_json(changed=False, result="Host macro %s already exists and force is set to no" % macro_name) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_housekeeping.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_housekeeping.py index 901ff965a..3f6e5d733 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_housekeeping.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_housekeeping.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: zabbix_housekeeping @@ -21,7 +21,7 @@ author: - ONODERA Masaru(@masa-orca) requirements: - - "python >= 2.6" + - "python >= 3.9" version_added: 1.6.0 @@ -39,7 +39,6 @@ options: hk_events_service: description: - Storage period of service data (e.g. 365d). - - This parameter is available since Zabbix 6.0. required: false type: str hk_events_internal: @@ -128,24 +127,21 @@ options: required: false type: str -notes: - - Zabbix 5.2 version and higher are supported. - extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Update housekeeping all parameter @@ -156,7 +152,7 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_housekeeping: login_user: Admin @@ -181,35 +177,29 @@ EXAMPLES = ''' hk_trends: 365d compression_status: off compress_older: 7d -''' +""" -RETURN = ''' +RETURN = """ msg: description: The result of the operation returned: success type: str - sample: 'Successfully update housekeeping setting' -''' + sample: "Successfully update housekeeping setting" +""" import re from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils class Housekeeping(ZabbixBase): - def __init__(self, module, zbx=None, zapi_wrapper=None): - super(Housekeeping, self).__init__(module, zbx, zapi_wrapper) - if LooseVersion(self._zbx_api_version) < LooseVersion('5.2.0'): - module.fail_json(msg="This module doesn't support Zabbix versions lower than 5.2.0") - # get housekeeping setting def get_housekeeping(self): try: - return self._zapi.housekeeping.get({'output': 'extend'}) + return self._zapi.housekeeping.get({"output": "extend"}) except Exception as e: self._module.fail_json(msg="Failed to get housekeeping setting: %s" % e) @@ -247,78 +237,75 @@ class Housekeeping(ZabbixBase): params = {} if isinstance(hk_events_mode, bool): - params['hk_events_mode'] = str(int(hk_events_mode)) + params["hk_events_mode"] = str(int(hk_events_mode)) if hk_events_trigger: - self.check_time_parameter('hk_events_trigger', hk_events_trigger) - params['hk_events_trigger'] = hk_events_trigger + self.check_time_parameter("hk_events_trigger", hk_events_trigger) + params["hk_events_trigger"] = hk_events_trigger if hk_events_service: - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - self._module.warn('hk_events_service is ignored with <= Zabbix 5.4.') - else: - self.check_time_parameter('hk_events_service', hk_events_service) - params['hk_events_service'] = hk_events_service + self.check_time_parameter("hk_events_service", hk_events_service) + params["hk_events_service"] = hk_events_service if hk_events_internal: - self.check_time_parameter('hk_events_internal', hk_events_internal) - params['hk_events_internal'] = hk_events_internal + self.check_time_parameter("hk_events_internal", hk_events_internal) + params["hk_events_internal"] = hk_events_internal if hk_events_discovery: - self.check_time_parameter('hk_events_discovery', hk_events_discovery) - params['hk_events_discovery'] = hk_events_discovery + self.check_time_parameter("hk_events_discovery", hk_events_discovery) + params["hk_events_discovery"] = hk_events_discovery if hk_events_autoreg: - self.check_time_parameter('hk_events_autoreg', hk_events_autoreg) - params['hk_events_autoreg'] = hk_events_autoreg + self.check_time_parameter("hk_events_autoreg", hk_events_autoreg) + params["hk_events_autoreg"] = hk_events_autoreg if isinstance(hk_services_mode, bool): - params['hk_services_mode'] = str(int(hk_services_mode)) + params["hk_services_mode"] = str(int(hk_services_mode)) if hk_services: - self.check_time_parameter('hk_services', hk_services) - params['hk_services'] = hk_services + self.check_time_parameter("hk_services", hk_services) + params["hk_services"] = hk_services if isinstance(hk_audit_mode, bool): - params['hk_audit_mode'] = str(int(hk_audit_mode)) + params["hk_audit_mode"] = str(int(hk_audit_mode)) if hk_audit: - self.check_time_parameter('hk_audit', hk_audit) - params['hk_audit'] = hk_audit + self.check_time_parameter("hk_audit", hk_audit) + params["hk_audit"] = hk_audit if isinstance(hk_sessions_mode, bool): - params['hk_sessions_mode'] = str(int(hk_sessions_mode)) + params["hk_sessions_mode"] = str(int(hk_sessions_mode)) if hk_sessions: - self.check_time_parameter('hk_sessions', hk_sessions) - params['hk_sessions'] = hk_sessions + self.check_time_parameter("hk_sessions", hk_sessions) + params["hk_sessions"] = hk_sessions if isinstance(hk_history_mode, bool): - params['hk_history_mode'] = str(int(hk_history_mode)) + params["hk_history_mode"] = str(int(hk_history_mode)) if isinstance(hk_history_global, bool): - params['hk_history_global'] = str(int(hk_history_global)) + params["hk_history_global"] = str(int(hk_history_global)) if hk_history: - self.check_time_parameter('hk_history', hk_history) - params['hk_history'] = hk_history + self.check_time_parameter("hk_history", hk_history) + params["hk_history"] = hk_history if isinstance(hk_trends_mode, bool): - params['hk_trends_mode'] = str(int(hk_trends_mode)) + params["hk_trends_mode"] = str(int(hk_trends_mode)) if isinstance(hk_trends_global, bool): - params['hk_trends_global'] = str(int(hk_trends_global)) + params["hk_trends_global"] = str(int(hk_trends_global)) if hk_trends: - self.check_time_parameter('hk_trends', hk_trends) - params['hk_trends'] = hk_trends + self.check_time_parameter("hk_trends", hk_trends) + params["hk_trends"] = hk_trends if isinstance(compression_status, bool): - params['compression_status'] = str(int(compression_status)) + params["compression_status"] = str(int(compression_status)) if compress_older: - self.check_time_parameter('compress_older', compress_older) - params['compress_older'] = compress_older + self.check_time_parameter("compress_older", compress_older) + params["compress_older"] = compress_older future_housekeeping = current_housekeeping.copy() future_housekeeping.update(params) @@ -338,58 +325,52 @@ class Housekeeping(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - hk_events_mode=dict(type='bool'), - hk_events_trigger=dict(type='str'), - hk_events_service=dict(type='str'), - hk_events_internal=dict(type='str'), - hk_events_discovery=dict(type='str'), - hk_events_autoreg=dict(type='str'), - hk_services_mode=dict(type='bool'), - hk_services=dict(type='str'), - hk_audit_mode=dict(type='bool'), - hk_audit=dict(type='str'), - hk_sessions_mode=dict(type='bool'), - hk_sessions=dict(type='str'), - hk_history_mode=dict(type='bool'), - hk_history_global=dict(type='bool'), - hk_history=dict(type='str'), - hk_trends_mode=dict(type='bool'), - hk_trends_global=dict(type='bool'), - hk_trends=dict(type='str'), - compression_status=dict(type='bool'), - compress_older=dict(type='str') + hk_events_mode=dict(type="bool"), + hk_events_trigger=dict(type="str"), + hk_events_service=dict(type="str"), + hk_events_internal=dict(type="str"), + hk_events_discovery=dict(type="str"), + hk_events_autoreg=dict(type="str"), + hk_services_mode=dict(type="bool"), + hk_services=dict(type="str"), + hk_audit_mode=dict(type="bool"), + hk_audit=dict(type="str"), + hk_sessions_mode=dict(type="bool"), + hk_sessions=dict(type="str"), + hk_history_mode=dict(type="bool"), + hk_history_global=dict(type="bool"), + hk_history=dict(type="str"), + hk_trends_mode=dict(type="bool"), + hk_trends_global=dict(type="bool"), + hk_trends=dict(type="str"), + compression_status=dict(type="bool"), + compress_older=dict(type="str") )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - hk_events_mode = module.params['hk_events_mode'] - hk_events_trigger = module.params['hk_events_trigger'] - hk_events_service = module.params['hk_events_service'] - hk_events_internal = module.params['hk_events_internal'] - hk_events_discovery = module.params['hk_events_discovery'] - hk_events_autoreg = module.params['hk_events_autoreg'] - hk_services_mode = module.params['hk_services_mode'] - hk_services = module.params['hk_services'] - hk_audit_mode = module.params['hk_audit_mode'] - hk_audit = module.params['hk_audit'] - hk_sessions_mode = module.params['hk_sessions_mode'] - hk_sessions = module.params['hk_sessions'] - hk_history_mode = module.params['hk_history_mode'] - hk_history_global = module.params['hk_history_global'] - hk_history = module.params['hk_history'] - hk_trends_mode = module.params['hk_trends_mode'] - hk_trends_global = module.params['hk_trends_global'] - hk_trends = module.params['hk_trends'] - compression_status = module.params['compression_status'] - compress_older = module.params['compress_older'] + hk_events_mode = module.params["hk_events_mode"] + hk_events_trigger = module.params["hk_events_trigger"] + hk_events_service = module.params["hk_events_service"] + hk_events_internal = module.params["hk_events_internal"] + hk_events_discovery = module.params["hk_events_discovery"] + hk_events_autoreg = module.params["hk_events_autoreg"] + hk_services_mode = module.params["hk_services_mode"] + hk_services = module.params["hk_services"] + hk_audit_mode = module.params["hk_audit_mode"] + hk_audit = module.params["hk_audit"] + hk_sessions_mode = module.params["hk_sessions_mode"] + hk_sessions = module.params["hk_sessions"] + hk_history_mode = module.params["hk_history_mode"] + hk_history_global = module.params["hk_history_global"] + hk_history = module.params["hk_history"] + hk_trends_mode = module.params["hk_trends_mode"] + hk_trends_global = module.params["hk_trends_global"] + hk_trends = module.params["hk_trends"] + compression_status = module.params["compression_status"] + compress_older = module.params["compress_older"] housekeeping = Housekeeping(module) @@ -419,5 +400,5 @@ def main(): ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_maintenance.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_maintenance.py index 139db5057..a2c635eb0 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_maintenance.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_maintenance.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_maintenance short_description: Create Zabbix maintenance windows @@ -16,7 +16,7 @@ description: - This module will let you create Zabbix maintenance windows. author: "Alexander Bulimov (@abulimov)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: state: description: @@ -57,14 +57,13 @@ options: description: - Type of maintenance. With data collection, or without. type: bool - default: 'yes' + default: "yes" visible_name: description: - Type of zabbix host name to use for identifying hosts to include in the maintenance. - I(visible_name=yes) to search by visible name, I(visible_name=no) to search by technical name. type: bool - default: 'yes' - version_added: '2.0.0' + default: "yes" tags: description: - List of tags to assign to the hosts in maintenance. @@ -81,7 +80,7 @@ options: description: - Value of the tag. type: str - default: '' + default: "" operator: description: - Condition operator. @@ -101,19 +100,19 @@ notes: - Module creates maintenance window from now() to now() + minutes, so if Zabbix server's time and host's time are not synchronized, you will get strange results. -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create a named maintenance window for host www1 for 90 minutes @@ -124,7 +123,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_maintenance: name: Update of www1 @@ -140,7 +139,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_maintenance: name: Update of www1 @@ -165,7 +164,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_maintenance: name: update @@ -183,12 +182,12 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_maintenance: name: Test1 state: absent -''' +""" import datetime import time @@ -197,81 +196,65 @@ from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils -from ansible.module_utils.compat.version import LooseVersion class MaintenanceModule(ZabbixBase): def create_maintenance(self, group_ids, host_ids, start_time, maintenance_type, period, name, desc, tags): end_time = start_time + period - try: - parameters = { - "groupids": group_ids, - "hostids": host_ids, - "name": name, - "maintenance_type": maintenance_type, - "active_since": str(start_time), - "active_till": str(end_time), - "description": desc, - "timeperiods": [{ - "timeperiod_type": "0", - "start_date": str(start_time), - "period": str(period), - }] - } - if tags is not None: - parameters['tags'] = tags - self._zapi.maintenance.create(parameters) - # zabbix_api can call sys.exit() so we need to catch SystemExit here - except (Exception, SystemExit) as e: - return 1, None, str(e) + parameters = { + "groupids": group_ids, + "hostids": host_ids, + "name": name, + "maintenance_type": maintenance_type, + "active_since": str(start_time), + "active_till": str(end_time), + "description": desc, + "timeperiods": [{ + "timeperiod_type": "0", + "start_date": str(start_time), + "period": str(period), + }] + } + if tags is not None: + parameters["tags"] = tags + self._zapi.maintenance.create(parameters) return 0, None, None def update_maintenance(self, maintenance_id, group_ids, host_ids, start_time, maintenance_type, period, desc, tags): end_time = start_time + period - try: - parameters = { - "maintenanceid": maintenance_id, - "groupids": group_ids, - "hostids": host_ids, - "maintenance_type": maintenance_type, - "active_since": str(start_time), - "active_till": str(end_time), - "description": desc, - "timeperiods": [{ - "timeperiod_type": "0", - "start_date": str(start_time), - "period": str(period), - }] - } - if tags is not None: - parameters['tags'] = tags - else: - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - parameters['tags'] = [] - self._zapi.maintenance.update(parameters) - # zabbix_api can call sys.exit() so we need to catch SystemExit here - except (Exception, SystemExit) as e: - return 1, None, str(e) + parameters = { + "maintenanceid": maintenance_id, + "groupids": group_ids, + "hostids": host_ids, + "maintenance_type": maintenance_type, + "active_since": str(start_time), + "active_till": str(end_time), + "description": desc, + "timeperiods": [{ + "timeperiod_type": "0", + "start_date": str(start_time), + "period": str(period), + }] + } + if tags is not None: + parameters["tags"] = tags + self._zapi.maintenance.update(parameters) return 0, None, None def get_maintenance(self, name): - try: - maintenances = self._zapi.maintenance.get( + maintenances = self._zapi.maintenance.get( + { + "filter": { - "filter": - { - "name": name, - }, - "selectGroups": "extend", - "selectHosts": "extend", - "selectTags": "extend" - } - ) - # zabbix_api can call sys.exit() so we need to catch SystemExit here - except (Exception, SystemExit) as e: - return 1, None, str(e) + "name": name, + }, + "selectGroups": "extend", + "selectHosts": "extend", + "selectTags": "extend" + } + ) for maintenance in maintenances: maintenance["groupids"] = [group["groupid"] for group @@ -283,29 +266,21 @@ class MaintenanceModule(ZabbixBase): return 0, None, None def delete_maintenance(self, maintenance_id): - try: - self._zapi.maintenance.delete([maintenance_id]) - # zabbix_api can call sys.exit() so we need to catch SystemExit here - except (Exception, SystemExit) as e: - return 1, None, str(e) + self._zapi.maintenance.delete([maintenance_id]) return 0, None, None def get_group_ids(self, host_groups): group_ids = [] for group in host_groups: - try: - result = self._zapi.hostgroup.get( + result = self._zapi.hostgroup.get( + { + "output": "extend", + "filter": { - "output": "extend", - "filter": - { - "name": group - } + "name": group } - ) - # zabbix_api can call sys.exit() so we need to catch SystemExit here - except (Exception, SystemExit) as e: - return 1, None, str(e) + } + ) if not result: return 1, None, "Group id for group %s not found" % group @@ -317,19 +292,15 @@ class MaintenanceModule(ZabbixBase): def get_host_ids(self, host_names, zabbix_host): host_ids = [] for host in host_names: - try: - result = self._zapi.host.get( + result = self._zapi.host.get( + { + "output": "extend", + "filter": { - "output": "extend", - "filter": - { - zabbix_host: host - } + zabbix_host: host } - ) - # zabbix_api can call sys.exit() so we need to catch SystemExit here - except (Exception, SystemExit) as e: - return 1, None, str(e) + } + ) if not result: return 1, None, "Host id for host %s not found" % host @@ -350,35 +321,35 @@ class MaintenanceModule(ZabbixBase): return True if str(int(start_time + period)) != maintenance["active_till"]: return True - if str(desc) != maintenance['description']: + if str(desc) != maintenance["description"]: return True - if tags is not None and 'tags' in maintenance: - if sorted(tags, key=lambda k: k['tag']) != sorted(maintenance['tags'], key=lambda k: k['tag']): + if tags is not None and "tags" in maintenance: + if sorted(tags, key=lambda k: k["tag"]) != sorted(maintenance["tags"], key=lambda k: k["tag"]): return True def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - state=dict(type='str', required=False, default='present', - choices=['present', 'absent']), - host_names=dict(type='list', required=False, - default=None, aliases=['host_name']), - minutes=dict(type='int', required=False, default=10), - host_groups=dict(type='list', required=False, - default=None, aliases=['host_group']), - name=dict(type='str', required=True), - desc=dict(type='str', required=False, default="Created by Ansible"), - collect_data=dict(type='bool', required=False, default=True), - visible_name=dict(type='bool', required=False, default=True), + state=dict(type="str", required=False, default="present", + choices=["present", "absent"]), + host_names=dict(type="list", required=False, + default=None, aliases=["host_name"], elements="str"), + minutes=dict(type="int", required=False, default=10), + host_groups=dict(type="list", required=False, + default=None, aliases=["host_group"], elements="str"), + name=dict(type="str", required=True), + desc=dict(type="str", required=False, default="Created by Ansible"), + collect_data=dict(type="bool", required=False, default=True), + visible_name=dict(type="bool", required=False, default=True), tags=dict( - type='list', - elements='dict', + type="list", + elements="dict", required=False, options=dict( - tag=dict(type='str', required=True), - operator=dict(type='int', default=2), - value=dict(type='str', default='') + tag=dict(type="str", required=True), + operator=dict(type="int", default=2), + value=dict(type="str", default="") ) ) )) @@ -387,23 +358,17 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - maint = MaintenanceModule(module) - host_names = module.params['host_names'] - host_groups = module.params['host_groups'] - state = module.params['state'] - minutes = module.params['minutes'] - name = module.params['name'] - desc = module.params['desc'] - collect_data = module.params['collect_data'] - visible_name = module.params['visible_name'] - tags = module.params['tags'] + host_names = module.params["host_names"] + host_groups = module.params["host_groups"] + state = module.params["state"] + minutes = module.params["minutes"] + name = module.params["name"] + desc = module.params["desc"] + collect_data = module.params["collect_data"] + visible_name = module.params["visible_name"] + tags = module.params["tags"] if collect_data: maintenance_type = 0 @@ -494,5 +459,5 @@ def main(): module.exit_json(changed=changed) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_map.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_map.py index 175b96df6..a0f3cc655 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_map.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_map.py @@ -7,7 +7,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_map author: @@ -37,7 +37,7 @@ description: C(zbx_trigger_color) contains indicator color specified either as CSS3 name or as a hexadecimal code starting with C(#). C(zbx_trigger_draw_style) contains indicator draw style. Possible values are the same as for C(zbx_draw_style)." requirements: - - "python >= 2.6" + - "python >= 3.9" - pydotplus - webcolors - Pillow @@ -61,7 +61,7 @@ options: - On C(present), it will create if map does not exist or update the map if the associated data is different. - On C(absent) will remove the map if it exists. required: false - choices: ['present', 'absent'] + choices: ["present", "absent"] default: "present" type: str width: @@ -98,7 +98,7 @@ options: description: - Map element label type. required: false - choices: ['label', 'ip', 'name', 'status', 'nothing', 'custom'] + choices: ["label", "ip", "name", "status", "nothing", "custom"] default: "name" type: str default_image: @@ -111,21 +111,21 @@ options: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -RETURN = r''' # ''' +RETURN = r""" # """ -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 ### @@ -139,7 +139,7 @@ EXAMPLES = r''' ### ### Each inventory host is present in Zabbix with a matching name. ### -### Contents of 'map.j2': +### Contents of "map.j2": # digraph G { # graph [layout=dot splines=false overlap=scale] # INTERNET [zbx_url="Google:https://google.com" zbx_image="Cloud_(96)"] @@ -168,7 +168,7 @@ EXAMPLES = r''' # } # } ### -### Create Zabbix map "Demo Map" made of template 'map.j2' +### Create Zabbix map "Demo Map" made of template "map.j2" - name: Create Zabbix map # set task level variables as we change ansible_connection plugin here vars: @@ -177,7 +177,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_map: name: Demo map @@ -189,7 +189,7 @@ EXAMPLES = r''' label_type: label delegate_to: localhost run_once: yes -''' +""" import base64 @@ -201,7 +201,6 @@ from operator import itemgetter from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils @@ -234,17 +233,17 @@ except ImportError: class Map(ZabbixBase): def __init__(self, module, zbx=None, zapi_wrapper=None): super(Map, self).__init__(module, zbx, zapi_wrapper) - self.map_name = module.params['name'] - self.dot_data = module.params['data'] - self.width = module.params['width'] - self.height = module.params['height'] - self.state = module.params['state'] - self.default_image = module.params['default_image'] + self.map_name = module.params["name"] + self.dot_data = module.params["data"] + self.width = module.params["width"] + self.height = module.params["height"] + self.state = module.params["state"] + self.default_image = module.params["default_image"] self.map_id = self._get_sysmap_id(self.map_name) - self.margin = module.params['margin'] - self.expand_problem = module.params['expand_problem'] - self.highlight = module.params['highlight'] - self.label_type = module.params['label_type'] + self.margin = module.params["margin"] + self.expand_problem = module.params["expand_problem"] + self.highlight = module.params["highlight"] + self.label_type = module.params["label_type"] self.selements_sort_keys = self._get_selements_sort_keys() def _build_graph(self): @@ -265,25 +264,25 @@ class Map(ZabbixBase): edges = self._get_graph_edges(graph) icon_ids = self._get_icon_ids() map_config = { - 'name': self.map_name, - 'label_type': self._get_label_type_id(self.label_type), - 'expandproblem': int(self.expand_problem), - 'highlight': int(self.highlight), - 'width': self.width, - 'height': self.height, - 'selements': self._get_selements(graph, nodes, icon_ids), - 'links': self._get_links(nodes, edges), + "name": self.map_name, + "label_type": self._get_label_type_id(self.label_type), + "expandproblem": int(self.expand_problem), + "highlight": int(self.highlight), + "width": self.width, + "height": self.height, + "selements": self._get_selements(graph, nodes, icon_ids), + "links": self._get_links(nodes, edges), } return map_config def _get_label_type_id(self, label_type): label_type_ids = { - 'label': 0, - 'ip': 1, - 'name': 2, - 'status': 3, - 'nothing': 4, - 'custom': 5, + "label": 0, + "ip": 1, + "name": 2, + "status": 3, + "nothing": 4, + "custom": 5, } try: label_type_id = label_type_ids[label_type] @@ -294,82 +293,73 @@ class Map(ZabbixBase): def _get_images_info(self, data, icon_ids): images = [ { - 'dot_tag': 'zbx_image', - 'zbx_property': 'iconid_off', - 'mandatory': True + "dot_tag": "zbx_image", + "zbx_property": "iconid_off", + "mandatory": True }, { - 'dot_tag': 'zbx_image_disabled', - 'zbx_property': 'iconid_disabled', - 'mandatory': False + "dot_tag": "zbx_image_disabled", + "zbx_property": "iconid_disabled", + "mandatory": False }, { - 'dot_tag': 'zbx_image_maintenance', - 'zbx_property': 'iconid_maintenance', - 'mandatory': False + "dot_tag": "zbx_image_maintenance", + "zbx_property": "iconid_maintenance", + "mandatory": False }, { - 'dot_tag': 'zbx_image_problem', - 'zbx_property': 'iconid_on', - 'mandatory': False + "dot_tag": "zbx_image_problem", + "zbx_property": "iconid_on", + "mandatory": False } ] images_info = {} default_image = self.default_image if self.default_image else sorted(icon_ids.items())[0][0] for image in images: - image_name = data.get(image['dot_tag'], None) + image_name = data.get(image["dot_tag"], None) if not image_name: - if image['mandatory']: + if image["mandatory"]: image_name = default_image else: continue image_name = remove_quotes(image_name) if image_name in icon_ids: - images_info[image['zbx_property']] = icon_ids[image_name] - if not image['mandatory']: - images_info['use_iconmap'] = 0 + images_info[image["zbx_property"]] = icon_ids[image_name] + if not image["mandatory"]: + images_info["use_iconmap"] = 0 else: self._module.fail_json(msg="Failed to find id for image '%s'" % image_name) return images_info def _get_element_type(self, data): types = { - 'host': 0, - 'sysmap': 1, - 'trigger': 2, - 'group': 3, - 'image': 4 + "host": 0, + "sysmap": 1, + "trigger": 2, + "group": 3, + "image": 4 } element_type = { - 'elementtype': types['image'], + "elementtype": types["image"], } - if LooseVersion(self._zbx_api_version) < LooseVersion('3.4'): - element_type.update({ - 'elementid': "0", - }) for type_name, type_id in sorted(types.items()): - field_name = 'zbx_' + type_name + field_name = "zbx_" + type_name if field_name in data: - method_name = '_get_' + type_name + '_id' + method_name = "_get_" + type_name + "_id" element_name = remove_quotes(data[field_name]) get_element_id = getattr(self, method_name, None) if get_element_id: elementid = get_element_id(element_name) if elementid and int(elementid) > 0: element_type.update({ - 'elementtype': type_id, - 'label': element_name + "elementtype": type_id, + "label": element_name + }) + element_type.update({ + "elements": [{ + type_name + "id": elementid, + }], }) - if LooseVersion(self._zbx_api_version) < LooseVersion('3.4'): - element_type.update({ - 'elementid': elementid, - }) - else: - element_type.update({ - 'elements': [{ - type_name + 'id': elementid, - }], - }) break else: self._module.fail_json(msg="Failed to find id for %s '%s'" % (type_name, element_name)) @@ -382,30 +372,30 @@ class Map(ZabbixBase): scales = self._get_scales(graph) for selementid, (node, data) in enumerate(nodes.items(), start=1): selement = { - 'selementid': selementid + "selementid": selementid } - data['selementid'] = selementid + data["selementid"] = selementid images_info = self._get_images_info(data, icon_ids) selement.update(images_info) - image_id = images_info['iconid_off'] + image_id = images_info["iconid_off"] if image_id not in icon_sizes: icon_sizes[image_id] = self._get_icon_size(image_id) - pos = self._convert_coordinates(data['pos'], scales, icon_sizes[image_id]) + pos = self._convert_coordinates(data["pos"], scales, icon_sizes[image_id]) selement.update(pos) - selement['label'] = remove_quotes(node) + selement["label"] = remove_quotes(node) element_type = self._get_element_type(data) selement.update(element_type) label = self._get_label(data) if label: - selement['label'] = label + selement["label"] = label urls = self._get_urls(data) if urls: - selement['urls'] = urls + selement["urls"] = urls selements.append(selement) return selements @@ -413,35 +403,35 @@ class Map(ZabbixBase): def _get_links(self, nodes, edges): links = {} for edge in edges: - link_id = tuple(sorted(edge.obj_dict['points'])) + link_id = tuple(sorted(edge.obj_dict["points"])) node1, node2 = link_id - data = edge.obj_dict['attributes'] + data = edge.obj_dict["attributes"] - if "style" in data and data['style'] == "invis": + if "style" in data and data["style"] == "invis": continue if link_id not in links: links[link_id] = { - 'selementid1': min(nodes[node1]['selementid'], nodes[node2]['selementid']), - 'selementid2': max(nodes[node1]['selementid'], nodes[node2]['selementid']), + "selementid1": min(nodes[node1]["selementid"], nodes[node2]["selementid"]), + "selementid2": max(nodes[node1]["selementid"], nodes[node2]["selementid"]), } link = links[link_id] if "color" not in link: - link['color'] = self._get_color_hex(remove_quotes(data.get('color', 'green'))) + link["color"] = self._get_color_hex(remove_quotes(data.get("color", "green"))) if "zbx_draw_style" not in link: - link['drawtype'] = self._get_link_draw_style_id(remove_quotes(data.get('zbx_draw_style', 'line'))) + link["drawtype"] = self._get_link_draw_style_id(remove_quotes(data.get("zbx_draw_style", "line"))) label = self._get_label(data) if label and "label" not in link: - link['label'] = label + link["label"] = label triggers = self._get_triggers(data) if triggers: if "linktriggers" not in link: - link['linktriggers'] = [] - link['linktriggers'] += triggers + link["linktriggers"] = [] + link["linktriggers"] += triggers return list(links.values()) @@ -449,12 +439,12 @@ class Map(ZabbixBase): urls = [] for url_raw in [remove_quotes(value) for key, value in data.items() if key.startswith("zbx_url")]: try: - name, url = url_raw.split(':', 1) + name, url = url_raw.split(":", 1) except Exception as e: self._module.fail_json(msg="Failed to parse zbx_url='%s': %s" % (url_raw, e)) urls.append({ - 'name': name, - 'url': url, + "name": name, + "url": url, }) return urls @@ -464,9 +454,9 @@ class Map(ZabbixBase): triggerid = self._get_trigger_id(trigger_definition) if triggerid: triggers.append({ - 'triggerid': triggerid, - 'color': self._get_color_hex(remove_quotes(data.get('zbx_trigger_color', 'red'))), - 'drawtype': self._get_link_draw_style_id(remove_quotes(data.get('zbx_trigger_draw_style', 'bold'))), + "triggerid": triggerid, + "color": self._get_color_hex(remove_quotes(data.get("zbx_trigger_color", "red"))), + "drawtype": self._get_link_draw_style_id(remove_quotes(data.get("zbx_trigger_draw_style", "bold"))), }) else: self._module.fail_json(msg="Failed to find trigger '%s'" % (trigger_definition)) @@ -475,23 +465,23 @@ class Map(ZabbixBase): @staticmethod def _get_label(data, default=None): if "zbx_label" in data: - label = remove_quotes(data['zbx_label']).replace('\\n', '\n') + label = remove_quotes(data["zbx_label"]).replace("\\n", "\n") elif "label" in data: - label = remove_quotes(data['label']) + label = remove_quotes(data["label"]) else: label = default return label def _get_sysmap_id(self, map_name): - exist_map = self._zapi.map.get({'filter': {'name': map_name}}) + exist_map = self._zapi.map.get({"filter": {"name": map_name}}) if exist_map: - return exist_map[0]['sysmapid'] + return exist_map[0]["sysmapid"] return None def _get_group_id(self, group_name): - exist_group = self._zapi.hostgroup.get({'filter': {'name': group_name}}) + exist_group = self._zapi.hostgroup.get({"filter": {"name": group_name}}) if exist_group: - return exist_group[0]['groupid'] + return exist_group[0]["groupid"] return None def map_exists(self): @@ -513,7 +503,7 @@ class Map(ZabbixBase): try: if self._module.check_mode: self._module.exit_json(changed=True) - map_config['sysmapid'] = self.map_id + map_config["sysmapid"] = self.map_id result = self._zapi.map.update(map_config) if result: return result @@ -532,24 +522,22 @@ class Map(ZabbixBase): def is_exist_map_correct(self, generated_map_config): exist_map_configs = self._zapi.map.get({ - 'sysmapids': self.map_id, - 'selectLinks': 'extend', - 'selectSelements': 'extend' + "sysmapids": self.map_id, + "selectLinks": "extend", + "selectSelements": "extend" }) exist_map_config = exist_map_configs[0] if not self._is_dicts_equal(generated_map_config, exist_map_config): return False - if not self._is_selements_equal(generated_map_config['selements'], exist_map_config['selements']): + if not self._is_selements_equal(generated_map_config["selements"], exist_map_config["selements"]): return False self._update_ids(generated_map_config, exist_map_config) - if not self._is_links_equal(generated_map_config['links'], exist_map_config['links']): + if not self._is_links_equal(generated_map_config["links"], exist_map_config["links"]): return False return True def _get_selements_sort_keys(self): - keys_to_sort = ['label'] - if LooseVersion(self._zbx_api_version) < LooseVersion('3.4'): - keys_to_sort.insert(0, 'elementid') + keys_to_sort = ["label"] return keys_to_sort def _is_selements_equal(self, generated_selements, exist_selements): @@ -558,22 +546,21 @@ class Map(ZabbixBase): generated_selements_sorted = sorted(generated_selements, key=itemgetter(*self.selements_sort_keys)) exist_selements_sorted = sorted(exist_selements, key=itemgetter(*self.selements_sort_keys)) for (generated_selement, exist_selement) in zip(generated_selements_sorted, exist_selements_sorted): - if LooseVersion(self._zbx_api_version) >= LooseVersion('3.4'): - if not self._is_elements_equal(generated_selement.get('elements', []), exist_selement.get('elements', [])): - return False - if not self._is_dicts_equal(generated_selement, exist_selement, ['selementid']): + if not self._is_elements_equal(generated_selement.get("elements", []), exist_selement.get("elements", [])): return False - if not self._is_urls_equal(generated_selement.get('urls', []), exist_selement.get('urls', [])): + if not self._is_dicts_equal(generated_selement, exist_selement, ["selementid"]): + return False + if not self._is_urls_equal(generated_selement.get("urls", []), exist_selement.get("urls", [])): return False return True def _is_urls_equal(self, generated_urls, exist_urls): if len(generated_urls) != len(exist_urls): return False - generated_urls_sorted = sorted(generated_urls, key=itemgetter('name', 'url')) - exist_urls_sorted = sorted(exist_urls, key=itemgetter('name', 'url')) + generated_urls_sorted = sorted(generated_urls, key=itemgetter("name", "url")) + exist_urls_sorted = sorted(exist_urls, key=itemgetter("name", "url")) for (generated_url, exist_url) in zip(generated_urls_sorted, exist_urls_sorted): - if not self._is_dicts_equal(generated_url, exist_url, ['selementid']): + if not self._is_dicts_equal(generated_url, exist_url, ["selementid"]): return False return True @@ -583,40 +570,40 @@ class Map(ZabbixBase): generated_elements_sorted = sorted(generated_elements, key=lambda k: k.values()[0]) exist_elements_sorted = sorted(exist_elements, key=lambda k: k.values()[0]) for (generated_element, exist_element) in zip(generated_elements_sorted, exist_elements_sorted): - if not self._is_dicts_equal(generated_element, exist_element, ['selementid']): + if not self._is_dicts_equal(generated_element, exist_element, ["selementid"]): return False return True # since generated IDs differ from real Zabbix ones, make real IDs match generated ones def _update_ids(self, generated_map_config, exist_map_config): - generated_selements_sorted = sorted(generated_map_config['selements'], key=itemgetter(*self.selements_sort_keys)) - exist_selements_sorted = sorted(exist_map_config['selements'], key=itemgetter(*self.selements_sort_keys)) + generated_selements_sorted = sorted(generated_map_config["selements"], key=itemgetter(*self.selements_sort_keys)) + exist_selements_sorted = sorted(exist_map_config["selements"], key=itemgetter(*self.selements_sort_keys)) id_mapping = {} for (generated_selement, exist_selement) in zip(generated_selements_sorted, exist_selements_sorted): - id_mapping[exist_selement['selementid']] = generated_selement['selementid'] - for link in exist_map_config['links']: - link['selementid1'] = id_mapping[link['selementid1']] - link['selementid2'] = id_mapping[link['selementid2']] - if link['selementid2'] < link['selementid1']: - link['selementid1'], link['selementid2'] = link['selementid2'], link['selementid1'] + id_mapping[exist_selement["selementid"]] = generated_selement["selementid"] + for link in exist_map_config["links"]: + link["selementid1"] = id_mapping[link["selementid1"]] + link["selementid2"] = id_mapping[link["selementid2"]] + if link["selementid2"] < link["selementid1"]: + link["selementid1"], link["selementid2"] = link["selementid2"], link["selementid1"] def _is_links_equal(self, generated_links, exist_links): if len(generated_links) != len(exist_links): return False - generated_links_sorted = sorted(generated_links, key=itemgetter('selementid1', 'selementid2', 'color', 'drawtype')) - exist_links_sorted = sorted(exist_links, key=itemgetter('selementid1', 'selementid2', 'color', 'drawtype')) + generated_links_sorted = sorted(generated_links, key=itemgetter("selementid1", "selementid2", "color", "drawtype")) + exist_links_sorted = sorted(exist_links, key=itemgetter("selementid1", "selementid2", "color", "drawtype")) for (generated_link, exist_link) in zip(generated_links_sorted, exist_links_sorted): - if not self._is_dicts_equal(generated_link, exist_link, ['selementid1', 'selementid2']): + if not self._is_dicts_equal(generated_link, exist_link, ["selementid1", "selementid2"]): return False - if not self._is_triggers_equal(generated_link.get('linktriggers', []), exist_link.get('linktriggers', [])): + if not self._is_triggers_equal(generated_link.get("linktriggers", []), exist_link.get("linktriggers", [])): return False return True def _is_triggers_equal(self, generated_triggers, exist_triggers): if len(generated_triggers) != len(exist_triggers): return False - generated_triggers_sorted = sorted(generated_triggers, key=itemgetter('triggerid')) - exist_triggers_sorted = sorted(exist_triggers, key=itemgetter('triggerid')) + generated_triggers_sorted = sorted(generated_triggers, key=itemgetter("triggerid")) + exist_triggers_sorted = sorted(exist_triggers, key=itemgetter("triggerid")) for (generated_trigger, exist_trigger) in zip(generated_triggers_sorted, exist_triggers_sorted): if not self._is_dicts_equal(generated_trigger, exist_trigger): return False @@ -637,40 +624,40 @@ class Map(ZabbixBase): return True def _get_host_id(self, hostname): - hostid = self._zapi.host.get({'filter': {'host': hostname}}) + hostid = self._zapi.host.get({"filter": {"host": hostname}}) if hostid: - return str(hostid[0]['hostid']) + return str(hostid[0]["hostid"]) def _get_trigger_id(self, trigger_definition): try: - host, trigger = trigger_definition.split(':', 1) + host, trigger = trigger_definition.split(":", 1) except Exception as e: self._module.fail_json(msg="Failed to parse zbx_trigger='%s': %s" % (trigger_definition, e)) triggerid = self._zapi.trigger.get({ - 'host': host, - 'filter': { - 'description': trigger + "host": host, + "filter": { + "description": trigger } }) if triggerid: - return str(triggerid[0]['triggerid']) + return str(triggerid[0]["triggerid"]) def _get_icon_ids(self): icons_list = self._zapi.image.get({}) icon_ids = {} for icon in icons_list: - icon_ids[icon['name']] = icon['imageid'] + icon_ids[icon["name"]] = icon["imageid"] return icon_ids def _get_icon_size(self, icon_id): icons_list = self._zapi.image.get({ - 'imageids': [ + "imageids": [ icon_id ], - 'select_image': True + "select_image": True }) if len(icons_list) > 0: - icon_base64 = icons_list[0]['image'] + icon_base64 = icons_list[0]["image"] else: self._module.fail_json(msg="Failed to find image with id %s" % icon_id) image = Image.open(BytesIO(base64.b64decode(icon_base64))) @@ -681,19 +668,19 @@ class Map(ZabbixBase): def _get_node_attributes(node): attr = {} if "attributes" in node.obj_dict: - attr.update(node.obj_dict['attributes']) + attr.update(node.obj_dict["attributes"]) pos = node.get_pos() if pos is not None: pos = remove_quotes(pos) xx, yy = pos.split(",") - attr['pos'] = (float(xx), float(yy)) + attr["pos"] = (float(xx), float(yy)) return attr def _get_graph_nodes(self, parent): nodes = {} for node in parent.get_nodes(): node_name = node.get_name() - if node_name in ('node', 'graph', 'edge'): + if node_name in ("node", "graph", "edge"): continue nodes[node_name] = self._get_node_attributes(node) for subgraph in parent.get_subgraphs(): @@ -714,38 +701,38 @@ class Map(ZabbixBase): scale_x = (self.width - self.margin * 2) / (float(max_x) - float(min_x)) if float(max_x) != float(min_x) else 0 scale_y = (self.height - self.margin * 2) / (float(max_y) - float(min_y)) if float(max_y) != float(min_y) else 0 return { - 'min_x': float(min_x), - 'min_y': float(min_y), - 'max_x': float(max_x), - 'max_y': float(max_y), - 'scale_x': float(scale_x), - 'scale_y': float(scale_y), + "min_x": float(min_x), + "min_y": float(min_y), + "max_x": float(max_x), + "max_y": float(max_y), + "scale_x": float(scale_x), + "scale_y": float(scale_y), } # transform Graphviz coordinates to Zabbix's ones def _convert_coordinates(self, pos, scales, icon_size): return { - 'x': int((pos[0] - scales['min_x']) * scales['scale_x'] - icon_size[0] / 2 + self.margin), - 'y': int((scales['max_y'] - pos[1] + scales['min_y']) * scales['scale_y'] - icon_size[1] / 2 + self.margin), + "x": int((pos[0] - scales["min_x"]) * scales["scale_x"] - icon_size[0] / 2 + self.margin), + "y": int((scales["max_y"] - pos[1] + scales["min_y"]) * scales["scale_y"] - icon_size[1] / 2 + self.margin), } def _get_color_hex(self, color_name): - if color_name.startswith('#'): + if color_name.startswith("#"): color_hex = color_name else: try: color_hex = webcolors.name_to_hex(color_name) except Exception as e: self._module.fail_json(msg="Failed to get RGB hex for color '%s': %s" % (color_name, e)) - color_hex = color_hex.strip('#').upper() + color_hex = color_hex.strip("#").upper() return color_hex def _get_link_draw_style_id(self, draw_style): draw_style_ids = { - 'line': 0, - 'bold': 2, - 'dotted': 3, - 'dashed': 4 + "line": 0, + "bold": 2, + "dotted": 3, + "dashed": 4 } try: draw_style_id = draw_style_ids[draw_style] @@ -764,34 +751,28 @@ def remove_quotes(s): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - name=dict(type='str', required=True, aliases=['map_name']), - data=dict(type='str', required=False, aliases=['dot_data']), - width=dict(type='int', default=800), - height=dict(type='int', default=600), - state=dict(type='str', default="present", choices=['present', 'absent']), - default_image=dict(type='str', required=False, aliases=['image']), - margin=dict(type='int', default=40), - expand_problem=dict(type='bool', default=True), - highlight=dict(type='bool', default=True), - label_type=dict(type='str', default='name', choices=['label', 'ip', 'name', 'status', 'nothing', 'custom']), + name=dict(type="str", required=True, aliases=["map_name"]), + data=dict(type="str", required=False, aliases=["dot_data"]), + width=dict(type="int", default=800), + height=dict(type="int", default=600), + state=dict(type="str", default="present", choices=["present", "absent"]), + default_image=dict(type="str", required=False, aliases=["image"]), + margin=dict(type="int", default=40), + expand_problem=dict(type="bool", default=True), + highlight=dict(type="bool", default=True), + label_type=dict(type="str", default="name", choices=["label", "ip", "name", "status", "nothing", "custom"]), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - if not HAS_PYDOTPLUS: - module.fail_json(msg=missing_required_lib('pydotplus', url='https://pypi.org/project/pydotplus/'), exception=PYDOT_IMP_ERR) + module.fail_json(msg=missing_required_lib("pydotplus", url="https://pypi.org/project/pydotplus/"), exception=PYDOT_IMP_ERR) if not HAS_WEBCOLORS: - module.fail_json(msg=missing_required_lib('webcolors', url='https://pypi.org/project/webcolors/'), exception=WEBCOLORS_IMP_ERR) + module.fail_json(msg=missing_required_lib("webcolors", url="https://pypi.org/project/webcolors/"), exception=WEBCOLORS_IMP_ERR) if not HAS_PIL: - module.fail_json(msg=missing_required_lib('Pillow', url='https://pypi.org/project/Pillow/'), exception=PIL_IMP_ERR) + module.fail_json(msg=missing_required_lib("Pillow", url="https://pypi.org/project/Pillow/"), exception=PIL_IMP_ERR) sysmap = Map(module) @@ -814,5 +795,5 @@ def main(): module.exit_json(changed=True, result="Successfully created map: %s" % sysmap.map_name) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_mediatype.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_mediatype.py index c5693f467..1e2514bf3 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_mediatype.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_mediatype.py @@ -7,7 +7,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_mediatype short_description: Create/Update/Delete Zabbix media types @@ -16,22 +16,21 @@ description: author: - Ruben Tsirunyan (@rubentsirunyan) requirements: - - "python >= 2.6" + - "python >= 3.9" options: name: - type: 'str' + type: "str" description: - Name of the media type. required: true description: - type: 'str' + type: "str" description: - Description of the media type. - - Works only with Zabbix versions 4.4 or newer. - default: '' + default: "" state: - type: 'str' + type: "str" description: - Desired state of the mediatype. - On C(present), it will create a mediatype if it does not exist or update the mediatype if the associated data is different. @@ -39,13 +38,12 @@ options: choices: - present - absent - default: 'present' + default: "present" type: - type: 'str' + type: "str" description: - Type of the media type. - Media types I(jabber) and I(ez_texting) works only with Zabbix versions 4.2 or older. - - Media type I(webhook) works only with Zabbix versions 4.4 or newer. choices: - email - script @@ -55,93 +53,90 @@ options: - ez_texting required: true status: - type: 'str' + type: "str" description: - Whether the media type is enabled or no. choices: - enabled - disabled - default: 'enabled' + default: "enabled" max_sessions: - type: 'int' + type: "int" description: - The maximum number of alerts that can be processed in parallel. - Possible value is 1 when I(type=sms) and 0-100 otherwise. - - Works only with Zabbix versions 3.4 or newer. default: 1 max_attempts: - type: 'int' + type: "int" description: - The maximum number of attempts to send an alert. - Possible range is 0-10. - - Works only with Zabbix versions 3.4 or newer. default: 3 attempt_interval: - type: 'str' + type: "str" description: - The interval between retry attempts. - - Possible range is 0-60s in Zabbix < 5.0 or 0-1h in Zabbix >= 5.0. - - Works only with Zabbix versions 3.4 or newer. + - Possible range is 0-1h. default: 10s script_name: - type: 'str' + type: "str" description: - The name of the executed script. - Required when I(type=script). script_params: - type: 'list' + type: "list" elements: str description: - List of script parameters. - Required when I(type=script). gsm_modem: - type: 'str' + type: "str" description: - Serial device name of the gsm modem. - Required when I(type=sms). username: - type: 'str' + type: "str" description: - Username or Jabber identifier. - Required when I(type=jabber) or I(type=ez_texting). - Required when I(type=email) and I(smtp_authentication=true). password: - type: 'str' + type: "str" description: - Authentication password. - Required when I(type=jabber) or I(type=ez_texting). - Required when I(type=email) and I(smtp_authentication=true). smtp_server: - type: 'str' + type: "str" description: - SMTP server host. - Required when I(type=email). - default: 'localhost' + default: "localhost" smtp_server_port: - type: 'int' + type: "int" description: - SMTP server port. - Required when I(type=email). default: 25 smtp_helo: - type: 'str' + type: "str" description: - SMTP HELO. - Required when I(type=email). - default: 'localhost' + default: "localhost" smtp_email: - type: 'str' + type: "str" description: - Email address from which notifications will be sent. - Required when I(type=email). smtp_authentication: - type: 'bool' + type: "bool" description: - Whether SMTP authentication with username and password should be enabled or not. - If set to C(true), C(username) and C(password) should be specified. default: false smtp_security: - type: 'str' + type: "str" description: - SMTP connection security level to use. choices: @@ -149,19 +144,19 @@ options: - STARTTLS - SSL/TLS smtp_verify_host: - type: 'bool' + type: "bool" description: - SSL verify host for SMTP. - Can be specified when I(smtp_security=STARTTLS) or I(smtp_security=SSL/TLS) default: false smtp_verify_peer: - type: 'bool' + type: "bool" description: - SSL verify peer for SMTP. - Can be specified when I(smtp_security=STARTTLS) or I(smtp_security=SSL/TLS) default: false message_text_limit: - type: 'str' + type: "str" description: - The message text limit. - Required when I(type=ez_texting). @@ -170,74 +165,72 @@ options: - USA - Canada webhook_script: - type: 'str' + type: "str" description: - Required when I(type=webhook). - JavaScript code that will perform webhook operation. - This code has access to all parameters in I(webhook_params). - It may perform HTTP GET, POST, PUT and DELETE requests and has control over HTTP headers and request body. - It may return OK status along with an optional list of tags and tag values or an error string. - - Works only with Zabbix versions 4.4 or newer. webhook_timeout: - type: 'str' + type: "str" description: - Can be used when I(type=webhook). - Execution timeout for JavaScript code in I(webhook_script). - Possible values are 1-60s. default: 30s process_tags: - type: 'bool' + type: "bool" description: - Can be used when I(type=webhook). - Process returned JSON property values as tags. - These tags are added to the already existing (if any) problem event tags in Zabbix. default: false event_menu: - type: 'bool' + type: "bool" description: - Can be used when I(type=webhook). - Includes entry in Event menu with link to created external ticket. default: false event_menu_url: - type: 'str' + type: "str" description: - Requred when I(event_menu=true). - Event menu entry underlying URL. event_menu_name: - type: 'str' + type: "str" description: - Requred when I(event_menu=true). - Event menu entry name. webhook_params: - type: 'list' - elements: 'dict' + type: "list" + elements: "dict" description: - Can be used when I(type=webhook). - Webhook variables that are passed to webhook script when executed. default: [] suboptions: name: - type: 'str' + type: "str" description: - Name of the parameter. required: true value: - type: 'str' + type: "str" description: - Value of the parameter. - All macros that are supported in problem notifications are supported in the parameters. - Values are URL-encoded automatically. Values from macros are resolved and then URL-encoded automatically. - default: '' + default: "" message_templates: - type: 'list' - elements: 'dict' + type: "list" + elements: "dict" description: - Default notification messages for the event types. - - Works only with Zabbix versions 5.0 or newer. default: [] suboptions: eventsource: - type: 'str' + type: "str" description: - Event source. - Required when I(recovery) is used. @@ -247,7 +240,7 @@ options: - autoregistration - internal recovery: - type: 'str' + type: "str" description: - Operation mode. - Required when I(eventsource) is used. @@ -256,40 +249,40 @@ options: - recovery_operations - update_operations subject: - type: 'str' + type: "str" description: - Subject of the default message. - May contain macros and is limited to 255 characters. - default: '' + default: "" body: - type: 'str' + type: "str" description: - Body of the default message. - May contain macros. - default: '' + default: "" extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -RETURN = r''' # ''' +RETURN = r""" # """ -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 -- name: 'Create an email mediatype with SMTP authentication' +- name: "Create an email mediatype with SMTP authentication" # set task level variables as we change ansible_connection plugin here vars: ansible_network_os: community.zabbix.zabbix @@ -297,19 +290,19 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_mediatype: name: "Ops email" - type: 'email' - smtp_server: 'example.com' + type: "email" + smtp_server: "example.com" smtp_server_port: 2000 - smtp_email: 'ops@example.com' + smtp_email: "ops@example.com" smtp_authentication: true - username: 'smtp_user' - password: 'smtp_pass' + username: "smtp_user" + password: "smtp_pass" -- name: 'Create a script mediatype' +- name: "Create a script mediatype" # set task level variables as we change ansible_connection plugin here vars: ansible_network_os: community.zabbix.zabbix @@ -317,17 +310,17 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_mediatype: name: "my script" - type: 'script' - script_name: 'my_script.py' + type: "script" + script_name: "my_script.py" script_params: - - 'arg1' - - 'arg2' + - "arg1" + - "arg2" -- name: 'Create a jabber mediatype' +- name: "Create a jabber mediatype" # set task level variables as we change ansible_connection plugin here vars: ansible_network_os: community.zabbix.zabbix @@ -335,15 +328,15 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_mediatype: name: "My jabber" - type: 'jabber' - username: 'jabber_id' - password: 'jabber_pass' + type: "jabber" + username: "jabber_id" + password: "jabber_pass" -- name: 'Create a SMS mediatype' +- name: "Create a SMS mediatype" # set task level variables as we change ansible_connection plugin here vars: ansible_network_os: community.zabbix.zabbix @@ -351,15 +344,14 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_mediatype: name: "My SMS Mediatype" - type: 'sms' - gsm_modem: '/dev/ttyS0' + type: "sms" + gsm_modem: "/dev/ttyS0" -# Supported since Zabbix 4.4 -- name: 'Create a webhook mediatype' +- name: "Create a webhook mediatype" # set task level variables as we change ansible_connection plugin here vars: ansible_network_os: community.zabbix.zabbix @@ -367,24 +359,23 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_mediatype: name: "My webhook Mediatype" - type: 'webhook' + type: "webhook" webhook_script: "{{ lookup('file', 'slack.js') }}" webhook_params: - name: alert_message - value: '{ALERT.MESSAGE}' + value: "{ALERT.MESSAGE}" - name: zabbix_url - value: '{$ZABBIX.URL}' + value: "{$ZABBIX.URL}" process_tags: true event_menu: true event_menu_name: "Open in Slack: '{EVENT.TAGS.__channel_name}'" - event_menu_url: '{EVENT.TAGS.__message_link}' + event_menu_url: "{EVENT.TAGS.__message_link}" -# Supported since Zabbix 5.0 -- name: 'Create an email mediatype with message templates' +- name: "Create an email mediatype with message templates" # set task level variables as we change ansible_connection plugin here vars: ansible_network_os: community.zabbix.zabbix @@ -392,12 +383,12 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_mediatype: name: "Ops email" - type: 'email' - smtp_email: 'ops@example.com' + type: "email" + smtp_email: "ops@example.com" message_templates: - eventsource: triggers recovery: operations @@ -419,7 +410,7 @@ EXAMPLES = r''' recovery: operations subject: "Autoregistration: {HOST.HOST}" body: "Host name: {HOST.HOST}\r\nHost IP: {HOST.IP}\r\nAgent port: {HOST.PORT}" -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -446,10 +437,10 @@ def diff(existing, new): for key in new: before[key] = existing[key] if new[key] is None: - after[key] = '' + after[key] = "" else: after[key] = new[key] - return {'before': before, 'after': after} + return {"before": before, "after": after} class MediaTypeModule(ZabbixBase): @@ -462,20 +453,18 @@ class MediaTypeModule(ZabbixBase): Returns: Tuple of (True, `id of the mediatype`) if mediatype exists, (False, None) otherwise """ - filter_key_name = 'description' - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.4'): - # description key changed to name key from zabbix 4.4 - filter_key_name = 'name' + filter_key_name = "description" + filter_key_name = "name" try: mediatype_list = self._zapi.mediatype.get({ - 'output': 'extend', - 'filter': {filter_key_name: [name]} + "output": "extend", + "filter": {filter_key_name: [name]} }) if len(mediatype_list) < 1: return False, None else: - return True, mediatype_list[0]['mediatypeid'] + return True, mediatype_list[0]["mediatypeid"] except Exception as e: self._module.fail_json(msg="Failed to get ID of the mediatype '{name}': {e}".format(name=name, e=e)) @@ -487,127 +476,104 @@ class MediaTypeModule(ZabbixBase): A dictionary of arguments that are related to transport type, and are in a format that is understandable by Zabbix API. """ - truths = {'False': '0', 'True': '1'} + truths = {"False": "0", "True": "1"} parameters = dict( - status='0' if self._module.params['status'] == 'enabled' else '1', + status="0" if self._module.params["status"] == "enabled" else "1", type={ - 'email': '0', - 'script': '1', - 'sms': '2', - 'jabber': '3', - 'webhook': '4', - 'ez_texting': '100' - }.get(self._module.params['type']), + "email": "0", + "script": "1", + "sms": "2", + "jabber": "3", + "webhook": "4", + "ez_texting": "100" + }.get(self._module.params["type"]), ) - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.4'): - parameters.update(dict( - name=self._module.params['name'], - description=self._module.params['description'], - )) - else: - parameters.update(dict(description=self._module.params['name'])) + parameters.update(dict( + name=self._module.params["name"], + description=self._module.params["description"], + maxsessions=str(self._module.params["max_sessions"]), + maxattempts=str(self._module.params["max_attempts"]), + attempt_interval=str(self._module.params["attempt_interval"]) + )) - if LooseVersion(self._zbx_api_version) >= LooseVersion('3.4'): - parameters.update(dict( - maxsessions=str(self._module.params['max_sessions']), - maxattempts=str(self._module.params['max_attempts']), - attempt_interval=str(self._module.params['attempt_interval']) - )) - - if self._module.params['message_templates'] and LooseVersion(self._zbx_api_version) >= LooseVersion('5.0'): + if self._module.params["message_templates"]: msg_templates = [] - for template in self._module.params['message_templates']: + for template in self._module.params["message_templates"]: msg_templates.append(dict( eventsource={ - 'triggers': '0', - 'discovery': '1', - 'autoregistration': '2', - 'internal': '3'}.get(template['eventsource']), + "triggers": "0", + "discovery": "1", + "autoregistration": "2", + "internal": "3"}.get(template["eventsource"]), recovery={ - 'operations': '0', - 'recovery_operations': '1', - 'update_operations': '2'}.get(template['recovery']), - subject=template['subject'], - message=template['body'] + "operations": "0", + "recovery_operations": "1", + "update_operations": "2"}.get(template["recovery"]), + subject=template["subject"], + message=template["body"] )) parameters.update(dict(message_templates=msg_templates)) - if self._module.params['type'] == 'email': + if self._module.params["type"] == "email": parameters.update(dict( - smtp_server=self._module.params['smtp_server'], - smtp_port=str(self._module.params['smtp_server_port']), - smtp_helo=self._module.params['smtp_helo'], - smtp_email=self._module.params['smtp_email'], - smtp_security={'None': '0', 'STARTTLS': '1', 'SSL/TLS': '2'}.get(str(self._module.params['smtp_security'])), - smtp_authentication=truths.get(str(self._module.params['smtp_authentication'])), - smtp_verify_host=truths.get(str(self._module.params['smtp_verify_host'])), - smtp_verify_peer=truths.get(str(self._module.params['smtp_verify_peer'])), - username=self._module.params['username'], - passwd=self._module.params['password'] + smtp_server=self._module.params["smtp_server"], + smtp_port=str(self._module.params["smtp_server_port"]), + smtp_helo=self._module.params["smtp_helo"], + smtp_email=self._module.params["smtp_email"], + smtp_security={"None": "0", "STARTTLS": "1", "SSL/TLS": "2"}.get(str(self._module.params["smtp_security"])), + smtp_authentication=truths.get(str(self._module.params["smtp_authentication"])), + smtp_verify_host=truths.get(str(self._module.params["smtp_verify_host"])), + smtp_verify_peer=truths.get(str(self._module.params["smtp_verify_peer"])), + username=self._module.params["username"], + passwd=self._module.params["password"] )) - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - if parameters['smtp_authentication'] == '0': - parameters.pop('username') - parameters.pop('passwd') + if parameters["smtp_authentication"] == "0": + parameters.pop("username") + parameters.pop("passwd") return parameters - elif self._module.params['type'] == 'script': - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): - if self._module.params['script_params'] is None: - _script_params = '' # ZBX-15706 + elif self._module.params["type"] == "script": + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): + if self._module.params["script_params"] is None: + _script_params = "" # ZBX-15706 else: - _script_params = '\n'.join(str(i) for i in self._module.params['script_params']) + '\n' + _script_params = "\n".join(str(i) for i in self._module.params["script_params"]) + "\n" parameters.update(dict( - exec_path=self._module.params['script_name'], + exec_path=self._module.params["script_name"], exec_params=_script_params )) else: _script_params = [] - if self._module.params['script_params']: - for i, val in enumerate(self._module.params['script_params']): - _script_params.append({'sortorder': str(i), 'value': val}) + if self._module.params["script_params"]: + for i, val in enumerate(self._module.params["script_params"]): + _script_params.append({"sortorder": str(i), "value": val}) parameters.update(dict( - exec_path=self._module.params['script_name'], + exec_path=self._module.params["script_name"], parameters=_script_params )) return parameters - elif self._module.params['type'] == 'sms': - parameters.update(dict(gsm_modem=self._module.params['gsm_modem'])) + elif self._module.params["type"] == "sms": + parameters.update(dict(gsm_modem=self._module.params["gsm_modem"])) return parameters - elif self._module.params['type'] == 'webhook' and LooseVersion(self._zbx_api_version) >= LooseVersion('4.4'): + elif self._module.params["type"] == "webhook": parameters.update(dict( - script=self._module.params['webhook_script'], - timeout=self._module.params['webhook_timeout'], - process_tags=truths.get(str(self._module.params['process_tags'])), - show_event_menu=truths.get(str(self._module.params['event_menu'])), - parameters=self._module.params['webhook_params'] + script=self._module.params["webhook_script"], + timeout=self._module.params["webhook_timeout"], + process_tags=truths.get(str(self._module.params["process_tags"])), + show_event_menu=truths.get(str(self._module.params["event_menu"])), + parameters=self._module.params["webhook_params"] )) - if self._module.params['event_menu']: + if self._module.params["event_menu"]: parameters.update(dict( - event_menu_url=self._module.params['event_menu_url'], - event_menu_name=self._module.params['event_menu_name'] + event_menu_url=self._module.params["event_menu_url"], + event_menu_name=self._module.params["event_menu_name"] )) return parameters - elif self._module.params['type'] == 'jabber' and LooseVersion(self._zbx_api_version) <= LooseVersion('4.2'): - parameters.update(dict( - username=self._module.params['username'], - passwd=self._module.params['password'] - )) - return parameters - - elif self._module.params['type'] == 'ez_texting' and LooseVersion(self._zbx_api_version) <= LooseVersion('4.2'): - parameters.update(dict( - username=self._module.params['username'], - passwd=self._module.params['password'], - exec_path={'USA': '0', 'Canada': '1'}.get(self._module.params['message_text_limit']), - )) - return parameters - - self._module.fail_json(msg="%s is unsupported for Zabbix version %s" % (parameters['unsupported_parameter'], parameters['zbx_api_version'])) + self._module.fail_json(msg="%s is unsupported for Zabbix version %s" % (self._module.params["type"], self._zbx_api_version)) def validate_params(self, params): """Validates arguments that are required together. @@ -629,7 +595,7 @@ class MediaTypeModule(ZabbixBase): msg="Following arguments are required when {key} is {value}: {arguments}".format( key=param[0], value=param[1], - arguments=', '.join(param[2]) + arguments=", ".join(param[2]) ) ) @@ -646,35 +612,37 @@ class MediaTypeModule(ZabbixBase): returned by diff() function with existing mediatype data and new params passed to it. """ - get_params = {'output': 'extend', 'mediatypeids': [mediatype_id]} - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.0'): - get_params.update({'selectMessageTemplates': 'extend'}) + get_params = { + "output": "extend", + "mediatypeids": [mediatype_id], + "selectMessageTemplates": "extend" + } existing_mediatype = self._zapi.mediatype.get(get_params)[0] - if existing_mediatype['type'] != kwargs['type']: + if existing_mediatype["type"] != kwargs["type"]: return kwargs, diff(existing_mediatype, kwargs) else: params_to_update = {} for key in kwargs: # sort list of parameters to prevent mismatch due to reordering - if key == 'parameters' and (kwargs[key] != [] or existing_mediatype[key] != []): - if LooseVersion(self._zbx_api_version) < LooseVersion('6.4'): - kwargs[key] = sorted(kwargs[key], key=lambda x: x['name']) - existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x['name']) + if key == "parameters" and (kwargs[key] != [] or existing_mediatype[key] != []): + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): + kwargs[key] = sorted(kwargs[key], key=lambda x: x["name"]) + existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x["name"]) else: - if kwargs['type'] == '1': # script - kwargs[key] = sorted(kwargs[key], key=lambda x: x['sortorder']) - existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x['sortorder']) - elif kwargs['type'] == '4': # webhook - kwargs[key] = sorted(kwargs[key], key=lambda x: x['name']) - existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x['name']) - - if key == 'message_templates' and (kwargs[key] != [] or existing_mediatype[key] != []): - kwargs[key] = sorted(kwargs[key], key=lambda x: x['subject']) - existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x['subject']) - - if (not (kwargs[key] is None and existing_mediatype[key] == '')) and kwargs[key] != existing_mediatype[key]: + if kwargs["type"] == "1": # script + kwargs[key] = sorted(kwargs[key], key=lambda x: x["sortorder"]) + existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x["sortorder"]) + elif kwargs["type"] == "4": # webhook + kwargs[key] = sorted(kwargs[key], key=lambda x: x["name"]) + existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x["name"]) + + if key == "message_templates" and (kwargs[key] != [] or existing_mediatype[key] != []): + kwargs[key] = sorted(kwargs[key], key=lambda x: x["subject"]) + existing_mediatype[key] = sorted(existing_mediatype[key], key=lambda x: x["subject"]) + + if (not (kwargs[key] is None and existing_mediatype[key] == "")) and kwargs[key] != existing_mediatype[key]: params_to_update[key] = kwargs[key] return params_to_update, diff(existing_mediatype, kwargs) @@ -688,89 +656,89 @@ class MediaTypeModule(ZabbixBase): try: self._zapi.mediatype.update(kwargs) except Exception as e: - self._module.fail_json(msg="Failed to update mediatype '{_id}': {e}".format(_id=kwargs['mediatypeid'], e=e)) + self._module.fail_json(msg="Failed to update mediatype '{_id}': {e}".format(_id=kwargs["mediatypeid"], e=e)) def create_mediatype(self, **kwargs): try: self._zapi.mediatype.create(kwargs) except Exception as e: - self._module.fail_json(msg="Failed to create mediatype '{name}': {e}".format(name=kwargs['name'], e=e)) + self._module.fail_json(msg="Failed to create mediatype '{name}': {e}".format(name=kwargs["name"], e=e)) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - name=dict(type='str', required=True), - description=dict(type='str', required=False, default=''), - state=dict(type='str', default='present', choices=['present', 'absent']), - type=dict(type='str', choices=['email', 'script', 'sms', 'webhook', 'jabber', 'ez_texting'], required=True), - status=dict(type='str', default='enabled', choices=['enabled', 'disabled'], required=False), - max_sessions=dict(type='int', default=1, required=False), - max_attempts=dict(type='int', default=3, required=False), - attempt_interval=dict(type='str', default='10s', required=False), + name=dict(type="str", required=True), + description=dict(type="str", required=False, default=""), + state=dict(type="str", default="present", choices=["present", "absent"]), + type=dict(type="str", choices=["email", "script", "sms", "webhook", "jabber", "ez_texting"], required=True), + status=dict(type="str", default="enabled", choices=["enabled", "disabled"], required=False), + max_sessions=dict(type="int", default=1, required=False), + max_attempts=dict(type="int", default=3, required=False), + attempt_interval=dict(type="str", default="10s", required=False), # Script - script_name=dict(type='str', required=False), - script_params=dict(type='list', required=False), + script_name=dict(type="str", required=False), + script_params=dict(type="list", required=False, elements="str"), # SMS - gsm_modem=dict(type='str', required=False), + gsm_modem=dict(type="str", required=False), # Jabber - username=dict(type='str', required=False), - password=dict(type='str', required=False, no_log=True), + username=dict(type="str", required=False), + password=dict(type="str", required=False, no_log=True), # Email - smtp_server=dict(type='str', default='localhost', required=False), - smtp_server_port=dict(type='int', default=25, required=False), - smtp_helo=dict(type='str', default='localhost', required=False), - smtp_email=dict(type='str', required=False), - smtp_security=dict(type='str', required=False, choices=['None', 'STARTTLS', 'SSL/TLS']), - smtp_authentication=dict(type='bool', default=False, required=False), - smtp_verify_host=dict(type='bool', default=False, required=False), - smtp_verify_peer=dict(type='bool', default=False, required=False), + smtp_server=dict(type="str", default="localhost", required=False), + smtp_server_port=dict(type="int", default=25, required=False), + smtp_helo=dict(type="str", default="localhost", required=False), + smtp_email=dict(type="str", required=False), + smtp_security=dict(type="str", required=False, choices=["None", "STARTTLS", "SSL/TLS"]), + smtp_authentication=dict(type="bool", default=False, required=False), + smtp_verify_host=dict(type="bool", default=False, required=False), + smtp_verify_peer=dict(type="bool", default=False, required=False), # EZ Text - message_text_limit=dict(type='str', required=False, choices=['USA', 'Canada']), + message_text_limit=dict(type="str", required=False, choices=["USA", "Canada"]), # Webhook - webhook_script=dict(type='str'), - webhook_timeout=dict(type='str', default='30s'), - process_tags=dict(type='bool', default=False), - event_menu=dict(type='bool', default=False), - event_menu_url=dict(type='str'), - event_menu_name=dict(type='str'), + webhook_script=dict(type="str"), + webhook_timeout=dict(type="str", default="30s"), + process_tags=dict(type="bool", default=False), + event_menu=dict(type="bool", default=False), + event_menu_url=dict(type="str"), + event_menu_name=dict(type="str"), webhook_params=dict( - type='list', - elements='dict', + type="list", + elements="dict", default=[], required=False, options=dict( - name=dict(type='str', required=True), - value=dict(type='str', default='') + name=dict(type="str", required=True), + value=dict(type="str", default="") ) ), message_templates=dict( - type='list', - elements='dict', + type="list", + elements="dict", default=[], required=False, options=dict( - eventsource=dict(type='str', choices=['triggers', 'discovery', 'autoregistration', 'internal']), - recovery=dict(type='str', choices=['operations', 'recovery_operations', 'update_operations']), - subject=dict(type='str', default=''), - body=dict(type='str', default='') + eventsource=dict(type="str", choices=["triggers", "discovery", "autoregistration", "internal"]), + recovery=dict(type="str", choices=["operations", "recovery_operations", "update_operations"]), + subject=dict(type="str", default=""), + body=dict(type="str", default="") ), required_together=[ - ['eventsource', 'recovery'] + ["eventsource", "recovery"] ], ) )) # this is used to simulate `required_if` of `AnsibleModule`, but only when state=present required_params = [ - ['type', 'email', ['smtp_email']], - ['type', 'script', ['script_name']], - ['type', 'sms', ['gsm_modem']], - ['type', 'jabber', ['username', 'password']], - ['type', 'ez_texting', ['username', 'password', 'message_text_limit']], - ['type', 'webhook', ['webhook_script']], - ['event_menu', True, ['event_menu_url', 'event_menu_name']], - ['smtp_authentication', True, ['username', 'password']] + ["type", "email", ["smtp_email"]], + ["type", "script", ["script_name"]], + ["type", "sms", ["gsm_modem"]], + ["type", "jabber", ["username", "password"]], + ["type", "ez_texting", ["username", "password", "message_text_limit"]], + ["type", "webhook", ["webhook_script"]], + ["event_menu", True, ["event_menu_url", "event_menu_name"]], + ["smtp_authentication", True, ["username", "password"]] ] module = AnsibleModule( @@ -778,24 +746,18 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - state = module.params['state'] - name = module.params['name'] + state = module.params["state"] + name = module.params["name"] mediatype = MediaTypeModule(module) - if module.params['state'] == 'present': + if module.params["state"] == "present": mediatype.validate_params(required_params) mediatype_exists, mediatype_id = mediatype.check_if_mediatype_exists(name) parameters = mediatype.construct_parameters() if mediatype_exists: - if state == 'absent': + if state == "absent": if module.check_mode: module.exit_json( changed=True, @@ -860,5 +822,5 @@ def main(): ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy.py index 3fdfe42c1..a5ddbe137 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy.py @@ -22,7 +22,7 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_proxy short_description: Create/delete/get/update Zabbix proxies @@ -31,7 +31,7 @@ description: author: - "Alen Komic (@akomic)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: proxy_name: description: @@ -42,7 +42,6 @@ options: description: - Comma-delimited list of IP/CIDR addresses or DNS names to accept active proxy requests from. - Requires I(status=active). - - Works only with >= Zabbix 4.0. ( remove option for <= 4.0 ) required: false type: str description: @@ -54,22 +53,22 @@ options: description: - Type of proxy. (4 - active, 5 - passive) required: false - choices: ['active', 'passive'] + choices: ["active", "passive"] default: "active" type: str tls_connect: description: - Connections to proxy. required: false - choices: ['no_encryption','PSK','certificate'] - default: 'no_encryption' + choices: ["no_encryption","PSK","certificate"] + default: "no_encryption" type: str tls_accept: description: - Connections from proxy. required: false - choices: ['no_encryption','PSK','certificate'] - default: 'no_encryption' + choices: ["no_encryption","PSK","certificate"] + default: "no_encryption" type: str ca_cert: description: @@ -98,14 +97,14 @@ options: - On C(present), it will create if proxy does not exist or update the proxy if the associated data is different. - On C(absent) will remove a proxy if it exists. required: false - choices: ['present', 'absent'] + choices: ["present", "absent"] default: "present" type: str interface: description: - Dictionary with params for the interface when proxy is in passive mode. - For more information, review proxy interface documentation at - - U(https://www.zabbix.com/documentation/4.0/manual/api/reference/proxy/object#proxy_interface). + - U(https://www.zabbix.com/documentation/current/en/manual/api/reference/proxy/object#proxy-interface). required: false suboptions: useip: @@ -120,53 +119,37 @@ options: description: - IP address used by proxy interface. - Required if I(useip=1). - default: '' + default: "" dns: type: str description: - DNS name of the proxy interface. - Required if I(useip=0). - default: '' + default: "" port: type: str description: - Port used by proxy interface. - default: '10051' - type: - type: int - description: - - Interface type to add. - - This suboption is currently ignored for Zabbix proxy. - - This suboption is deprecated since Ansible 2.10 and will eventually be removed in 2.14. - required: false - default: 0 - main: - type: int - description: - - Whether the interface is used as default. - - This suboption is currently ignored for Zabbix proxy. - - This suboption is deprecated since Ansible 2.10 and will eventually be removed in 2.14. - required: false - default: 0 + default: "10051" default: {} type: dict extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create or update a proxy with proxy type active @@ -177,7 +160,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_proxy: proxy_name: ExampleProxy @@ -194,7 +177,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_proxy: proxy_name: ExampleProxy @@ -214,7 +197,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_proxy: proxy_name: ExampleProxy @@ -224,15 +207,14 @@ EXAMPLES = r''' interface: dns: proxy.example.com port: 10051 -''' +""" -RETURN = r''' # ''' +RETURN = r""" # """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils @@ -243,13 +225,13 @@ class Proxy(ZabbixBase): self.existing_data = None def proxy_exists(self, proxy_name): - result = self._zapi.proxy.get({'output': 'extend', - 'selectInterface': 'extend', - 'filter': {'host': proxy_name}}) + result = self._zapi.proxy.get({"output": "extend", + "selectInterface": "extend", + "filter": {"host": proxy_name}}) - if len(result) > 0 and 'proxyid' in result[0]: + if len(result) > 0 and "proxyid" in result[0]: self.existing_data = result[0] - return result[0]['proxyid'] + return result[0]["proxyid"] else: return result @@ -263,23 +245,19 @@ class Proxy(ZabbixBase): if data[item]: parameters[item] = data[item] - if 'proxy_address' in data and data['status'] != '5': - parameters.pop('proxy_address', False) + if "proxy_address" in data and data["status"] != "5": + parameters.pop("proxy_address", False) - if 'interface' in data and data['status'] != '6': - parameters.pop('interface', False) - else: - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - parameters['interface'].pop('type') - parameters['interface'].pop('main') + if "interface" in data and data["status"] != "6": + parameters.pop("interface", False) proxy_ids_list = self._zapi.proxy.create(parameters) self._module.exit_json(changed=True, - result="Successfully added proxy %s (%s)" % (data['host'], data['status'])) + result="Successfully added proxy %s (%s)" % (data["host"], data["status"])) if len(proxy_ids_list) >= 1: - return proxy_ids_list['proxyids'][0] + return proxy_ids_list["proxyids"][0] except Exception as e: - self._module.fail_json(msg="Failed to create proxy %s: %s" % (data['host'], e)) + self._module.fail_json(msg="Failed to create proxy %s: %s" % (data["host"], e)) def delete_proxy(self, proxy_id, proxy_name): try: @@ -299,33 +277,22 @@ class Proxy(ZabbixBase): for key in data: if data[key]: parameters[key] = data[key] - if 'interface' in parameters: - if parameters['status'] == '5': + if "interface" in parameters: + if parameters["status"] == "5": # Active proxy - parameters.pop('interface', False) + parameters.pop("interface", False) else: # Passive proxy - parameters['interface']['useip'] = str(parameters['interface']['useip']) - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0.0'): - parameters['interface'].pop('type', False) - parameters['interface'].pop('main', False) - else: - parameters['interface']['type'] = '0' - parameters['interface']['main'] = '1' - if ('interface' in self.existing_data - and isinstance(self.existing_data['interface'], dict)): - new_interface = self.existing_data['interface'].copy() - new_interface.update(parameters['interface']) - parameters['interface'] = new_interface - - if parameters['status'] == '5': + parameters["interface"]["useip"] = str(parameters["interface"]["useip"]) + + if parameters["status"] == "5": # Active proxy - parameters.pop('tls_connect', False) + parameters.pop("tls_connect", False) else: # Passive proxy - parameters.pop('tls_accept', False) + parameters.pop("tls_accept", False) - parameters['proxyid'] = proxy_id + parameters["proxyid"] = proxy_id change_parameters = {} difference = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(parameters, self.existing_data, change_parameters)) @@ -333,43 +300,41 @@ class Proxy(ZabbixBase): if difference == {}: self._module.exit_json(changed=False) else: - difference['proxyid'] = proxy_id + difference["proxyid"] = proxy_id self._zapi.proxy.update(parameters) self._module.exit_json( changed=True, result="Successfully updated proxy %s (%s)" % - (data['host'], proxy_id) + (data["host"], proxy_id) ) except Exception as e: self._module.fail_json(msg="Failed to update proxy %s: %s" % - (data['host'], e)) + (data["host"], e)) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - proxy_name=dict(type='str', required=True), - proxy_address=dict(type='str', required=False), - status=dict(type='str', default="active", choices=['active', 'passive']), - state=dict(type='str', default="present", choices=['present', 'absent']), - description=dict(type='str', required=False), - tls_connect=dict(type='str', default='no_encryption', choices=['no_encryption', 'PSK', 'certificate']), - tls_accept=dict(type='str', default='no_encryption', choices=['no_encryption', 'PSK', 'certificate']), - ca_cert=dict(type='str', required=False, default=None, aliases=['tls_issuer']), - tls_subject=dict(type='str', required=False, default=None), - tls_psk_identity=dict(type='str', required=False, default=None), - tls_psk=dict(type='str', required=False, default=None, no_log=True), + proxy_name=dict(type="str", required=True), + proxy_address=dict(type="str", required=False), + status=dict(type="str", default="active", choices=["active", "passive"]), + state=dict(type="str", default="present", choices=["present", "absent"]), + description=dict(type="str", required=False), + tls_connect=dict(type="str", default="no_encryption", choices=["no_encryption", "PSK", "certificate"]), + tls_accept=dict(type="str", default="no_encryption", choices=["no_encryption", "PSK", "certificate"]), + ca_cert=dict(type="str", required=False, default=None, aliases=["tls_issuer"]), + tls_subject=dict(type="str", required=False, default=None), + tls_psk_identity=dict(type="str", required=False, default=None), + tls_psk=dict(type="str", required=False, default=None, no_log=True), interface=dict( - type='dict', + type="dict", required=False, default={}, options=dict( - useip=dict(type='int', choices=[0, 1], default=0), - ip=dict(type='str', default=''), - dns=dict(type='str', default=''), - port=dict(type='str', default='10051'), - type=dict(type='int', default=0, removed_in_version="3.0.0", removed_from_collection='community.zabbix'), # was Ansible 2.14 - main=dict(type='int', default=0, removed_in_version="3.0.0", removed_from_collection='community.zabbix'), # was Ansible 2.14 + useip=dict(type="int", choices=[0, 1], default=0), + ip=dict(type="str", default=""), + dns=dict(type="str", default=""), + port=dict(type="str", default="10051") ), ) )) @@ -378,38 +343,32 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - proxy_name = module.params['proxy_name'] - proxy_address = module.params['proxy_address'] - description = module.params['description'] - status = module.params['status'] - tls_connect = module.params['tls_connect'] - tls_accept = module.params['tls_accept'] - tls_issuer = module.params['ca_cert'] - tls_subject = module.params['tls_subject'] - tls_psk_identity = module.params['tls_psk_identity'] - tls_psk = module.params['tls_psk'] - state = module.params['state'] - interface = module.params['interface'] + proxy_name = module.params["proxy_name"] + proxy_address = module.params["proxy_address"] + description = module.params["description"] + status = module.params["status"] + tls_connect = module.params["tls_connect"] + tls_accept = module.params["tls_accept"] + tls_issuer = module.params["ca_cert"] + tls_subject = module.params["tls_subject"] + tls_psk_identity = module.params["tls_psk_identity"] + tls_psk = module.params["tls_psk"] + state = module.params["state"] + interface = module.params["interface"] # convert enabled to 0; disabled to 1 status = 6 if status == "passive" else 5 - if tls_connect == 'certificate': + if tls_connect == "certificate": tls_connect = 4 - elif tls_connect == 'PSK': + elif tls_connect == "PSK": tls_connect = 2 else: tls_connect = 1 - if tls_accept == 'certificate': + if tls_accept == "certificate": tls_accept = 4 - elif tls_accept == 'PSK': + elif tls_accept == "PSK": tls_accept = 2 else: tls_accept = 1 @@ -425,17 +384,17 @@ def main(): proxy.delete_proxy(proxy_id, proxy_name) else: proxy.update_proxy(proxy_id, { - 'host': proxy_name, - 'description': description, - 'status': str(status), - 'tls_connect': str(tls_connect), - 'tls_accept': str(tls_accept), - 'tls_issuer': tls_issuer, - 'tls_subject': tls_subject, - 'tls_psk_identity': tls_psk_identity, - 'tls_psk': tls_psk, - 'interface': interface, - 'proxy_address': proxy_address + "host": proxy_name, + "description": description, + "status": str(status), + "tls_connect": str(tls_connect), + "tls_accept": str(tls_accept), + "tls_issuer": tls_issuer, + "tls_subject": tls_subject, + "tls_psk_identity": tls_psk_identity, + "tls_psk": tls_psk, + "interface": interface, + "proxy_address": proxy_address }) else: if state == "absent": @@ -443,19 +402,19 @@ def main(): module.exit_json(changed=False) proxy_id = proxy.add_proxy(data={ - 'host': proxy_name, - 'description': description, - 'status': str(status), - 'tls_connect': str(tls_connect), - 'tls_accept': str(tls_accept), - 'tls_issuer': tls_issuer, - 'tls_subject': tls_subject, - 'tls_psk_identity': tls_psk_identity, - 'tls_psk': tls_psk, - 'interface': interface, - 'proxy_address': proxy_address + "host": proxy_name, + "description": description, + "status": str(status), + "tls_connect": str(tls_connect), + "tls_accept": str(tls_accept), + "tls_issuer": tls_issuer, + "tls_subject": tls_subject, + "tls_psk_identity": tls_psk_identity, + "tls_psk": tls_psk, + "interface": interface, + "proxy_address": proxy_address }) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy_info.py index b40022883..c82112609 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy_info.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_proxy_info.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ module: zabbix_proxy_info short_description: Gather information about Zabbix proxy version_added: 1.5.0 @@ -17,7 +17,7 @@ author: description: - This module allows you to obtain detailed information about configured zabbix proxies. requirements: - - "python >= 2.6" + - "python >= 3.9" options: proxy_name: description: @@ -33,19 +33,19 @@ options: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Get zabbix proxy info alongside the list of hosts monitored by the proxy @@ -56,17 +56,14 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_proxy_info: - server_url: "http://zabbix.example.com/zabbix/" - login_user: admin - login_password: secret proxy_name: zbx01.example.com proxy_hosts: true -''' +""" -RETURN = ''' +RETURN = """ zabbix_proxy: description: example returned: always @@ -120,7 +117,7 @@ zabbix_proxy: "tls_subject": "", "uuid": "" } -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -134,15 +131,15 @@ class Proxy(ZabbixBase): def get_proxy(self, name, hosts=False): result = {} params = { - 'filter': { - 'host': name + "filter": { + "host": name }, - 'output': 'extend', - 'selectInterface': 'extend', + "output": "extend", + "selectInterface": "extend", } if hosts: - params['selectHosts'] = ['host', 'hostid'] + params["selectHosts"] = ["host", "hostid"] try: result = self._zapi.proxy.get(params) @@ -155,8 +152,8 @@ class Proxy(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - proxy_name=dict(type='str', required=True), - proxy_hosts=dict(type='bool', required=False, default=False), + proxy_name=dict(type="str", required=True), + proxy_hosts=dict(type="bool", required=False, default=False), )) module = AnsibleModule( @@ -164,14 +161,8 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - name = module.params['proxy_name'] - hosts = module.params['proxy_hosts'] + name = module.params["proxy_name"] + hosts = module.params["proxy_hosts"] proxy = Proxy(module) result = proxy.get_proxy(name, hosts) diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_regexp.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_regexp.py new file mode 100644 index 000000000..fc3ccedee --- /dev/null +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_regexp.py @@ -0,0 +1,345 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2022, ONODERA Masaru <masaru-onodera@ieee.org> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +DOCUMENTATION = """ +--- +module: zabbix_regexp + +short_description: Create/update/delete Zabbix regular expression + + +description: + - This module allows you to create, update and delete Zabbix regular expression. + +author: + - ONODERA Masaru(@masa-orca) + +requirements: + - "python >= 3.9" + +version_added: 2.1.0 + +options: + name: + description: + - Name of this regular expression + type: str + required: true + test_string: + description: + - A test string for this regular expression + type: str + expressions: + description: + - List of expressions. + - The regular expression returns true when all expressions return true. + - Required when C(state=present). + type: list + elements: dict + suboptions: + expression: + description: + - A expression string + type: str + required: true + expression_type: + description: + - A expression string + type: str + required: true + choices: + - "character_string_included" + - "any_character_string_included" + - "character_string_not_included" + - "result_is_true" + - "result_is_false" + exp_delimiter: + description: + - Delimiter for expression. + - Used if expression_type is C(any_character_string_included). + - Default values is C(,) + type: str + choices: [",", ".", "/"] + case_sensitive: + description: + - If true, the expression will be case sensitive. + type: bool + default: false + state: + description: + - State of the regular expression. + type: str + choices: ['present', 'absent'] + default: 'present' + + +notes: + - Only Zabbix >= 6.0 is supported. + +extends_documentation_fragment: + - community.zabbix.zabbix + +""" + +EXAMPLES = """ +# If you want to use Username and Password to be authenticated by Zabbix Server +- name: Set credentials to access Zabbix Server API + ansible.builtin.set_fact: + ansible_user: Admin + ansible_httpapi_pass: zabbix + +# If you want to use API token to be authenticated by Zabbix Server +# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens +- name: Set API token + ansible.builtin.set_fact: + ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 + +- name: Update regexp of 'File systems for discovery' + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_regexp: + name: File systems for discovery + test_string: ext2 + expressions: + - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$" + expression_type: result_is_true +""" + +RETURN = """ +msg: + description: The result of the operation + returned: success + type: str + sample: 'Successfully updated regular expression setting' +""" + + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase +from ansible.module_utils.compat.version import LooseVersion + +import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils + + +class RegularExpression(ZabbixBase): + def __init__(self, module, zbx=None, zapi_wrapper=None): + super(RegularExpression, self).__init__(module, zbx, zapi_wrapper) + if LooseVersion(self._zbx_api_version) < LooseVersion("6.0"): + module.fail_json( + msg="This module doesn't support Zabbix versions lower than 6.0" + ) + + def get_regexps(self, regexp_name): + try: + regexps = self._zapi.regexp.get( + { + "output": "extend", + "selectExpressions": [ + "expression", + "expression_type", + "exp_delimiter", + "case_sensitive", + ], + "filter": {"name": regexp_name}, + } + ) + if len(regexps) >= 2: + self._module.fail_json("Too many regexps are matched.") + return regexps + except Exception as e: + self._module.fail_json( + msg="Failed to get regular expression setting: %s" % e + ) + + def delete_regexp(self, regexp): + try: + parameter = [regexp["regexpid"]] + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.regexp.delete(parameter) + self._module.exit_json( + changed=True, msg="Successfully deleted regular expression setting." + ) + except Exception as e: + self._module.fail_json( + msg="Failed to delete regular expression setting: %s" % e + ) + + def _convert_expressions_to_json(self, expressions): + expression_type_values = [ + "character_string_included", + "any_character_string_included", + "character_string_not_included", + "result_is_true", + "result_is_false", + ] + + expression_jsons = [] + for expression in expressions: + expression_json = {} + + expression_json["expression"] = expression["expression"] + expression_type = zabbix_utils.helper_to_numeric_value( + expression_type_values, expression["expression_type"] + ) + expression_json["expression_type"] = str(expression_type) + if expression["expression_type"] == "any_character_string_included": + if expression["exp_delimiter"]: + expression_json["exp_delimiter"] = expression["exp_delimiter"] + else: + expression_json["exp_delimiter"] = "," + elif expression["exp_delimiter"]: + self._module.warn( + "A value of exp_delimiter will be ignored because expression_type is not 'any_character_string_included'." + ) + case_sensitive = "0" + if expression["case_sensitive"]: + case_sensitive = "1" + expression_json["case_sensitive"] = case_sensitive + + expression_jsons.append(expression_json) + return expression_jsons + + def create_regexp(self, name, test_string, expressions): + try: + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.regexp.create( + { + "name": name, + "test_string": test_string, + "expressions": self._convert_expressions_to_json(expressions), + } + ) + self._module.exit_json( + changed=True, msg="Successfully created regular expression setting." + ) + except Exception as e: + self._module.fail_json( + msg="Failed to create regular expression setting: %s" % e + ) + + def update_regexp(self, current_regexp, name, test_string, expressions): + try: + current_expressions = [] + for expression in current_regexp["expressions"]: + if expression["expression_type"] != "1": + expression = zabbix_utils.helper_normalize_data( + expression, del_keys=["exp_delimiter"] + )[0] + current_expressions.append(expression) + future_expressions = self._convert_expressions_to_json(expressions) + diff_expressions = [] + zabbix_utils.helper_compare_lists( + current_expressions, future_expressions, diff_expressions + ) + if ( + current_regexp["name"] == name + and current_regexp["test_string"] == test_string + and len(diff_expressions) == 0 + ): + self._module.exit_json(changed=False) + else: + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.regexp.update( + { + "regexpid": current_regexp["regexpid"], + "name": name, + "test_string": test_string, + "expressions": future_expressions, + } + ) + self._module.exit_json( + changed=True, msg="Successfully updated regular expression setting." + ) + except Exception as e: + self._module.fail_json( + msg="Failed to update regular expression setting: %s" % e + ) + + +def main(): + """Main ansible module function""" + + argument_spec = zabbix_utils.zabbix_common_argument_spec() + argument_spec.update( + dict( + name=dict(type="str", required=True), + test_string=dict( + type="str", + ), + expressions=dict( + type="list", + elements="dict", + options=dict( + expression=dict(type="str", required=True), + expression_type=dict( + type="str", + required=True, + choices=[ + "character_string_included", + "any_character_string_included", + "character_string_not_included", + "result_is_true", + "result_is_false", + ], + ), + exp_delimiter=dict(type="str", choices=[",", ".", "/"]), + case_sensitive=dict(type="bool", default=False), + ), + ), + state=dict( + type="str", + required=False, + default="present", + choices=["present", "absent"], + ), + ) + ) + + module = AnsibleModule( + argument_spec=argument_spec, + required_if=[["state", "present", ["expressions"]]], + supports_check_mode=True, + ) + + name = module.params["name"] + test_string = module.params["test_string"] + expressions = module.params["expressions"] + state = module.params["state"] + + regexp_class_obj = RegularExpression(module) + regexps = regexp_class_obj.get_regexps(name) + + if state == "absent": + if len(regexps) == 1: + regexp_class_obj.delete_regexp(regexps[0]) + else: + module.exit_json(changed=False) + else: + if len(regexps) == 1: + regexp_class_obj.update_regexp(regexps[0], name, test_string, expressions) + else: + regexp_class_obj.create_regexp(name, test_string, expressions) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_screen.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_screen.py deleted file mode 100644 index 5e350fc80..000000000 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_screen.py +++ /dev/null @@ -1,496 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2013-2014, Epic Games, Inc. -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -from __future__ import absolute_import, division, print_function -__metaclass__ = type - - -DOCUMENTATION = r''' ---- -module: zabbix_screen -short_description: Create/update/delete Zabbix screens -description: - - This module allows you to create, modify and delete Zabbix screens and associated graph data. -author: - - "Cove (@cove)" - - "Tony Minfei Ding (!UNKNOWN)" - - "Harrison Gu (@harrisongu)" -requirements: - - "python >= 2.6" - - "Zabbix <= 5.2" -options: - screens: - description: - - List of screens to be created/updated/deleted (see example). - type: list - elements: dict - required: true - suboptions: - screen_name: - description: - - Screen name will be used. - - If a screen has already been added, the screen name won't be updated. - type: str - required: true - host_group: - description: - - Host group(s) will be used for searching hosts. - - Required if I(state=present). - type: list - elements: str - aliases: [ 'host_groups' ] - state: - description: - - I(present) - Create a screen if it doesn't exist. If the screen already exists, the screen will be updated as needed. - - I(absent) - If a screen exists, the screen will be deleted. - type: str - default: present - choices: - - absent - - present - graph_names: - description: - - Graph names will be added to a screen. Case insensitive. - - Required if I(state=present). - type: list - elements: str - graph_width: - description: - - Graph width will be set in graph settings. - type: int - graph_height: - description: - - Graph height will be set in graph settings. - type: int - graphs_in_row: - description: - - Limit columns of a screen and make multiple rows. - type: int - default: 3 - sort: - description: - - Sort hosts alphabetically. - - If there are numbers in hostnames, leading zero should be used. - type: bool - default: no - -extends_documentation_fragment: -- community.zabbix.zabbix - - -notes: - - Too many concurrent updates to the same screen may cause Zabbix to return errors, see examples for a workaround if needed. - - Screens where removed from Zabbix with Version 5.4 -''' - -EXAMPLES = r''' -# If you want to use Username and Password to be authenticated by Zabbix Server -- name: Set credentials to access Zabbix Server API - set_fact: - ansible_user: Admin - ansible_httpapi_pass: zabbix - -# If you want to use API token to be authenticated by Zabbix Server -# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens -- name: Set API token - set_fact: - ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - -# Screens where removed from Zabbix with Version 5.4 - -# Create/update a screen. -- name: Create a new screen or update an existing screen's items 5 in a row - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_screen: - screens: - - screen_name: ExampleScreen1 - host_group: Example group1 - state: present - graph_names: - - Example graph1 - - Example graph2 - graph_width: 200 - graph_height: 100 - graphs_in_row: 5 - -# Create/update multi-screen -- name: Create two of new screens or update the existing screens' items - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_screen: - screens: - - screen_name: ExampleScreen1 - host_group: Example group1 - state: present - graph_names: - - Example graph1 - - Example graph2 - graph_width: 200 - graph_height: 100 - - screen_name: ExampleScreen2 - host_group: Example group2 - state: present - graph_names: - - Example graph1 - - Example graph2 - graph_width: 200 - graph_height: 100 - -# Limit the Zabbix screen creations to one host since Zabbix can return an error when doing concurrent updates -- name: Create a new screen or update an existing screen's items - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_screen: - state: present - screens: - - screen_name: ExampleScreen - host_group: Example group - state: present - graph_names: - - Example graph1 - - Example graph2 - graph_width: 200 - graph_height: 100 - when: inventory_hostname==groups['group_name'][0] - -# Create/update using multiple hosts_groups. Hosts NOT present in all listed host_groups will be skipped. -- name: Create new screen or update the existing screen's items for hosts in both given groups - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_screen: - screens: - - screen_name: ExampleScreen1 - host_group: - - Example group1 - - Example group2 - state: present - graph_names: - - Example graph1 - - Example graph2 - graph_width: 200 - graph_height: 100 -''' - - -from ansible.module_utils.basic import AnsibleModule - -from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible_collections.community.zabbix.plugins.module_utils.wrappers import ScreenItem -from ansible.module_utils.compat.version import LooseVersion - -import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils - - -class Screen(ZabbixBase): - # get list of group ids by list of group names - def get_host_group_ids(self, group_names): - if not group_names: - self._module.fail_json(msg="group_name is required") - hostGroup_list = self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': group_names}}) - if not hostGroup_list: - self._module.fail_json(msg="Host group not found: {0}".format(group_names)) - else: - hostGroup_ids = [g['groupid'] for g in hostGroup_list] - return hostGroup_ids - - # get monitored host_ids by host_group_ids - # (the hosts belonging to all given groups) - def get_host_ids_by_group_ids(self, group_ids, sort): - host_list = self._zapi.host.get({'output': 'extend', 'selectGroups': 'groupid', 'groupids': group_ids, 'monitored_hosts': 1}) - if not host_list: - self._module.fail_json(msg="No hosts in the all group(s) with ids {0}".format(group_ids)) - else: - if sort: - host_list = sorted(host_list, key=lambda name: name['name']) - host_ids = [] - for host in host_list: - host_group_ids = [g['groupid'] for g in host['groups']] - # Check if all search group ids are in hosts group ids - if set(group_ids).issubset(host_group_ids): - host_id = host['hostid'] - host_ids.append(host_id) - return host_ids - - # get screen - def get_screen_id(self, screen_name): - if screen_name == "": - self._module.fail_json(msg="screen_name is required") - try: - screen_id_list = self._zapi.screen.get({'output': 'extend', 'search': {"name": screen_name}}) - if len(screen_id_list) >= 1: - screen_id = screen_id_list[0]['screenid'] - return screen_id - return None - except Exception as e: - self._module.fail_json(msg="Failed to get screen %s from Zabbix: %s" % (screen_name, e)) - - # create screen - def create_screen(self, screen_name, h_size, v_size): - try: - if self._module.check_mode: - self._module.exit_json(changed=True) - screen = self._zapi.screen.create({'name': screen_name, 'hsize': h_size, 'vsize': v_size}) - return screen['screenids'][0] - except Exception as e: - self._module.fail_json(msg="Failed to create screen %s: %s" % (screen_name, e)) - - # update screen - def update_screen(self, screen_id, screen_name, h_size, v_size): - try: - if self._module.check_mode: - self._module.exit_json(changed=True) - self._zapi.screen.update({'screenid': screen_id, 'hsize': h_size, 'vsize': v_size}) - except Exception as e: - self._module.fail_json(msg="Failed to update screen %s: %s" % (screen_name, e)) - - # delete screen - def delete_screen(self, screen_id, screen_name): - try: - if self._module.check_mode: - self._module.exit_json(changed=True) - self._zapi.screen.delete([screen_id]) - except Exception as e: - self._module.fail_json(msg="Failed to delete screen %s: %s" % (screen_name, e)) - - # get graph ids - def get_graph_ids(self, hosts, graph_name_list): - graph_id_lists = [] - vsize = 1 - for host in hosts: - graph_id_list = self.get_graphs_by_host_id(graph_name_list, host) - size = len(graph_id_list) - if size > 0: - graph_id_lists.extend(graph_id_list) - if vsize < size: - vsize = size - return graph_id_lists, vsize - - # getGraphs - def get_graphs_by_host_id(self, graph_name_list, host_id): - graph_ids = [] - for graph_name in graph_name_list: - graphs_list = self._zapi.graph.get({'output': 'extend', 'search': {'name': graph_name}, 'hostids': host_id}) - graph_id_list = [] - if len(graphs_list) > 0: - for graph in graphs_list: - graph_id = graph['graphid'] - graph_id_list.append(graph_id) - if len(graph_id_list) > 0: - graph_ids.extend(graph_id_list) - return graph_ids - - # get screen items - def get_screen_items(self, screen_id): - screen_item_list = self._zapi.screenitem.get({'output': 'extend', 'screenids': screen_id}) - return screen_item_list - - # delete screen items - def delete_screen_items(self, screen_id, screen_item_id_list): - if len(screen_item_id_list) == 0: - return True - screen_item_list = self.get_screen_items(screen_id) - if len(screen_item_list) > 0: - if self._module.check_mode: - self._module.exit_json(changed=True) - ScreenItem.delete(self, screen_item_id_list) - return True - return False - - # get screen's hsize and vsize - def get_hsize_vsize(self, hosts, v_size, graphs_in_row): - h_size = len(hosts) - # when there is only one host, put all graphs in a row - if h_size == 1: - if v_size <= graphs_in_row: - h_size = v_size - else: - h_size = graphs_in_row - v_size = (v_size - 1) // h_size + 1 - # when len(hosts) is more then graphs_in_row - elif len(hosts) > graphs_in_row: - h_size = graphs_in_row - v_size = (len(hosts) // graphs_in_row + 1) * v_size - - return h_size, v_size - - # create screen_items - def create_screen_items(self, screen_id, hosts, graph_name_list, width, height, h_size, graphs_in_row): - if len(hosts) < 4: - if width is None or width < 0: - width = 500 - else: - if width is None or width < 0: - width = 200 - if height is None or height < 0: - height = 100 - - # when there're only one host, only one row is not good. - if len(hosts) == 1: - graph_id_list = self.get_graphs_by_host_id(graph_name_list, hosts[0]) - for i, graph_id in enumerate(graph_id_list): - if graph_id is not None: - ScreenItem.create(self, ignoreExists=True, data={'screenid': screen_id, 'resourcetype': 0, 'resourceid': graph_id, - 'width': width, 'height': height, - 'x': i % h_size, 'y': i // h_size, 'colspan': 1, 'rowspan': 1, - 'elements': 0, 'valign': 0, 'halign': 0, - 'style': 0, 'dynamic': 0, 'sort_triggers': 0}) - else: - for i, host in enumerate(hosts): - graph_id_list = self.get_graphs_by_host_id(graph_name_list, host) - for j, graph_id in enumerate(graph_id_list): - if graph_id is not None: - ScreenItem.create(self, ignoreExists=True, data={'screenid': screen_id, 'resourcetype': 0, 'resourceid': graph_id, - 'width': width, 'height': height, - 'x': i % graphs_in_row, 'y': len(graph_id_list) * (i // graphs_in_row) + j, - 'colspan': 1, 'rowspan': 1, - 'elements': 0, 'valign': 0, 'halign': 0, - 'style': 0, 'dynamic': 0, 'sort_triggers': 0}) - - -def main(): - argument_spec = zabbix_utils.zabbix_common_argument_spec() - argument_spec.update(dict( - screens=dict( - type='list', - elements='dict', - required=True, - options=dict( - screen_name=dict(type='str', required=True), - host_group=dict(type='list', aliases=['host_groups'], elements='str'), - state=dict(type='str', default='present', choices=['absent', 'present']), - graph_names=dict(type='list', elements='str'), - graph_width=dict(type='int', default=None), - graph_height=dict(type='int', default=None), - graphs_in_row=dict(type='int', default=3), - sort=dict(default=False, type='bool'), - ), - required_if=[ - ['state', 'present', ['host_group']] - ] - ) - )) - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True - ) - - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - screens = module.params['screens'] - - screen = Screen(module) - if LooseVersion(screen._zbx_api_version) >= LooseVersion('5.4'): - module.fail_json(msg="Zabbix 5.4 removed the Screens feature see (%s)." % ( - "https://www.zabbix.com/documentation/current/en/manual/api/changes_5.2_-_5.4" - )) - - created_screens = [] - changed_screens = [] - deleted_screens = [] - - for zabbix_screen in screens: - screen_name = zabbix_screen['screen_name'] - screen_id = screen.get_screen_id(screen_name) - state = zabbix_screen['state'] - sort = zabbix_screen['sort'] - - if state == "absent": - if screen_id: - screen_item_list = screen.get_screen_items(screen_id) - screen_item_id_list = [] - for screen_item in screen_item_list: - screen_item_id = screen_item['screenitemid'] - screen_item_id_list.append(screen_item_id) - screen.delete_screen_items(screen_id, screen_item_id_list) - screen.delete_screen(screen_id, screen_name) - - deleted_screens.append(screen_name) - else: - host_group = zabbix_screen['host_group'] - graph_names = zabbix_screen['graph_names'] - graphs_in_row = zabbix_screen['graphs_in_row'] - graph_width = zabbix_screen['graph_width'] - graph_height = zabbix_screen['graph_height'] - host_group_ids = screen.get_host_group_ids(host_group) - hosts = screen.get_host_ids_by_group_ids(host_group_ids, sort) - if not hosts: - module.fail_json(msg="No hosts found belongin to all given groups: %s" % host_group) - screen_item_id_list = [] - resource_id_list = [] - - graph_ids, v_size = screen.get_graph_ids(hosts, graph_names) - h_size, v_size = screen.get_hsize_vsize(hosts, v_size, graphs_in_row) - - if not screen_id: - # create screen - screen_id = screen.create_screen(screen_name, h_size, v_size) - screen.create_screen_items(screen_id, hosts, graph_names, graph_width, graph_height, h_size, graphs_in_row) - created_screens.append(screen_name) - else: - screen_item_list = screen.get_screen_items(screen_id) - - for screen_item in screen_item_list: - screen_item_id = screen_item['screenitemid'] - resource_id = screen_item['resourceid'] - screen_item_id_list.append(screen_item_id) - resource_id_list.append(resource_id) - - # when the screen items changed, then update - if graph_ids != resource_id_list: - deleted = screen.delete_screen_items(screen_id, screen_item_id_list) - if deleted: - screen.update_screen(screen_id, screen_name, h_size, v_size) - screen.create_screen_items(screen_id, hosts, graph_names, graph_width, graph_height, h_size, graphs_in_row) - changed_screens.append(screen_name) - - if created_screens and changed_screens: - module.exit_json(changed=True, result="Successfully created screen(s): %s, and updated screen(s): %s" % (",".join(created_screens), - ",".join(changed_screens))) - elif created_screens: - module.exit_json(changed=True, result="Successfully created screen(s): %s" % ",".join(created_screens)) - elif changed_screens: - module.exit_json(changed=True, result="Successfully updated screen(s): %s" % ",".join(changed_screens)) - elif deleted_screens: - module.exit_json(changed=True, result="Successfully deleted screen(s): %s" % ",".join(deleted_screens)) - else: - module.exit_json(changed=False) - - -if __name__ == '__main__': - main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_script.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_script.py index 15277b0fa..643851885 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_script.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_script.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ module: zabbix_script short_description: Create/update/delete Zabbix scripts version_added: 1.7.0 @@ -17,7 +17,7 @@ author: description: - This module allows you to create, update and delete scripts. requirements: - - "python >= 2.6" + - "python >= 3.9" options: name: description: @@ -27,10 +27,9 @@ options: script_type: description: - Script type. - - Types C(ssh), C(telnet) and C(webhook) works only with Zabbix >= 5.4. type: str required: true - choices: ['script', 'ipmi', 'ssh', 'telnet', 'webhook'] + choices: ["script", "ipmi", "ssh", "telnet", "webhook"] command: description: - Command to run. @@ -39,24 +38,22 @@ options: scope: description: - Script scope. - - Works only with Zabbix >= 5.4. For lower versions is silently ignored which is equivalent of C(manual_host_action). type: str required: false - choices: ['action_operation', 'manual_host_action', 'manual_event_action'] - default: 'action_operation' + choices: ["action_operation", "manual_host_action", "manual_event_action"] + default: "action_operation" execute_on: description: - Where to run the script. - Used if type is C(script). type: str required: false - choices: ['zabbix_agent', 'zabbix_server', 'zabbix_server_proxy'] - default: 'zabbix_server_proxy' + choices: ["zabbix_agent", "zabbix_server", "zabbix_server_proxy"] + default: "zabbix_server_proxy" menu_path: description: - Folders separated by slash that form a menu like navigation in frontend when clicked on host or event. - Used if scope is C(manual_host_action) or C(manual_event_action). - - Works only with Zabbix >= 5.4. For lower versions is silently ignored. Prepend menu path to name instead. type: str required: false authtype: @@ -65,7 +62,7 @@ options: - Used if type is C(ssh). type: str required: false - choices: ['password', 'public_key'] + choices: ["password", "public_key"] username: description: - User name used for authentication. @@ -98,25 +95,25 @@ options: required: false host_group: description: - - host group name that the script can be run on. If set to 'all', the script will be available on all host groups. + - host group name that the script can be run on. If set to "all", the script will be available on all host groups. type: str required: false - default: 'all' + default: "all" user_group: description: - - user group name that will be allowed to run the script. If set to 'all', the script will be available for all user groups. + - user group name that will be allowed to run the script. If set to "all", the script will be available for all user groups. - Used if scope is C(manual_host_action) or C(manual_event_action). type: str required: false - default: 'all' + default: "all" host_access: description: - Host permissions needed to run the script. - Used if scope is C(manual_host_action) or C(manual_event_action). type: str required: false - choices: ['read', 'write'] - default: 'read' + choices: ["read", "write"] + default: "read" confirmation: description: - Confirmation pop up text. The pop up will appear when trying to run the script from the Zabbix frontend. @@ -127,9 +124,9 @@ options: description: - Webhook script execution timeout in seconds. Time suffixes are supported, e.g. 30s, 1m. - Required if type is C(webhook). - - 'Possible values: 1-60s.' + - "Possible values: 1-60s." type: str - default: '30s' + default: "30s" required: false parameters: description: @@ -148,7 +145,7 @@ options: - Parameter value. Supports macros. type: str required: false - default: '' + default: "" description: description: - Description of the script. @@ -159,24 +156,24 @@ options: - State of the script. type: str required: false - choices: ['present', 'absent'] - default: 'present' + choices: ["present", "absent"] + default: "present" extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: test - Create new action operation script to execute webhook @@ -187,34 +184,33 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org - zabbix_script: + community.zabbix.zabbix_script: name: Test action operation script scope: action_operation script_type: webhook - command: 'return 0' + command: "return 0" description: "Test action operation script" state: present -''' +""" -RETURN = ''' -''' +RETURN = """ +""" from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils class Script(ZabbixBase): def get_script_ids(self, script_name): script_ids = [] - scripts = self._zapi.script.get({'filter': {'name': script_name}}) + scripts = self._zapi.script.get({"filter": {"name": script_name}}) for script in scripts: - script_ids.append(script['scriptid']) + script_ids.append(script["scriptid"]) return script_ids def create_script(self, name, script_type, command, scope, execute_on, menu_path, authtype, username, password, @@ -233,103 +229,95 @@ class Script(ZabbixBase): def generate_script_config(self, name, script_type, command, scope, execute_on, menu_path, authtype, username, password, publickey, privatekey, port, host_group, user_group, host_access, confirmation, script_timeout, parameters, description): - if host_group == 'all': - groupid = '0' + if host_group == "all": + groupid = "0" else: - groups = self._zapi.hostgroup.get({'filter': {'name': host_group}}) + groups = self._zapi.hostgroup.get({"filter": {"name": host_group}}) if not groups: - self._module.fail_json(changed=False, msg='Host group "%s" not found' % host_group) - groupid = groups[0]['groupid'] + self._module.fail_json(changed=False, msg="Host group '%s' not found" % host_group) + groupid = groups[0]["groupid"] - if user_group == 'all': - usrgrpid = '0' + if user_group == "all": + usrgrpid = "0" else: - user_groups = self._zapi.usergroup.get({'filter': {'name': user_group}}) + user_groups = self._zapi.usergroup.get({"filter": {"name": user_group}}) if not user_groups: - self._module.fail_json(changed=False, msg='User group "%s" not found' % user_group) - usrgrpid = user_groups[0]['usrgrpid'] + self._module.fail_json(changed=False, msg="User group '%s' not found" % user_group) + usrgrpid = user_groups[0]["usrgrpid"] request = { - 'name': name, - 'type': str(zabbix_utils.helper_to_numeric_value([ - 'script', - 'ipmi', - 'ssh', - 'telnet', - '', - 'webhook'], script_type)), - 'command': command, - 'scope': str(zabbix_utils.helper_to_numeric_value([ - '', - 'action_operation', - 'manual_host_action', - '', - 'manual_event_action'], scope)), - 'groupid': groupid + "name": name, + "type": str(zabbix_utils.helper_to_numeric_value([ + "script", + "ipmi", + "ssh", + "telnet", + "", + "webhook"], script_type)), + "command": command, + "scope": str(zabbix_utils.helper_to_numeric_value([ + "", + "action_operation", + "manual_host_action", + "", + "manual_event_action"], scope)), + "groupid": groupid } if description is not None: - request['description'] = description + request["description"] = description - if script_type == 'script': + if script_type == "script": if execute_on is None: - execute_on = 'zabbix_server_proxy' - request['execute_on'] = str(zabbix_utils.helper_to_numeric_value([ - 'zabbix_agent', - 'zabbix_server', - 'zabbix_server_proxy'], execute_on)) + execute_on = "zabbix_server_proxy" + request["execute_on"] = str(zabbix_utils.helper_to_numeric_value([ + "zabbix_agent", + "zabbix_server", + "zabbix_server_proxy"], execute_on)) - if scope in ['manual_host_action', 'manual_event_action']: + if scope in ["manual_host_action", "manual_event_action"]: if menu_path is None: - request['menu_path'] = '' + request["menu_path"] = "" else: - request['menu_path'] = menu_path - request['usrgrpid'] = usrgrpid - request['host_access'] = str(zabbix_utils.helper_to_numeric_value([ - '', - '', - 'read', - 'write'], host_access)) + request["menu_path"] = menu_path + request["usrgrpid"] = usrgrpid + request["host_access"] = str(zabbix_utils.helper_to_numeric_value([ + "", + "", + "read", + "write"], host_access)) if confirmation is None: - request['confirmation'] = '' + request["confirmation"] = "" else: - request['confirmation'] = confirmation + request["confirmation"] = confirmation - if script_type == 'ssh': + if script_type == "ssh": if authtype is None: - self._module.fail_json(changed=False, msg='authtype must be provided for ssh script type') - request['authtype'] = str(zabbix_utils.helper_to_numeric_value([ - 'password', - 'public_key'], authtype)) - if authtype == 'public_key': + self._module.fail_json(changed=False, msg="authtype must be provided for ssh script type") + request["authtype"] = str(zabbix_utils.helper_to_numeric_value([ + "password", + "public_key"], authtype)) + if authtype == "public_key": if publickey is None or privatekey is None: - self._module.fail_json(changed=False, msg='publickey and privatekey must be provided for ssh script type with publickey authtype') - request['publickey'] = publickey - request['privatekey'] = privatekey + self._module.fail_json(changed=False, msg="publickey and privatekey must be provided for ssh script type with publickey authtype") + request["publickey"] = publickey + request["privatekey"] = privatekey - if script_type in ['ssh', 'telnet']: + if script_type in ["ssh", "telnet"]: if username is None: - self._module.fail_json(changed=False, msg='username must be provided for "ssh" and "telnet" script types') - request['username'] = username - if (script_type == 'ssh' and authtype == 'password') or script_type == 'telnet': + self._module.fail_json(changed=False, msg="username must be provided for 'ssh' and 'telnet' script types") + request["username"] = username + if (script_type == "ssh" and authtype == "password") or script_type == "telnet": if password is None: - self._module.fail_json(changed=False, msg='password must be provided for telnet script type or ssh script type with password autheype') - request['password'] = password + self._module.fail_json(changed=False, msg="password must be provided for telnet script type or ssh script type with password autheype") + request["password"] = password if port is not None: - request['port'] = port + request["port"] = port - if script_type == 'webhook': - request['timeout'] = script_timeout + if script_type == "webhook": + request["timeout"] = script_timeout if parameters: - request['parameters'] = parameters - - if LooseVersion(self._zbx_api_version) < LooseVersion('5.4'): - if script_type not in ['script', 'ipmi']: - self._module.fail_json(changed=False, msg='script_type must be script or ipmi in version <5.4') - if 'scope' in request: - del request['scope'] - if 'menu_path' in request: - del request['menu_path'] + request["parameters"] = parameters return request @@ -338,7 +326,7 @@ class Script(ZabbixBase): generated_config = self.generate_script_config(name, script_type, command, scope, execute_on, menu_path, authtype, username, password, publickey, privatekey, port, host_group, user_group, host_access, confirmation, script_timeout, parameters, description) - live_config = self._zapi.script.get({'filter': {'name': name}})[0] + live_config = self._zapi.script.get({"filter": {"name": name}})[0] change_parameters = {} difference = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(generated_config, live_config, change_parameters)) @@ -348,7 +336,7 @@ class Script(ZabbixBase): if self._module.check_mode: self._module.exit_json(changed=True) - generated_config['scriptid'] = live_config['scriptid'] + generated_config["scriptid"] = live_config["scriptid"] self._zapi.script.update(generated_config) self._module.exit_json(changed=True, msg="Script %s updated" % name) @@ -356,55 +344,55 @@ class Script(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - name=dict(type='str', required=True), + name=dict(type="str", required=True), script_type=dict( - type='str', + type="str", required=True, - choices=['script', 'ipmi', 'ssh', 'telnet', 'webhook']), - command=dict(type='str', required=True), + choices=["script", "ipmi", "ssh", "telnet", "webhook"]), + command=dict(type="str", required=True), scope=dict( - type='str', + type="str", required=False, - choices=['action_operation', 'manual_host_action', 'manual_event_action'], - default='action_operation'), + choices=["action_operation", "manual_host_action", "manual_event_action"], + default="action_operation"), execute_on=dict( - type='str', + type="str", required=False, - choices=['zabbix_agent', 'zabbix_server', 'zabbix_server_proxy'], - default='zabbix_server_proxy'), - menu_path=dict(type='str', required=False), + choices=["zabbix_agent", "zabbix_server", "zabbix_server_proxy"], + default="zabbix_server_proxy"), + menu_path=dict(type="str", required=False), authtype=dict( - type='str', + type="str", required=False, - choices=['password', 'public_key']), - username=dict(type='str', required=False), - password=dict(type='str', required=False, no_log=True), - publickey=dict(type='str', required=False), - privatekey=dict(type='str', required=False, no_log=True), - port=dict(type='str', required=False), - host_group=dict(type='str', required=False, default='all'), - user_group=dict(type='str', required=False, default='all'), + choices=["password", "public_key"]), + username=dict(type="str", required=False), + password=dict(type="str", required=False, no_log=True), + publickey=dict(type="str", required=False), + privatekey=dict(type="str", required=False, no_log=True), + port=dict(type="str", required=False), + host_group=dict(type="str", required=False, default="all"), + user_group=dict(type="str", required=False, default="all"), host_access=dict( - type='str', + type="str", required=False, - choices=['read', 'write'], - default='read'), - confirmation=dict(type='str', required=False), - script_timeout=dict(type='str', default='30s', required=False), + choices=["read", "write"], + default="read"), + confirmation=dict(type="str", required=False), + script_timeout=dict(type="str", default="30s", required=False), parameters=dict( - type='list', - elements='dict', + type="list", + elements="dict", options=dict( - name=dict(type='str', required=True), - value=dict(type='str', required=False, default='') + name=dict(type="str", required=True), + value=dict(type="str", required=False, default="") ) ), - description=dict(type='str', required=False), + description=dict(type="str", required=False), state=dict( - type='str', + type="str", required=False, - default='present', - choices=['present', 'absent']) + default="present", + choices=["present", "absent"]) )) module = AnsibleModule( @@ -412,32 +400,26 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - name = module.params['name'] - script_type = module.params['script_type'] - command = module.params['command'] - scope = module.params['scope'] - execute_on = module.params['execute_on'] - menu_path = module.params['menu_path'] - authtype = module.params['authtype'] - username = module.params['username'] - password = module.params['password'] - publickey = module.params['publickey'] - privatekey = module.params['privatekey'] - port = module.params['port'] - host_group = module.params['host_group'] - user_group = module.params['user_group'] - host_access = module.params['host_access'] - confirmation = module.params['confirmation'] - script_timeout = module.params['script_timeout'] - parameters = module.params['parameters'] - description = module.params['description'] - state = module.params['state'] + name = module.params["name"] + script_type = module.params["script_type"] + command = module.params["command"] + scope = module.params["scope"] + execute_on = module.params["execute_on"] + menu_path = module.params["menu_path"] + authtype = module.params["authtype"] + username = module.params["username"] + password = module.params["password"] + publickey = module.params["publickey"] + privatekey = module.params["privatekey"] + port = module.params["port"] + host_group = module.params["host_group"] + user_group = module.params["user_group"] + host_access = module.params["host_access"] + confirmation = module.params["confirmation"] + script_timeout = module.params["script_timeout"] + parameters = module.params["parameters"] + description = module.params["description"] + state = module.params["state"] script = Script(module) script_ids = script.get_script_ids(name) diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_service.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_service.py index 9468ee49a..8a7b9b605 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_service.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_service.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ --- module: zabbix_service short_description: Create/update/delete Zabbix service @@ -18,61 +18,26 @@ author: - "Emmanuel Riviere (@emriver)" - "Evgeny Yurchenko (@BGmot)" requirements: - - "python >= 2.7" + - "python >= 3.9" options: name: description: - Name of Zabbix service required: true type: str - parent: - description: - - Name of Zabbix service parent - - With >= Zabbix 6.0 this field is removed from the API and is dropped silently by module. - required: false - type: str - sla: - description: - - Sla value (i.e 99.99), goodsla in Zabbix API - - With >= Zabbix 6.0 this field is removed from the API and is dropped silently by module. - required: false - type: float - calculate_sla: - description: - - If yes, calculate the SLA value for this service, showsla in Zabbix API - - With >= Zabbix 6.0 this field is removed from the API and is dropped silently by module. - required: false - default: false - type: bool algorithm: description: - - Algorithm used to calculate the sla with < Zabbix 6.0 - - ' - C(no), sla is not calculated' - - ' - C(one_child), problem if at least one child has a problem' - - ' - C(all_children), problem if all children have problems' - - Status calculation rule. Only applicable if child services exists with >= Zabbix 6.0 - - ' - C(status_to_ok), set status to OK with' - - ' - C(most_crit_if_all_children), most critical if all children have problems' - - ' - C(most_crit_of_child_serv), most critical of child services with' - required: false - type: str - choices: ["no", "one_child", "all_children", "status_to_ok", "most_crit_if_all_children", "most_crit_of_child_serv"] - default: one_child - trigger_name: - description: - - Name of trigger linked to the service. - - With >= Zabbix 6.0 this field is removed from the API and is dropped silently by module. - required: false - type: str - trigger_host: - description: - - Name of host linked to the service. - - With >= Zabbix 6.0 this field is removed from the API and is dropped silently by module. + - Status calculation rule. Only applicable if child services exists. + - " - C(status_to_ok), set status to OK with" + - " - C(most_crit_if_all_children), most critical if all children have problems" + - " - C(most_crit_of_child_serv), most critical of child services with" required: false type: str + choices: ["status_to_ok", "most_crit_if_all_children", "most_crit_of_child_serv"] + default: status_to_ok state: description: - - 'State: present - create/update service; absent - delete service.' + - "State: present - create/update service; absent - delete service." required: false choices: [present, absent] default: "present" @@ -85,20 +50,17 @@ options: weight: description: - Service weight. - - New field with >= Zabbix 6.0. required: false - default: '0' + default: "0" type: str description: description: - Description of the service. - - New field with >= Zabbix 6.0. required: false type: str tags: description: - Service tags to be created for the service. - - New field with >= Zabbix 6.0. required: false type: list elements: dict @@ -116,7 +78,6 @@ options: problem_tags: description: - Problem tags to be created for the service. - - New field with >= Zabbix 6.0. required: false type: list elements: dict @@ -131,7 +92,7 @@ options: - Mapping condition operator. - C(equals) - C(like) - choices: ['equals', 'like'] + choices: ["equals", "like"] required: false default: "equals" type: str @@ -144,21 +105,18 @@ options: parents: description: - Parent services to be linked to the service. - - New field with >= Zabbix 6.0. required: false type: list elements: str children: description: - Child services to be linked to the service. - - New field with >= Zabbix 6.0. required: false type: list elements: str propagation_rule: description: - Status propagation value. Must be set together with propagation_rule. - - New field with >= Zabbix 6.0. - C(as_is) propagate service status as is - without any changes - C(increase) increase the propagated status by a given propagation_value (by 1 to 5 severities) - C(decrease) decrease the propagated status by a given propagation_value (by 1 to 5 severities) @@ -171,30 +129,28 @@ options: propagation_value: description: - Status propagation value. Must be set together with propagation_rule. - - New field with >= Zabbix 6.0. - - 'Possible values when I(propagation_rule=as_is or ignore):' - - ' - C(not_classified)' - - 'Possible values when I(propagation_rule=increase or decrease):' - - ' - C(information)' - - ' - C(warning)' - - ' - C(average)' - - ' - C(high)' - - ' - C(disaster)' - - 'Possible values when I(propagation_rule=fixed):' - - ' - C(ok)' - - ' - C(not_classified)' - - ' - C(information)' - - ' - C(warning)' - - ' - C(average)' - - ' - C(high)' - - ' - C(disaster)' + - "Possible values when I(propagation_rule=as_is or ignore):" + - " - C(not_classified)" + - "Possible values when I(propagation_rule=increase or decrease):" + - " - C(information)" + - " - C(warning)" + - " - C(average)" + - " - C(high)" + - " - C(disaster)" + - "Possible values when I(propagation_rule=fixed):" + - " - C(ok)" + - " - C(not_classified)" + - " - C(information)" + - " - C(warning)" + - " - C(average)" + - " - C(high)" + - " - C(disaster)" - Required with C(propagation_rule) required: false type: str status_rules: description: - Status rules for the service. - - New field with >= Zabbix 6.0. required: false type: list elements: dict @@ -214,8 +170,8 @@ options: type: str limit_value: description: - - 'Limit value: N, N% or W' - - 'Possible values: 1-100000 for N and W, 1-100 for N%' + - "Limit value: N, N% or W" + - "Possible values: 1-100000 for N and W, 1-100 for N%" required: true type: int limit_status: @@ -245,43 +201,23 @@ options: extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ --- # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 -# Creates a new Zabbix service with Zabbix < 6.0 -- name: Manage services - # set task level variables - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_service: - name: apache2 service - sla: 99.99 - calculate_sla: yes - algorithm: one_child - trigger_name: apache2 service status - trigger_host: webserver01 - state: present - -# Creates a new Zabbix service with Zabbix >= 6.0 +# Creates a new Zabbix service - name: Create Zabbix service monitoring Apache2 in DCs in Toronto area # set task level variables vars: @@ -290,10 +226,10 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_service: - name: 'apache2 service Toronto' + name: "apache2 service Toronto" description: Apache2 services in Toronto area sortorder: 0 propagation_rule: increase @@ -325,7 +261,7 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_service: name: apache2 service @@ -336,27 +272,26 @@ EXAMPLES = ''' - tag: area value: global children: - - 'apache2 service Toronto' -''' + - "apache2 service Toronto" +""" -RETURN = ''' +RETURN = """ --- -''' +""" from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils -from ansible.module_utils.compat.version import LooseVersion class Service(ZabbixBase): def get_service_ids(self, service_name): service_ids = [] - services = self._zapi.service.get({'filter': {'name': service_name}}) + services = self._zapi.service.get({"filter": {"name": service_name}}) for service in services: - service_ids.append(service['serviceid']) + service_ids.append(service["serviceid"]) return service_ids def delete_service(self, service_ids): @@ -365,208 +300,160 @@ class Service(ZabbixBase): self._zapi.service.delete(service_ids) def dump_services(self, service_ids): - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - services = self._zapi.service.get({'output': 'extend', 'filter': {'serviceid': service_ids}, 'selectParent': '1'}) - else: - services = self._zapi.service.get({'output': 'extend', 'filter': {'serviceid': service_ids}, 'selectParents': 'extend', - 'selectTags': 'extend', 'selectProblemTags': 'extend', 'selectChildren': 'extend', - 'selectStatusRules': 'extend'}) + services = self._zapi.service.get({"output": "extend", "filter": {"serviceid": service_ids}, "selectParents": "extend", + "selectTags": "extend", "selectProblemTags": "extend", "selectChildren": "extend", + "selectStatusRules": "extend"}) return services - def generate_service_config(self, name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, + def generate_service_config(self, name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules): - algorithms = {'no': '0', 'one_child': '1', 'all_children': '2', - 'status_to_ok': '0', 'most_crit_if_all_children': '1', 'most_crit_of_child_serv': '2'} + algorithms = {"status_to_ok": "0", "most_crit_if_all_children": "1", "most_crit_of_child_serv": "2"} algorithm = algorithms[algorithm] - if LooseVersion(self._zbx_api_version) < LooseVersion('6.0'): - if calculate_sla: - calculate_sla = 1 - else: - calculate_sla = 0 - else: - sla = 0 # Parameter does not exist in >= 6.0 but we needed for format() function constructing request - - # Zabbix api return when no trigger - trigger_id = 0 - if trigger_host and trigger_name: - # Retrieving the host to get the trigger - hosts = self._zapi.host.get({'filter': {'host': trigger_host}}) - if not hosts: - self._module.fail_json(msg="Target host %s not found" % trigger_host) - host_id = hosts[0]['hostid'] - - triggers = self._zapi.trigger.get({'filter': {'description': trigger_name}, 'hostids': [host_id]}) - if not triggers: - self._module.fail_json(msg="Trigger %s not found on host %s" % (trigger_name, trigger_host)) - trigger_id = triggers[0]['triggerid'] - request = { - 'name': name, - 'algorithm': algorithm, - 'showsla': str(calculate_sla), - 'sortorder': sortorder, - 'goodsla': format(sla, '.4f'), # Sla has 4 decimals - 'triggerid': str(trigger_id) + "name": name, + "algorithm": algorithm, + "sortorder": sortorder, + "description": description, + "weight": weight } - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - request.pop('showsla') - request.pop('triggerid') - request.pop('goodsla') - request['description'] = description - request['weight'] = weight + if tags: + request["tags"] = tags + else: + request["tags"] = [] + + request["problem_tags"] = [] + if problem_tags: + p_operators = {"equals": "0", "like": "2"} + for p_tag in problem_tags: + pt = {"tag": p_tag["tag"], "operator": "0", "value": ""} + if "operator" in p_tag: + pt["operator"] = p_operators[p_tag["operator"]] + if "value" in p_tag: + pt["value"] = p_tag["value"] + request["problem_tags"].append(pt) + + if parents: + p_service_ids = [] + p_services = self._zapi.service.get({"filter": {"name": parents}}) + for p_service in p_services: + p_service_ids.append({"serviceid": p_service["serviceid"]}) + request["parents"] = p_service_ids + else: + request["parents"] = [] + + if children: + c_service_ids = [] + c_services = self._zapi.service.get({"filter": {"name": children}}) + for c_service in c_services: + c_service_ids.append({"serviceid": c_service["serviceid"]}) + request["children"] = c_service_ids + else: + request["children"] = [] + + request["status_rules"] = [] + if status_rules: + for s_rule in status_rules: + status_rule = {} + if "type" in s_rule: + sr_type_map = {"at_least_n_child_services_have_status_or_above": "0", + "at_least_npct_child_services_have_status_or_above": "1", + "less_than_n_child_services_have_status_or_below": "2", + "less_than_npct_child_services_have_status_or_below": "3", + "weight_child_services_with_status_or_above_at_least_w": "4", + "weight_child_services_with_status_or_above_at_least_npct": "5", + "weight_child_services_with_status_or_below_less_w": "6", + "weight_child_services_with_status_or_below_less_npct": "7"} + if s_rule["type"] not in sr_type_map: + self._module.fail_json(msg="Wrong value for 'type' parameter in status rule.") + status_rule["type"] = sr_type_map[s_rule["type"]] + else: + self._module.fail_json(msg="'type' is mandatory paremeter for status rule.") - if tags: - request['tags'] = tags - else: - request['tags'] = [] - - request['problem_tags'] = [] - if problem_tags: - p_operators = {'equals': '0', 'like': '2'} - for p_tag in problem_tags: - pt = {'tag': p_tag['tag'], 'operator': '0', 'value': ''} - if 'operator' in p_tag: - pt['operator'] = p_operators[p_tag['operator']] - if 'value' in p_tag: - pt['value'] = p_tag['value'] - request['problem_tags'].append(pt) - - if parents: - p_service_ids = [] - p_services = self._zapi.service.get({'filter': {'name': parents}}) - for p_service in p_services: - p_service_ids.append({'serviceid': p_service['serviceid']}) - request['parents'] = p_service_ids - else: - request['parents'] = [] - - if children: - c_service_ids = [] - c_services = self._zapi.service.get({'filter': {'name': children}}) - for c_service in c_services: - c_service_ids.append({'serviceid': c_service['serviceid']}) - request['children'] = c_service_ids - else: - request['children'] = [] - - request['status_rules'] = [] - if status_rules: - for s_rule in status_rules: - status_rule = {} - if 'type' in s_rule: - sr_type_map = {'at_least_n_child_services_have_status_or_above': '0', - 'at_least_npct_child_services_have_status_or_above': '1', - 'less_than_n_child_services_have_status_or_below': '2', - 'less_than_npct_child_services_have_status_or_below': '3', - 'weight_child_services_with_status_or_above_at_least_w': '4', - 'weight_child_services_with_status_or_above_at_least_npct': '5', - 'weight_child_services_with_status_or_below_less_w': '6', - 'weight_child_services_with_status_or_below_less_npct': '7'} - if s_rule['type'] not in sr_type_map: - self._module.fail_json(msg="Wrong value for 'type' parameter in status rule.") - status_rule['type'] = sr_type_map[s_rule['type']] - else: - self._module.fail_json(msg="'type' is mandatory paremeter for status rule.") - - if 'limit_value' in s_rule: - lv = s_rule['limit_value'] - if status_rule['type'] in ['0', '2', '4', '6']: - if int(lv) < 1 or int(lv) > 100000: - self._module.fail_json(msg="'limit_value' for N and W must be between 1 and 100000 but provided %s" % lv) - else: - if int(lv) < 1 or int(lv) > 100: - self._module.fail_json(msg="'limit_value' for N%% must be between 1 and 100 but provided %s" % lv) - status_rule['limit_value'] = str(lv) - else: - self._module.fail_json(msg="'limit_value' is mandatory paremeter for status rule.") - - if 'limit_status' in s_rule: - sr_ls_map = {'ok': '-1', 'not_classified': '0', 'information': '1', 'warning': '2', - 'average': '3', 'high': '4', 'disaster': 5} - if s_rule['limit_status'] not in sr_ls_map: - self._module.fail_json(msg="Wrong value for 'limit_status' parameter in status rule.") - status_rule['limit_status'] = sr_ls_map[s_rule['limit_status']] + if "limit_value" in s_rule: + lv = s_rule["limit_value"] + if status_rule["type"] in ["0", "2", "4", "6"]: + if int(lv) < 1 or int(lv) > 100000: + self._module.fail_json(msg="'limit_value' for N and W must be between 1 and 100000 but provided %s" % lv) else: - self._module.fail_json(msg="'limit_status' is mandatory paremeter for status rule.") - - if 'new_status' in s_rule: - sr_ns_map = {'not_classified': '0', 'information': '1', 'warning': '2', - 'average': '3', 'high': '4', 'disaster': '5'} - if s_rule['new_status'] not in sr_ns_map: - self._module.fail_json(msg="Wrong value for 'new_status' parameter in status rule.") - status_rule['new_status'] = sr_ns_map[s_rule['new_status']] - else: - self._module.fail_json(msg="'new_status' is mandatory paremeter for status rule.") - - request['status_rules'].append(status_rule) - - request['propagation_rule'] = '0' - if propagation_rule: - if propagation_value is None: - self._module.fail_json(msg="If 'propagation_rule' is provided then 'propagation_value' must be provided too.") - pr_map = {'as_is': '0', 'increase': '1', 'decrease': '2', 'ignore': '3', 'fixed': '4'} - if propagation_rule not in pr_map: - self._module.fail_json(msg="Wrong value for 'propagation_rule' parameter.") + if int(lv) < 1 or int(lv) > 100: + self._module.fail_json(msg="'limit_value' for N%% must be between 1 and 100 but provided %s" % lv) + status_rule["limit_value"] = str(lv) else: - request['propagation_rule'] = pr_map[propagation_rule] - - request['propagation_value'] = '0' - if propagation_value: - if propagation_rule is None: - self._module.fail_json(msg="If 'propagation_value' is provided then 'propagation_rule' must be provided too.") - pv_map = {'ok': '-1', 'not_classified': '0', 'information': '1', 'warning': '2', - 'average': '3', 'high': '4', 'disaster': '5'} - if propagation_value not in pv_map: - self._module.fail_json(msg="Wrong value for 'propagation_value' parameter.") + self._module.fail_json(msg="'limit_value' is mandatory paremeter for status rule.") + + if "limit_status" in s_rule: + sr_ls_map = {"ok": "-1", "not_classified": "0", "information": "1", "warning": "2", + "average": "3", "high": "4", "disaster": 5} + if s_rule["limit_status"] not in sr_ls_map: + self._module.fail_json(msg="Wrong value for 'limit_status' parameter in status rule.") + status_rule["limit_status"] = sr_ls_map[s_rule["limit_status"]] else: - request['propagation_value'] = pv_map[propagation_value] - else: - if parent: - parent_ids = self.get_service_ids(parent) - if not parent_ids: - self._module.fail_json(msg="Parent %s not found" % parent) - request['parentid'] = parent_ids[0] + self._module.fail_json(msg="'limit_status' is mandatory paremeter for status rule.") + + if "new_status" in s_rule: + sr_ns_map = {"not_classified": "0", "information": "1", "warning": "2", + "average": "3", "high": "4", "disaster": "5"} + if s_rule["new_status"] not in sr_ns_map: + self._module.fail_json(msg="Wrong value for 'new_status' parameter in status rule.") + status_rule["new_status"] = sr_ns_map[s_rule["new_status"]] + else: + self._module.fail_json(msg="'new_status' is mandatory paremeter for status rule.") + + request["status_rules"].append(status_rule) + + request["propagation_rule"] = "0" + if propagation_rule: + if propagation_value is None: + self._module.fail_json(msg="If 'propagation_rule' is provided then 'propagation_value' must be provided too.") + pr_map = {"as_is": "0", "increase": "1", "decrease": "2", "ignore": "3", "fixed": "4"} + if propagation_rule not in pr_map: + self._module.fail_json(msg="Wrong value for 'propagation_rule' parameter.") + else: + request["propagation_rule"] = pr_map[propagation_rule] + + request["propagation_value"] = "0" + if propagation_value: + if propagation_rule is None: + self._module.fail_json(msg="If 'propagation_value' is provided then 'propagation_rule' must be provided too.") + pv_map = {"ok": "-1", "not_classified": "0", "information": "1", "warning": "2", + "average": "3", "high": "4", "disaster": "5"} + if propagation_value not in pv_map: + self._module.fail_json(msg="Wrong value for 'propagation_value' parameter.") + else: + request["propagation_value"] = pv_map[propagation_value] + return request - def create_service(self, name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, algorithm, + def create_service(self, name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules): if self._module.check_mode: self._module.exit_json(changed=True) - self._zapi.service.create(self.generate_service_config(name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, + self._zapi.service.create(self.generate_service_config(name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules)) - def update_service(self, service_id, name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, algorithm, + def update_service(self, service_id, name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules): - generated_config = self.generate_service_config(name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, algorithm, + generated_config = self.generate_service_config(name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules) live_config = self.dump_services(service_id)[0] - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.0'): - if len(live_config['parents']) > 0: - # Need to rewrite parents list to only service ids - new_parents = [] - for parent in live_config['parents']: - new_parents.append({'serviceid': parent['serviceid']}) - live_config['parents'] = new_parents - - if len(live_config['children']) > 0: - # Need to rewrite children list to only service ids - new_children = [] - for child in live_config['children']: - new_children.append({'serviceid': child['serviceid']}) - live_config['children'] = new_children - - else: - if 'goodsla' in live_config: - live_config['goodsla'] = format(float(live_config['goodsla']), '.4f') + if len(live_config["parents"]) > 0: + # Need to rewrite parents list to only service ids + new_parents = [] + for parent in live_config["parents"]: + new_parents.append({"serviceid": parent["serviceid"]}) + live_config["parents"] = new_parents - if 'parentid' in generated_config: - if 'serviceid' in live_config['parent']: - live_config['parentid'] = live_config['parent']['serviceid'] + if len(live_config["children"]) > 0: + # Need to rewrite children list to only service ids + new_children = [] + for child in live_config["children"]: + new_children.append({"serviceid": child["serviceid"]}) + live_config["children"] = new_children change_parameters = {} difference = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(generated_config, live_config, change_parameters)) @@ -576,7 +463,7 @@ class Service(ZabbixBase): if self._module.check_mode: self._module.exit_json(changed=True) - generated_config['serviceid'] = service_id + generated_config["serviceid"] = service_id self._zapi.service.update(generated_config) self._module.exit_json(changed=True, msg="Service %s updated" % name) @@ -584,81 +471,75 @@ class Service(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - name=dict(type='str', required=True), - parent=dict(type='str', required=False), - sla=dict(type='float', required=False), - calculate_sla=dict(type='bool', required=False, default=False), - algorithm=dict(default='one_child', required=False, choices=['no', 'one_child', 'all_children', - 'status_to_ok', 'most_crit_if_all_children', 'most_crit_of_child_serv']), - trigger_name=dict(type='str', required=False), - trigger_host=dict(type='str', required=False), - sortorder=dict(type='str', required=True), - weight=dict(default='0', type='str', required=False), - state=dict(default="present", choices=['present', 'absent']), - description=dict(type='str', required=False), + name=dict(type="str", required=True), + algorithm=dict(default="status_to_ok", required=False, choices=["status_to_ok", "most_crit_if_all_children", "most_crit_of_child_serv"]), + sortorder=dict(type="str", required=True), + weight=dict(default="0", type="str", required=False), + state=dict(default="present", choices=["present", "absent"]), + description=dict(type="str", required=False), tags=dict( - type='list', + type="list", required=False, - elements='dict', + elements="dict", options=dict( tag=dict( - type='str', + type="str", required=True ), value=dict( - type='str', + type="str", required=False ) ) ), problem_tags=dict( - type='list', + type="list", required=False, - elements='dict', + elements="dict", options=dict( tag=dict( - type='str', + type="str", required=True ), operator=dict( - type='str', + type="str", required=False, choices=[ - 'equals', - 'like' + "equals", + "like" ], - default='equals' + default="equals" ), value=dict( - type='str', + type="str", required=False, - default='' + default="" ) ) ), - parents=dict(type='list', required=False, elements='str'), - children=dict(type='list', required=False, elements='str'), - propagation_rule=dict(default='as_is', type='str', required=False), - propagation_value=dict(type='str', required=False), + parents=dict(type="list", required=False, elements="str"), + children=dict(type="list", required=False, elements="str"), + propagation_rule=dict(default="as_is", type="str", required=False), + propagation_value=dict(type="str", required=False), status_rules=dict( - type='list', + type="list", required=False, - elements='dict', + elements="dict", options=dict( type=dict( - type='str', + type="str", required=True ), limit_value=dict( - type='int', + type="int", required=True ), limit_status=dict( - type='str', + type="str", required=True ), new_status=dict( - type='str', + type="str", required=True ) ) @@ -669,30 +550,19 @@ def main(): supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - name = module.params['name'] - parent = module.params['parent'] - sla = module.params['sla'] - calculate_sla = module.params['calculate_sla'] - algorithm = module.params['algorithm'] - trigger_name = module.params['trigger_name'] - trigger_host = module.params['trigger_host'] - sortorder = module.params['sortorder'] - weight = module.params['weight'] - state = module.params['state'] - description = module.params['description'] - tags = module.params['tags'] - problem_tags = module.params['problem_tags'] - parents = module.params['parents'] - children = module.params['children'] - propagation_rule = module.params['propagation_rule'] - propagation_value = module.params['propagation_value'] - status_rules = module.params['status_rules'] + name = module.params["name"] + algorithm = module.params["algorithm"] + sortorder = module.params["sortorder"] + weight = module.params["weight"] + state = module.params["state"] + description = module.params["description"] + tags = module.params["tags"] + problem_tags = module.params["problem_tags"] + parents = module.params["parents"] + children = module.params["children"] + propagation_rule = module.params["propagation_rule"] + propagation_value = module.params["propagation_value"] + status_rules = module.params["status_rules"] # Load service module service = Service(module) @@ -706,18 +576,16 @@ def main(): module.exit_json(changed=True, result="Successfully deleted service(s) %s" % name) elif state == "present": - if (trigger_name and not trigger_host) or (trigger_host and not trigger_name): - module.fail_json(msg="Specify either both trigger_host and trigger_name or none to create or update a service") # Does not exists going to create it if not service_ids: - service.create_service(name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, algorithm, description, + service.create_service(name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules) module.exit_json(changed=True, msg="Service %s created" % name) # Else we update it if needed else: - service.update_service(service_ids[0], name, parent, sla, calculate_sla, trigger_name, trigger_host, sortorder, weight, + service.update_service(service_ids[0], name, sortorder, weight, algorithm, description, tags, problem_tags, parents, children, propagation_rule, propagation_value, status_rules) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_settings.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_settings.py new file mode 100644 index 000000000..de8ec6886 --- /dev/null +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_settings.py @@ -0,0 +1,1112 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2023, ONODERA Masaru <masaru-onodera@ieee.org> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +DOCUMENTATION = """ +--- +module: zabbix_settings + +short_description: Update Zabbix global settings. + +description: + - This module allows you to update Zabbix global settings. + +author: + - ONODERA Masaru(@masa-orca) + +requirements: + - "python >= 3.9" + +version_added: 2.1.0 + +options: + default_lang: + description: + - Default language for users. + required: false + type: str + default_timezone: + description: + - Default time zone for users. + - Please set C(system) if you want to use system time zone. + required: false + type: str + default_theme: + description: + - Default theme for users. + required: false + type: str + choices: + - blue-theme + - dark-theme + - hc-light + - hc-dark + search_limit: + description: + - A number of search and filter results limit. + required: false + type: int + max_overview_table_size: + description: + - Max number of columns and rows in overview tables + required: false + type: int + max_in_table: + description: + - Max count of elements to show inside table cell + required: false + type: int + server_check_interval: + description: + - The Zabbix shows "Zabbix server is down" warning if C(true). + required: false + type: bool + work_period: + description: + - Working time setting. + - U(https://www.zabbix.com/documentation/current/en/manual/appendix/time_period) + required: false + type: str + show_technical_errors: + description: + - The Zabbix shows PHP and SQL technical errors to users who are non-Super admin or belong to user groups with debug mode not enabled if C(true). + required: false + type: bool + history_period: + description: + - Max period of displaying history data. + - Accepts seconds and time unit with suffix (e.g. 24h). + required: false + type: str + period_default: + description: + - Default period value for time filter. + - Accepts seconds and time unit with suffix (e.g. 1h). + required: false + type: str + max_period: + description: + - Max period for time filter. + - Accepts seconds and time unit with suffix (e.g. 1y). + required: false + type: str + severity_color_0: + description: + - A custom color for not classified severity. + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + severity_color_1: + description: + - A custom color for information severity. + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + severity_color_2: + description: + - A custom color for warning severity. + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + severity_color_3: + description: + - A custom color for average severity. + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + severity_color_4: + description: + - A custom color for high severity. + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + severity_color_5: + description: + - A custom color for disaster severity. + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + severity_name_0: + description: + - A custom name for not classified severity. + required: false + type: str + severity_name_1: + description: + - A custom name for information severity. + required: false + type: str + severity_name_2: + description: + - A custom name for warning severity. + required: false + type: str + severity_name_3: + description: + - A custom name for average severity. + required: false + type: str + severity_name_4: + description: + - A custom name for high severity. + required: false + type: str + severity_name_5: + description: + - A custom name for disaster severity. + required: false + type: str + custom_color: + description: + - Custom event color settings will be activated if C(true). + required: false + type: bool + ok_period: + description: + - A time of period for displaying OK triggers. + - Accepts seconds and time unit with suffix (e.g. 5m). + required: false + type: str + blink_period: + description: + - A time of period for blinking status changed triggers. + - Accepts seconds and time unit with suffix (e.g. 5m). + required: false + type: str + problem_unack_color: + description: + - A custom color for unacknowledged PROBLEM events. + - This setting will be activated if I(custom_color=true). + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + problem_ack_color: + description: + - A custom color for acknowledged PROBLEM events. + - This setting will be activated if I(custom_color=true). + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + ok_unack_color: + description: + - A custom color for unacknowledged RESOLVED events. + - This setting will be activated if I(custom_color=true). + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + ok_ack_color: + description: + - A custom color for acknowledged RESOLVED events. + - This setting will be activated if I(custom_color=true). + - Please set hexadecimal color code (e.g. 00FF00). + required: false + type: str + problem_unack_style: + description: + - Unacknowledged PROBLEM events blink if C(true). + required: false + type: bool + problem_ack_style: + description: + - Acknowledged PROBLEM events blink if C(true). + required: false + type: bool + ok_unack_style: + description: + - Unacknowledged RESOLVED events blink if C(true). + required: false + type: bool + ok_ack_style: + description: + - Acknowledged RESOLVED events blink if C(true). + required: false + type: bool + frontend_url: + description: + - A URL of frontend. + - This parameter is used for url parameter of settings API. + required: false + type: str + discovery_group: + description: + - A hostgroup which discovered hosts will belong to. + required: false + type: str + default_inventory_mode: + description: + - A default value for host inventory mode. + required: false + type: str + choices: + - disabled + - manual + - automatic + alert_usrgrp: + description: + - A name of user group which user belongs to receive an alerm message when database down. + required: false + type: str + snmptrap_logging: + description: + - Logging unmatched SNMP traps will be ebabled if C(true). + required: false + type: bool + login_attempts: + description: + - A number of login attempts you can try with non blocked. + required: false + type: int + login_block: + description: + - A time of interval to reset login attempts when the user is blocked. + - Accepts seconds and time unit with suffix (e.g. 5m). + required: false + type: str + validate_uri_schemes: + description: + - Validate URI schemes if C(true). + required: false + type: bool + uri_valid_schemes: + description: + - A list of valid URI scheme. + required: false + type: list + elements: str + x_frame_options: + description: + - A text of X-Frame-Options of HTTP header. + required: false + type: str + iframe_sandboxing_enabled: + description: + - The Zabbix uses iframe sandboxing if C(true). + required: false + type: bool + iframe_sandboxing_exceptions: + description: + - A text of iframe sandboxing exceptions. + required: false + type: str + connect_timeout: + description: + - A time of connection timeout with Zabbix server. + required: false + type: str + socket_timeout: + description: + - A time of network default timeout. + required: false + type: str + media_type_test_timeout: + description: + - A time of network timeout for media type test. + required: false + type: str + item_test_timeout: + description: + - A time of network timeout for item tests. + required: false + type: str + script_timeout: + description: + - A time of network timeout for script execution. + required: false + type: str + report_test_timeout: + description: + - A time of network timeout for scheduled report test. + required: false + type: str + auditlog_enabled: + description: + - Enable audit logging if C(true). + required: false + type: bool + geomaps_tile_provider: + description: + - A provider of Geomap tile. + - Please set C(another) if you want use non default provider + required: false + type: str + choices: + - OpenStreetMap.Mapnik + - OpenTopoMap + - Stamen.TonerLite + - Stamen.Terrain + - USGS.USTopo + - USGS.USImagery + - another + geomaps_tile_url: + description: + - A URL of geomap tile. + required: false + type: str + geomaps_max_zoom: + description: + - Max zoom level of geomap. + required: false + type: str + geomaps_attribution: + description: + - A text of Geomap attribution. + required: false + type: str + vault_provider: + description: + - A name of vault provider. + - This parameter is available since Zabbix 6.2. + required: false + type: str + choices: + - HashiCorp_Vault + - CyberArk_Vault + +notes: + - This module manages settings related with settings api except ha_failover_delay. + +extends_documentation_fragment: + - community.zabbix.zabbix +""" + +EXAMPLES = """ +# If you want to use Username and Password to be authenticated by Zabbix Server +- name: Set credentials to access Zabbix Server API + ansible.builtin.set_fact: + ansible_user: Admin + ansible_httpapi_pass: zabbix + +# If you want to use API token to be authenticated by Zabbix Server +# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens +- name: Set API token + ansible.builtin.set_fact: + ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 + +- name: Update settings + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_settings: + alert_usrgrp: "0" + auditlog_enabled: false + blink_period: "10m" + connect_timeout: "30s" + custom_color: false + default_inventory_mode: automatic +""" + +RETURN = """ +msg: + description: The result of the operation + returned: success + type: str + sample: "Successfully update global settings" +""" + +import re + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase +from ansible.module_utils.compat.version import LooseVersion +import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils + + +class Settings(ZabbixBase): + # get setting setting + def get_settings(self): + try: + return self._zapi.settings.get({"output": "extend"}) + except Exception as e: + self._module.fail_json(msg="Failed to get settings: %s" % e) + + def _is_time(self, time): + pattern = re.compile(r"^(\d+)([smhdwMy]?)$") + search_result = pattern.search(time) + if search_result is None: + self._module.fail_json(msg="{0} is invalid value.".format(time)) + return True + + def _is_color(self, color): + pattern = re.compile(r"^[0-9a-fA-F]{6}$") + search_result = pattern.search(color) + if search_result is None: + self._module.fail_json(msg="{0} is invalid value.".format(color)) + return True + + def get_usrgrpid_from_name(self, usrgrp): + usrgrpids = self._zapi.usergroup.get({"filter": {"name": usrgrp}}) + if not usrgrpids or len(usrgrpids) > 1: + self._module.fail_json("User group '%s' cannot be found" % usrgrp) + return usrgrpids[0]["usrgrpid"] + + def get_groupid_from_name(self, hostgroup): + groupid = self._zapi.hostgroup.get({"filter": {"name": hostgroup}}) + if not groupid or len(groupid) > 1: + self._module.fail_json("Host group '%s' cannot be found" % hostgroup) + return groupid[0]["groupid"] + + def update_settings( + self, + current_settings, + default_lang, + default_timezone, + default_theme, + search_limit, + max_overview_table_size, + max_in_table, + server_check_interval, + work_period, + show_technical_errors, + history_period, + period_default, + max_period, + severity_color_0, + severity_color_1, + severity_color_2, + severity_color_3, + severity_color_4, + severity_color_5, + severity_name_0, + severity_name_1, + severity_name_2, + severity_name_3, + severity_name_4, + severity_name_5, + custom_color, + ok_period, + blink_period, + problem_unack_color, + problem_ack_color, + ok_unack_color, + ok_ack_color, + problem_unack_style, + problem_ack_style, + ok_unack_style, + ok_ack_style, + frontend_url, + discovery_group, + default_inventory_mode, + alert_usrgrp, + snmptrap_logging, + login_attempts, + login_block, + validate_uri_schemes, + uri_valid_schemes, + x_frame_options, + iframe_sandboxing_enabled, + iframe_sandboxing_exceptions, + connect_timeout, + socket_timeout, + media_type_test_timeout, + item_test_timeout, + script_timeout, + report_test_timeout, + auditlog_enabled, + geomaps_tile_provider, + geomaps_tile_url, + geomaps_max_zoom, + geomaps_attribution, + vault_provider, + ): + try: + params = {} + + if isinstance(default_lang, str): + if default_lang != current_settings["default_lang"]: + params["default_lang"] = default_lang + + if isinstance(default_timezone, str): + if default_timezone != current_settings["default_timezone"]: + params["default_timezone"] = default_timezone + + if isinstance(default_theme, str): + if default_theme != current_settings["default_theme"]: + params["default_theme"] = default_theme + + if isinstance(search_limit, int): + if str(search_limit) != current_settings["search_limit"]: + params["search_limit"] = str(search_limit) + + if isinstance(max_overview_table_size, int): + if ( + str(max_overview_table_size) + != current_settings["max_overview_table_size"] + ): + params["max_overview_table_size"] = str(max_overview_table_size) + + if isinstance(max_in_table, int): + if str(max_in_table) != current_settings["max_in_table"]: + params["max_in_table"] = str(max_in_table) + + if isinstance(server_check_interval, bool): + if server_check_interval: + if current_settings["server_check_interval"] != "10": + params["server_check_interval"] = "10" + else: + if current_settings["server_check_interval"] != "0": + params["server_check_interval"] = "0" + + if isinstance(work_period, str): + if work_period != current_settings["work_period"]: + params["work_period"] = work_period + + if isinstance(show_technical_errors, bool): + if show_technical_errors: + if current_settings["show_technical_errors"] != "1": + params["show_technical_errors"] = "1" + else: + if current_settings["show_technical_errors"] != "0": + params["show_technical_errors"] = "0" + + if isinstance(history_period, str): + if self._is_time(history_period): + if history_period != current_settings["history_period"]: + params["history_period"] = history_period + + if isinstance(period_default, str): + if self._is_time(period_default): + if period_default != current_settings["period_default"]: + params["period_default"] = period_default + + if isinstance(max_period, str): + if self._is_time(max_period): + if max_period != current_settings["max_period"]: + params["max_period"] = max_period + + if isinstance(severity_color_0, str): + if self._is_color(severity_color_0): + if severity_color_0 != current_settings["severity_color_0"]: + params["severity_color_0"] = severity_color_0 + + if isinstance(severity_color_1, str): + if self._is_color(severity_color_1): + if severity_color_1 != current_settings["severity_color_1"]: + params["severity_color_1"] = severity_color_1 + + if isinstance(severity_color_2, str): + if self._is_color(severity_color_2): + if severity_color_2 != current_settings["severity_color_2"]: + params["severity_color_2"] = severity_color_2 + + if isinstance(severity_color_3, str): + if self._is_color(severity_color_3): + if severity_color_3 != current_settings["severity_color_3"]: + params["severity_color_3"] = severity_color_3 + + if isinstance(severity_color_4, str): + if self._is_color(severity_color_4): + if severity_color_4 != current_settings["severity_color_4"]: + params["severity_color_4"] = severity_color_4 + + if isinstance(severity_color_5, str): + if self._is_color(severity_color_5): + if severity_color_5 != current_settings["severity_color_5"]: + params["severity_color_5"] = severity_color_5 + + if isinstance(severity_name_0, str): + if severity_name_0 != current_settings["severity_name_0"]: + params["severity_name_0"] = severity_name_0 + + if isinstance(severity_name_1, str): + if severity_name_1 != current_settings["severity_name_1"]: + params["severity_name_1"] = severity_name_1 + + if isinstance(severity_name_2, str): + if severity_name_2 != current_settings["severity_name_2"]: + params["severity_name_2"] = severity_name_2 + + if isinstance(severity_name_3, str): + if severity_name_3 != current_settings["severity_name_3"]: + params["severity_name_3"] = severity_name_3 + + if isinstance(severity_name_4, str): + if severity_name_4 != current_settings["severity_name_4"]: + params["severity_name_4"] = severity_name_4 + + if isinstance(severity_name_5, str): + if severity_name_5 != current_settings["severity_name_5"]: + params["severity_name_5"] = severity_name_5 + + if isinstance(custom_color, bool): + if custom_color: + if current_settings["custom_color"] != "1": + params["custom_color"] = "1" + else: + if current_settings["custom_color"] != "0": + params["custom_color"] = "0" + + if isinstance(ok_period, str): + if self._is_time(ok_period): + if ok_period != current_settings["ok_period"]: + params["ok_period"] = ok_period + + if isinstance(blink_period, str): + if self._is_time(blink_period): + if blink_period != current_settings["blink_period"]: + params["blink_period"] = blink_period + + if isinstance(problem_unack_color, str): + if self._is_color(problem_unack_color): + if problem_unack_color != current_settings["problem_unack_color"]: + params["problem_unack_color"] = problem_unack_color + + if isinstance(problem_ack_color, str): + if self._is_color(problem_ack_color): + if problem_ack_color != current_settings["problem_ack_color"]: + params["problem_ack_color"] = problem_ack_color + + if isinstance(ok_unack_color, str): + if self._is_color(ok_unack_color): + if ok_unack_color != current_settings["ok_unack_color"]: + params["ok_unack_color"] = ok_unack_color + + if isinstance(ok_ack_color, str): + if self._is_color(ok_ack_color): + if ok_ack_color != current_settings["ok_ack_color"]: + params["ok_ack_color"] = ok_ack_color + + if isinstance(problem_unack_style, bool): + if problem_unack_style: + if current_settings["problem_unack_style"] != "1": + params["problem_unack_style"] = "1" + else: + if current_settings["problem_unack_style"] != "0": + params["problem_unack_style"] = "0" + + if isinstance(problem_ack_style, bool): + if problem_ack_style: + if current_settings["problem_ack_style"] != "1": + params["problem_ack_style"] = "1" + else: + if current_settings["problem_ack_style"] != "0": + params["problem_ack_style"] = "0" + + if isinstance(ok_unack_style, bool): + if ok_unack_style: + if current_settings["ok_unack_style"] != "1": + params["ok_unack_style"] = "1" + else: + if current_settings["ok_unack_style"] != "0": + params["ok_unack_style"] = "0" + + if isinstance(ok_ack_style, bool): + if ok_ack_style: + if current_settings["ok_ack_style"] != "1": + params["ok_ack_style"] = "1" + else: + if current_settings["ok_ack_style"] != "0": + params["ok_ack_style"] = "0" + + if isinstance(frontend_url, str): + if frontend_url != current_settings["url"]: + params["url"] = frontend_url + + if isinstance(discovery_group, str): + discovery_groupid = self.get_groupid_from_name(discovery_group) + if current_settings["discovery_groupid"] != discovery_groupid: + params["discovery_groupid"] = discovery_groupid + + if isinstance(default_inventory_mode, str): + _default_inventory_mode = str( + zabbix_utils.helper_to_numeric_value( + ["disabled", "manual", "automatic"], default_inventory_mode + ) + - 1 + ) + if ( + _default_inventory_mode + != current_settings["default_inventory_mode"] + ): + params["default_inventory_mode"] = _default_inventory_mode + + if isinstance(alert_usrgrp, str): + if alert_usrgrp != "0": + alert_usrgrpid = self.get_usrgrpid_from_name(alert_usrgrp) + else: + alert_usrgrpid = alert_usrgrp + if current_settings["alert_usrgrpid"] != alert_usrgrpid: + params["alert_usrgrpid"] = alert_usrgrpid + + if isinstance(snmptrap_logging, bool): + if snmptrap_logging: + if current_settings["snmptrap_logging"] != "1": + params["snmptrap_logging"] = "1" + else: + if current_settings["snmptrap_logging"] != "0": + params["snmptrap_logging"] = "0" + + if isinstance(login_attempts, int): + if str(login_attempts) != current_settings["login_attempts"]: + params["login_attempts"] = str(login_attempts) + + if isinstance(login_block, str): + if self._is_time(login_block): + if login_block != current_settings["login_block"]: + params["login_block"] = login_block + + if isinstance(validate_uri_schemes, bool): + if validate_uri_schemes: + if current_settings["validate_uri_schemes"] != "1": + params["validate_uri_schemes"] = "1" + else: + if current_settings["validate_uri_schemes"] != "0": + params["validate_uri_schemes"] = "0" + + if isinstance(uri_valid_schemes, list): + current_uri_valid_schemes = current_settings["uri_valid_schemes"].split( + "," + ) + uri_valid_schemes.sort() + current_uri_valid_schemes.sort() + compare_result = [] + zabbix_utils.helper_compare_lists( + uri_valid_schemes, current_uri_valid_schemes, compare_result + ) + if len(compare_result) != 0: + params["uri_valid_schemes"] = ",".join(uri_valid_schemes) + + if isinstance(x_frame_options, str): + if x_frame_options != current_settings["x_frame_options"]: + params["x_frame_options"] = x_frame_options + + if isinstance(iframe_sandboxing_enabled, bool): + if iframe_sandboxing_enabled: + if current_settings["iframe_sandboxing_enabled"] != "1": + params["iframe_sandboxing_enabled"] = "1" + else: + if current_settings["iframe_sandboxing_enabled"] != "0": + params["iframe_sandboxing_enabled"] = "0" + + if isinstance(iframe_sandboxing_exceptions, str): + if ( + iframe_sandboxing_exceptions + != current_settings["iframe_sandboxing_exceptions"] + ): + params[ + "iframe_sandboxing_exceptions" + ] = iframe_sandboxing_exceptions + + if isinstance(connect_timeout, str): + if self._is_time(connect_timeout): + if connect_timeout != current_settings["connect_timeout"]: + params["connect_timeout"] = connect_timeout + + if isinstance(socket_timeout, str): + if self._is_time(socket_timeout): + if socket_timeout != current_settings["socket_timeout"]: + params["socket_timeout"] = socket_timeout + + if isinstance(media_type_test_timeout, str): + if self._is_time(media_type_test_timeout): + if ( + media_type_test_timeout + != current_settings["media_type_test_timeout"] + ): + params["media_type_test_timeout"] = media_type_test_timeout + + if isinstance(item_test_timeout, str): + if self._is_time(item_test_timeout): + if item_test_timeout != current_settings["item_test_timeout"]: + params["item_test_timeout"] = item_test_timeout + + if isinstance(script_timeout, str): + if self._is_time(script_timeout): + if script_timeout != current_settings["script_timeout"]: + params["script_timeout"] = script_timeout + + if isinstance(report_test_timeout, str): + if self._is_time(report_test_timeout): + if report_test_timeout != current_settings["report_test_timeout"]: + params["report_test_timeout"] = report_test_timeout + + if isinstance(auditlog_enabled, bool): + if auditlog_enabled: + if current_settings["auditlog_enabled"] != "1": + params["auditlog_enabled"] = "1" + else: + if current_settings["auditlog_enabled"] != "0": + params["auditlog_enabled"] = "0" + + if isinstance(geomaps_tile_provider, str): + _geomaps_tile_provider = geomaps_tile_provider + if geomaps_tile_provider == "another": + _geomaps_tile_provider = "" + if _geomaps_tile_provider != current_settings["geomaps_tile_provider"]: + params["geomaps_tile_provider"] = _geomaps_tile_provider + + if isinstance(geomaps_tile_url, str): + if geomaps_tile_url != current_settings["geomaps_tile_url"]: + params["geomaps_tile_url"] = geomaps_tile_url + + if isinstance(geomaps_max_zoom, int): + if str(geomaps_max_zoom) != current_settings["geomaps_max_zoom"]: + params["geomaps_max_zoom"] = str(geomaps_max_zoom) + + if isinstance(geomaps_attribution, str): + if geomaps_attribution != current_settings["geomaps_attribution"]: + params["geomaps_attribution"] = geomaps_attribution + + if LooseVersion("6.2") <= LooseVersion(self._zbx_api_version): + if isinstance(vault_provider, str): + _vault_provider = str( + zabbix_utils.helper_to_numeric_value( + ["HashiCorp_Vault", "CyberArk_Vault"], vault_provider + ) + ) + if _vault_provider != current_settings["vault_provider"]: + params["vault_provider"] = _vault_provider + + if params != {}: + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.settings.update(params) + self._module.exit_json( + changed=True, result="Successfully updated global settings" + ) + else: + if self._module.check_mode: + self._module.exit_json(changed=False) + self._module.exit_json( + changed=False, result="Settings are already up to date" + ) + except Exception as e: + self._module.fail_json(msg="Failed to update global settings: %s" % e) + + +def main(): + argument_spec = zabbix_utils.zabbix_common_argument_spec() + argument_spec.update( + dict( + default_lang=dict(type="str"), + default_timezone=dict(type="str"), + default_theme=dict( + type="str", choices=["blue-theme", "dark-theme", "hc-light", "hc-dark"] + ), + search_limit=dict(type="int"), + max_overview_table_size=dict(type="int"), + max_in_table=dict(type="int"), + server_check_interval=dict(type="bool"), + work_period=dict(type="str"), + show_technical_errors=dict(type="bool"), + history_period=dict(type="str"), + period_default=dict(type="str"), + max_period=dict(type="str"), + severity_color_0=dict(type="str"), + severity_color_1=dict(type="str"), + severity_color_2=dict(type="str"), + severity_color_3=dict(type="str"), + severity_color_4=dict(type="str"), + severity_color_5=dict(type="str"), + severity_name_0=dict(type="str"), + severity_name_1=dict(type="str"), + severity_name_2=dict(type="str"), + severity_name_3=dict(type="str"), + severity_name_4=dict(type="str"), + severity_name_5=dict(type="str"), + custom_color=dict(type="bool"), + ok_period=dict(type="str"), + blink_period=dict(type="str"), + problem_unack_color=dict(type="str"), + problem_ack_color=dict(type="str"), + ok_unack_color=dict(type="str"), + ok_ack_color=dict(type="str"), + problem_unack_style=dict(type="bool"), + problem_ack_style=dict(type="bool"), + ok_unack_style=dict(type="bool"), + ok_ack_style=dict(type="bool"), + frontend_url=dict(type="str"), + discovery_group=dict(type="str"), + default_inventory_mode=dict( + type="str", choices=["disabled", "manual", "automatic"] + ), + alert_usrgrp=dict(type="str"), + snmptrap_logging=dict(type="bool"), + login_attempts=dict(type="int"), + login_block=dict(type="str"), + validate_uri_schemes=dict(type="bool"), + uri_valid_schemes=dict(type="list", elements="str"), + x_frame_options=dict(type="str"), + iframe_sandboxing_enabled=dict(type="bool"), + iframe_sandboxing_exceptions=dict(type="str"), + connect_timeout=dict(type="str"), + socket_timeout=dict(type="str"), + media_type_test_timeout=dict(type="str"), + item_test_timeout=dict(type="str"), + script_timeout=dict(type="str"), + report_test_timeout=dict(type="str"), + auditlog_enabled=dict(type="bool"), + geomaps_tile_provider=dict( + type="str", + choices=[ + "OpenStreetMap.Mapnik", + "OpenTopoMap", + "Stamen.TonerLite", + "Stamen.Terrain", + "USGS.USTopo", + "USGS.USImagery", + "another", + ], + ), + geomaps_tile_url=dict(type="str"), + geomaps_max_zoom=dict(type="str"), + geomaps_attribution=dict(type="str"), + vault_provider=dict( + type="str", choices=["HashiCorp_Vault", "CyberArk_Vault"] + ), + ) + ) + module = AnsibleModule( + argument_spec=argument_spec, + required_if=[ + [ + "geomaps_tile_provider", + "another", + ["geomaps_tile_url", "geomaps_max_zoom", "geomaps_attribution"], + ], + ], + supports_check_mode=True, + ) + + default_lang = module.params["default_lang"] + default_timezone = module.params["default_timezone"] + default_theme = module.params["default_theme"] + search_limit = module.params["search_limit"] + max_overview_table_size = module.params["max_overview_table_size"] + max_in_table = module.params["max_in_table"] + server_check_interval = module.params["server_check_interval"] + work_period = module.params["work_period"] + show_technical_errors = module.params["show_technical_errors"] + history_period = module.params["history_period"] + period_default = module.params["period_default"] + max_period = module.params["max_period"] + severity_color_0 = module.params["severity_color_0"] + severity_color_1 = module.params["severity_color_1"] + severity_color_2 = module.params["severity_color_2"] + severity_color_3 = module.params["severity_color_3"] + severity_color_4 = module.params["severity_color_4"] + severity_color_5 = module.params["severity_color_5"] + severity_name_0 = module.params["severity_name_0"] + severity_name_1 = module.params["severity_name_1"] + severity_name_2 = module.params["severity_name_2"] + severity_name_3 = module.params["severity_name_3"] + severity_name_4 = module.params["severity_name_4"] + severity_name_5 = module.params["severity_name_5"] + custom_color = module.params["custom_color"] + ok_period = module.params["ok_period"] + blink_period = module.params["blink_period"] + problem_unack_color = module.params["problem_unack_color"] + problem_ack_color = module.params["problem_ack_color"] + ok_unack_color = module.params["ok_unack_color"] + ok_ack_color = module.params["ok_ack_color"] + problem_unack_style = module.params["problem_unack_style"] + problem_ack_style = module.params["problem_ack_style"] + ok_unack_style = module.params["ok_unack_style"] + ok_ack_style = module.params["ok_ack_style"] + frontend_url = module.params["frontend_url"] + discovery_group = module.params["discovery_group"] + default_inventory_mode = module.params["default_inventory_mode"] + alert_usrgrp = module.params["alert_usrgrp"] + snmptrap_logging = module.params["snmptrap_logging"] + login_attempts = module.params["login_attempts"] + login_block = module.params["login_block"] + validate_uri_schemes = module.params["validate_uri_schemes"] + uri_valid_schemes = module.params["uri_valid_schemes"] + x_frame_options = module.params["x_frame_options"] + iframe_sandboxing_enabled = module.params["iframe_sandboxing_enabled"] + iframe_sandboxing_exceptions = module.params["iframe_sandboxing_exceptions"] + connect_timeout = module.params["connect_timeout"] + socket_timeout = module.params["socket_timeout"] + media_type_test_timeout = module.params["media_type_test_timeout"] + item_test_timeout = module.params["item_test_timeout"] + script_timeout = module.params["script_timeout"] + report_test_timeout = module.params["report_test_timeout"] + auditlog_enabled = module.params["auditlog_enabled"] + geomaps_tile_provider = module.params["geomaps_tile_provider"] + geomaps_tile_url = module.params["geomaps_tile_url"] + geomaps_max_zoom = module.params["geomaps_max_zoom"] + geomaps_attribution = module.params["geomaps_attribution"] + vault_provider = module.params["vault_provider"] + + settings = Settings(module) + + current_settings = settings.get_settings() + settings.update_settings( + current_settings, + default_lang, + default_timezone, + default_theme, + search_limit, + max_overview_table_size, + max_in_table, + server_check_interval, + work_period, + show_technical_errors, + history_period, + period_default, + max_period, + severity_color_0, + severity_color_1, + severity_color_2, + severity_color_3, + severity_color_4, + severity_color_5, + severity_name_0, + severity_name_1, + severity_name_2, + severity_name_3, + severity_name_4, + severity_name_5, + custom_color, + ok_period, + blink_period, + problem_unack_color, + problem_ack_color, + ok_unack_color, + ok_ack_color, + problem_unack_style, + problem_ack_style, + ok_unack_style, + ok_ack_style, + frontend_url, + discovery_group, + default_inventory_mode, + alert_usrgrp, + snmptrap_logging, + login_attempts, + login_block, + validate_uri_schemes, + uri_valid_schemes, + x_frame_options, + iframe_sandboxing_enabled, + iframe_sandboxing_exceptions, + connect_timeout, + socket_timeout, + media_type_test_timeout, + item_test_timeout, + script_timeout, + report_test_timeout, + auditlog_enabled, + geomaps_tile_provider, + geomaps_tile_url, + geomaps_max_zoom, + geomaps_attribution, + vault_provider, + ) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_template.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_template.py index 7c4c098af..a773790aa 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_template.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_template.py @@ -8,19 +8,19 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_template -short_description: Create/update/delete/dump Zabbix template +short_description: Create/update/delete Zabbix template description: - - This module allows you to create, modify, delete and dump Zabbix templates. + - This module allows you to create, modify and delete Zabbix templates. - Multiple templates can be created or modified at once if passing JSON or XML to module. author: - "sookido (@sookido)" - "Logan Vig (@logan2211)" - "Dusan Matejka (@D3DeFi)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: template_name: description: @@ -93,7 +93,6 @@ options: tags: description: - List of tags to assign to the template. - - Works only with >= Zabbix 4.2. - Providing I(tags=[]) with I(force=yes) will clean all of the tags from the template. required: false type: list @@ -108,54 +107,34 @@ options: description: - Value of the template tag. type: str - default: '' - dump_format: - description: - - Format to use when dumping template with C(state=dump). - - This option is deprecated and will eventually be removed in 2.14. - required: false - choices: [json, xml] - default: "json" - type: str - omit_date: - description: - - Removes the date field for the exported/dumped template - - Requires C(state=dump) - required: false - type: bool - default: false + default: "" state: description: - Required state of the template. - On C(state=present) template will be created/imported or updated depending if it is already present. - - On C(state=dump) template content will get dumped into required format specified in I(dump_format). - On C(state=absent) template will be deleted. - - The C(state=dump) is deprecated and will be removed in 2.14. The M(community.zabbix.zabbix_template_info) module should be used instead. required: false - choices: [present, absent, dump] + choices: [present, absent] default: "present" type: str extends_documentation_fragment: - community.zabbix.zabbix +""" -notes: -- there where breaking changes in the Zabbix API with version 5.4 onwards (especially UUIDs) which may - require you to export the templates again (see version tag >= 5.4 in the resulting file/data). -''' -EXAMPLES = r''' +EXAMPLES = r""" --- # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create a new Zabbix template linked to groups, macros and templates @@ -166,7 +145,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_name: ExampleHost @@ -177,12 +156,12 @@ EXAMPLES = r''' - Example template1 - Example template2 macros: - - macro: '{$EXAMPLE_MACRO1}' + - macro: "{$EXAMPLE_MACRO1}" value: 30000 - - macro: '{$EXAMPLE_MACRO2}' + - macro: "{$EXAMPLE_MACRO2}" value: 3 - - macro: '{$EXAMPLE_MACRO3}' - value: 'Example' + - macro: "{$EXAMPLE_MACRO3}" + value: "Example" state: present - name: Unlink and clear templates from the existing Zabbix template @@ -193,7 +172,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_name: ExampleHost @@ -210,7 +189,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_json: "{{ lookup('file', 'zabbix_apache2.json') }}" @@ -224,7 +203,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_xml: "{{ lookup('file', 'zabbix_apache2.xml') }}" @@ -238,20 +217,18 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_json: zabbix_export: - version: '3.2' + version: "3.2" templates: - name: Template for Testing - description: 'Testing template import' + description: "Testing template import" template: Test Template groups: - name: Templates - applications: - - name: Test Application state: present - name: Configure macros on the existing Zabbix template @@ -262,13 +239,13 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_name: Template macros: - - macro: '{$TEST_MACRO}' - value: 'Example' + - macro: "{$TEST_MACRO}" + value: "Example" state: present - name: Add tags to the existing Zabbix template @@ -279,7 +256,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_name: Template @@ -296,110 +273,16 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template: template_name: Template state: absent +""" -- name: Dump Zabbix template as JSON - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_template: - template_name: Template - omit_date: yes - state: dump - register: template_dump - -- name: Dump Zabbix template as XML - # set task level variables as we change ansible_connection plugin here - vars: - ansible_network_os: community.zabbix.zabbix - ansible_connection: httpapi - ansible_httpapi_port: 443 - ansible_httpapi_use_ssl: true - ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu - ansible_host: zabbix-example-fqdn.org - community.zabbix.zabbix_template: - template_name: Template - dump_format: xml - omit_date: false - state: dump - register: template_dump -''' - -RETURN = r''' +RETURN = r""" --- -template_json: - description: The JSON dump of the template - returned: when state is dump and omit_date is no - type: str - sample: { - "zabbix_export":{ - "date":"2017-11-29T16:37:24Z", - "templates":[{ - "templates":[], - "description":"", - "httptests":[], - "screens":[], - "applications":[], - "discovery_rules":[], - "groups":[{"name":"Templates"}], - "name":"Test Template", - "items":[], - "macros":[], - "template":"test" - }], - "version":"3.2", - "groups":[{ - "name":"Templates" - }] - } - } - -template_xml: - description: dump of the template in XML representation - returned: when state is dump, dump_format is xml and omit_date is yes - type: str - sample: |- - <?xml version="1.0" ?> - <zabbix_export> - <version>4.2</version> - <groups> - <group> - <name>Templates</name> - </group> - </groups> - <templates> - <template> - <template>test</template> - <name>Test Template</name> - <description/> - <groups> - <group> - <name>Templates</name> - </group> - </groups> - <applications/> - <items/> - <discovery_rules/> - <httptests/> - <macros/> - <templates/> - <screens/> - <tags/> - </template> - </templates> - </zabbix_export> -''' +""" import json @@ -422,12 +305,12 @@ class Template(ZabbixBase): def get_group_ids_by_group_names(self, group_names): group_ids = [] for group_name in group_names: - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.2'): - group = self._zapi.templategroup.get({'output': ['groupid'], 'filter': {'name': group_name}}) + if LooseVersion(self._zbx_api_version) >= LooseVersion("6.2"): + group = self._zapi.templategroup.get({"output": ["groupid"], "filter": {"name": group_name}}) else: - group = self._zapi.hostgroup.get({'output': ['groupid'], 'filter': {'name': group_name}}) + group = self._zapi.hostgroup.get({"output": ["groupid"], "filter": {"name": group_name}}) if group: - group_ids.append({'groupid': group[0]['groupid']}) + group_ids.append({"groupid": group[0]["groupid"]}) else: self._module.fail_json(msg="Template group not found: %s" % group_name) return group_ids @@ -437,25 +320,25 @@ class Template(ZabbixBase): if template_list is None or len(template_list) == 0: return template_ids for template in template_list: - template_list = self._zapi.template.get({'output': 'extend', 'filter': {'host': template}}) + template_list = self._zapi.template.get({"output": "extend", "filter": {"host": template}}) if len(template_list) < 1: continue else: - template_id = template_list[0]['templateid'] - template_ids.append({'templateid': template_id}) + template_id = template_list[0]["templateid"] + template_ids.append({"templateid": template_id}) return template_ids def add_template(self, template_name, group_ids, link_template_ids, macros, tags): if self._module.check_mode: self._module.exit_json(changed=True) - new_template = {'host': template_name, 'groups': group_ids, 'templates': link_template_ids, 'macros': macros, 'tags': tags} + new_template = {"host": template_name, "groups": group_ids, "templates": link_template_ids, "macros": macros, "tags": tags} if macros is None: - new_template.update({'macros': []}) + new_template.update({"macros": []}) if tags is None: - new_template.update({'tags': []}) + new_template.update({"tags": []}) if link_template_ids is None: - new_template.update({'templates': []}) + new_template.update({"templates": []}) self._zapi.template.create(new_template) @@ -470,17 +353,17 @@ class Template(ZabbixBase): changed = False # Compare filtered and formatted XMLs strings for any changes. It is expected that provided # XML has same structure as Zabbix uses (e.g. it was optimally exported via Zabbix GUI or API) - if template_content is not None and template_type == 'xml': - existing_template = self.dump_template(template_ids, template_type='xml') + if template_content is not None and template_type == "xml": + existing_template = self.dump_template(template_ids, template_type="xml") if self.filter_xml_template(template_content) != self.filter_xml_template(existing_template): changed = True return changed - existing_template = self.dump_template(template_ids, template_type='json') + existing_template = self.dump_template(template_ids, template_type="json") # Compare JSON objects as deep sorted python dictionaries - if template_content is not None and template_type == 'json': + if template_content is not None and template_type == "json": parsed_template_json = self.load_json_template(template_content) if self.diff_template(parsed_template_json, existing_template): changed = True @@ -489,19 +372,19 @@ class Template(ZabbixBase): # If neither template_json or template_xml were used, user provided all parameters via module options if template_groups is not None: - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.2'): - existing_groups = [g['name'] for g in existing_template['zabbix_export']['template_groups']] + if LooseVersion(self._zbx_api_version) >= LooseVersion("6.2"): + existing_groups = [g["name"] for g in existing_template["zabbix_export"]["template_groups"]] else: - existing_groups = [g['name'] for g in existing_template['zabbix_export']['groups']] + existing_groups = [g["name"] for g in existing_template["zabbix_export"]["groups"]] if set(template_groups) != set(existing_groups): changed = True - if 'templates' not in existing_template['zabbix_export']['templates'][0]: - existing_template['zabbix_export']['templates'][0]['templates'] = [] + if "templates" not in existing_template["zabbix_export"]["templates"][0]: + existing_template["zabbix_export"]["templates"][0]["templates"] = [] # Check if any new templates would be linked or any existing would be unlinked - exist_child_templates = [t['name'] for t in existing_template['zabbix_export']['templates'][0]['templates']] + exist_child_templates = [t["name"] for t in existing_template["zabbix_export"]["templates"][0]["templates"]] if link_templates is not None: if set(link_templates) != set(exist_child_templates): changed = True @@ -516,46 +399,45 @@ class Template(ZabbixBase): changed = True break - if 'macros' not in existing_template['zabbix_export']['templates'][0]: - existing_template['zabbix_export']['templates'][0]['macros'] = [] + if "macros" not in existing_template["zabbix_export"]["templates"][0]: + existing_template["zabbix_export"]["templates"][0]["macros"] = [] if template_macros is not None: - existing_macros = existing_template['zabbix_export']['templates'][0]['macros'] + existing_macros = existing_template["zabbix_export"]["templates"][0]["macros"] if template_macros != existing_macros: changed = True - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.2'): - if 'tags' not in existing_template['zabbix_export']['templates'][0]: - existing_template['zabbix_export']['templates'][0]['tags'] = [] - if template_tags is not None: - existing_tags = existing_template['zabbix_export']['templates'][0]['tags'] - if template_tags != existing_tags: - changed = True + if "tags" not in existing_template["zabbix_export"]["templates"][0]: + existing_template["zabbix_export"]["templates"][0]["tags"] = [] + if template_tags is not None: + existing_tags = existing_template["zabbix_export"]["templates"][0]["tags"] + if template_tags != existing_tags: + changed = True return changed def update_template(self, template_ids, group_ids, link_template_ids, clear_template_ids, template_macros, template_tags): template_changes = {} if group_ids is not None: - template_changes.update({'groups': group_ids}) + template_changes.update({"groups": group_ids}) if link_template_ids is not None: - template_changes.update({'templates': link_template_ids}) + template_changes.update({"templates": link_template_ids}) else: - template_changes.update({'templates': []}) + template_changes.update({"templates": []}) if clear_template_ids is not None: - template_changes.update({'templates_clear': clear_template_ids}) + template_changes.update({"templates_clear": clear_template_ids}) if template_macros is not None: - template_changes.update({'macros': template_macros}) + template_changes.update({"macros": template_macros}) else: - template_changes.update({'macros': []}) + template_changes.update({"macros": []}) if template_tags is not None: - template_changes.update({'tags': template_tags}) + template_changes.update({"tags": template_tags}) else: - template_changes.update({'tags': []}) + template_changes.update({"tags": []}) if template_changes: # If we got here we know that only one template was provided via template_name @@ -566,7 +448,7 @@ class Template(ZabbixBase): if self._module.check_mode: self._module.exit_json(changed=True) - templateids_list = [t.get('templateid') for t in templateids] + templateids_list = [t.get("templateid") for t in templateids] self._zapi.template.delete(templateids_list) def ordered_json(self, obj): @@ -578,26 +460,21 @@ class Template(ZabbixBase): else: return obj - def dump_template(self, template_ids, template_type='json', omit_date=False): - template_ids_list = [t.get('templateid') for t in template_ids] + def dump_template(self, template_ids, template_type="json"): + template_ids_list = [t.get("templateid") for t in template_ids] try: - dump = self._zapi.configuration.export({'format': template_type, 'options': {'templates': template_ids_list}}) - if template_type == 'xml': - xmlroot = ET.fromstring(dump.encode('utf-8')) - # remove date field if requested - if omit_date: - date = xmlroot.find(".date") - if date is not None: - xmlroot.remove(date) + dump = self._zapi.configuration.export({"format": template_type, "options": {"templates": template_ids_list}}) + if template_type == "xml": + xmlroot = ET.fromstring(dump.encode("utf-8")) if PY2: - return str(ET.tostring(xmlroot, encoding='utf-8')) + return str(ET.tostring(xmlroot, encoding="utf-8")) else: - return str(ET.tostring(xmlroot, encoding='utf-8').decode('utf-8')) + return str(ET.tostring(xmlroot, encoding="utf-8").decode("utf-8")) else: - return self.load_json_template(dump, omit_date=omit_date) + return self.load_json_template(dump) except Exception as e: - self._module.fail_json(msg='Unable to export template: %s' % e) + self._module.fail_json(msg="Unable to export template: %s" % e) def diff_template(self, template_json_a, template_json_b): # Compare 2 zabbix templates and return True if they differ. @@ -609,20 +486,18 @@ class Template(ZabbixBase): def filter_template(self, template_json): # Filter the template json to contain only the keys we will update - keep_keys = set(['graphs', 'templates', 'triggers', 'value_maps']) - unwanted_keys = set(template_json['zabbix_export']) - keep_keys + keep_keys = set(["graphs", "templates", "triggers", "value_maps"]) + unwanted_keys = set(template_json["zabbix_export"]) - keep_keys for unwanted_key in unwanted_keys: - del template_json['zabbix_export'][unwanted_key] + del template_json["zabbix_export"][unwanted_key] # Versions older than 2.4 do not support description field within template desc_not_supported = False - if LooseVersion(self._zbx_api_version) < LooseVersion('2.4'): - desc_not_supported = True # Filter empty attributes from template object to allow accurate comparison - for template in template_json['zabbix_export']['templates']: + for template in template_json["zabbix_export"]["templates"]: for key in list(template.keys()): - if not template[key] or (key == 'description' and desc_not_supported): + if not template[key] or (key == "description" and desc_not_supported): template.pop(key) return template_json @@ -634,7 +509,7 @@ class Template(ZabbixBase): It is advised that provided XML template exactly matches XML structure used by Zabbix""" # Strip last new line and convert string to ElementTree parsed_xml_root = self.load_xml_template(template_xml.strip()) - keep_keys = ['graphs', 'templates', 'triggers', 'value_maps'] + keep_keys = ["graphs", "templates", "triggers", "value_maps"] # Remove unwanted XML nodes for node in list(parsed_xml_root): @@ -642,209 +517,174 @@ class Template(ZabbixBase): parsed_xml_root.remove(node) # Filter empty attributes from template objects to allow accurate comparison - for template in list(parsed_xml_root.find('templates')): + for template in list(parsed_xml_root.find("templates")): for element in list(template): if element.text is None and len(list(element)) == 0: template.remove(element) # Filter new lines and indentation - xml_root_text = list(line.strip() for line in ET.tostring(parsed_xml_root, encoding='utf8', method='xml').decode().split('\n')) - return ''.join(xml_root_text) + xml_root_text = list(line.strip() for line in ET.tostring(parsed_xml_root, encoding="utf8", method="xml").decode().split("\n")) + return "".join(xml_root_text) - def load_json_template(self, template_json, omit_date=False): + def load_json_template(self, template_json): try: jsondoc = json.loads(template_json) - if omit_date and 'date' in jsondoc['zabbix_export']: - del jsondoc['zabbix_export']['date'] return jsondoc except ValueError as e: - self._module.fail_json(msg='Invalid JSON provided', details=to_native(e), exception=traceback.format_exc()) + self._module.fail_json(msg="Invalid JSON provided", details=to_native(e), exception=traceback.format_exc()) def load_xml_template(self, template_xml): try: return ET.fromstring(template_xml) except ET.ParseError as e: - self._module.fail_json(msg='Invalid XML provided', details=to_native(e), exception=traceback.format_exc()) + self._module.fail_json(msg="Invalid XML provided", details=to_native(e), exception=traceback.format_exc()) - def import_template(self, template_content, template_type='json'): + def import_template(self, template_content, template_type="json"): if self._module.check_mode: self._module.exit_json(changed=True) # rules schema latest version update_rules = { - 'applications': { - 'createMissing': True, - 'deleteMissing': True + "discoveryRules": { + "createMissing": True, + "updateExisting": True, + "deleteMissing": True }, - 'discoveryRules': { - 'createMissing': True, - 'updateExisting': True, - 'deleteMissing': True + "graphs": { + "createMissing": True, + "updateExisting": True, + "deleteMissing": True }, - 'graphs': { - 'createMissing': True, - 'updateExisting': True, - 'deleteMissing': True + "host_groups": { + "createMissing": True }, - 'host_groups': { - 'createMissing': True + "httptests": { + "createMissing": True, + "updateExisting": True, + "deleteMissing": True }, - 'httptests': { - 'createMissing': True, - 'updateExisting': True, - 'deleteMissing': True + "items": { + "createMissing": True, + "updateExisting": True, + "deleteMissing": True }, - 'items': { - 'createMissing': True, - 'updateExisting': True, - 'deleteMissing': True + "templates": { + "createMissing": True, + "updateExisting": True }, - 'templates': { - 'createMissing': True, - 'updateExisting': True + "template_groups": { + "createMissing": True }, - 'template_groups': { - 'createMissing': True + "templateLinkage": { + "createMissing": True }, - 'templateLinkage': { - 'createMissing': True + "templateScreens": { + "createMissing": True, + "updateExisting": True, + "deleteMissing": True }, - 'templateScreens': { - 'createMissing': True, - 'updateExisting': True, - 'deleteMissing': True + "triggers": { + "createMissing": True, + "updateExisting": True, + "deleteMissing": True }, - 'triggers': { - 'createMissing': True, - 'updateExisting': True, - 'deleteMissing': True - }, - 'valueMaps': { - 'createMissing': True, - 'updateExisting': True + "valueMaps": { + "createMissing": True, + "updateExisting": True } } try: - # updateExisting for application removed from zabbix api after 3.2 - if LooseVersion(self._zbx_api_version) <= LooseVersion('3.2'): - update_rules['applications']['updateExisting'] = True - - # templateLinkage.deleteMissing only available in 4.0 branch higher .16 and higher 4.4.4 - # it's not available in 4.2 branches or lower 4.0.16 - if LooseVersion(self._zbx_api_version).version[:2] == LooseVersion('4.0').version and \ - LooseVersion(self._zbx_api_version).version[:3] >= LooseVersion('4.0.16').version: - update_rules['templateLinkage']['deleteMissing'] = True - if LooseVersion(self._zbx_api_version) >= LooseVersion('4.4.4'): - update_rules['templateLinkage']['deleteMissing'] = True - - # templateScreens is named templateDashboards in zabbix >= 5.2 - # https://support.zabbix.com/browse/ZBX-18677 - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.2'): - update_rules["templateDashboards"] = update_rules.pop("templateScreens") - - # Zabbix 5.4 no longer supports applications - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.4'): - update_rules.pop('applications', None) + update_rules["templateLinkage"]["deleteMissing"] = True + update_rules["templateDashboards"] = update_rules.pop("templateScreens") # before Zabbix 6.2 host_groups and template_group are joined into groups parameter - if LooseVersion(self._zbx_api_version) < LooseVersion('6.2'): - update_rules['groups'] = {'createMissing': True} - update_rules.pop('host_groups', None) - update_rules.pop('template_groups', None) + if LooseVersion(self._zbx_api_version) < LooseVersion("6.2"): + update_rules["groups"] = {"createMissing": True} + update_rules.pop("host_groups", None) + update_rules.pop("template_groups", None) # The loaded unicode slash of multibyte as a string is escaped when parsing JSON by json.loads in Python2. # So, it is imported in the unicode string into Zabbix. # The following processing is removing the unnecessary slash in escaped for decoding correctly to the multibyte string. # https://github.com/ansible-collections/community.zabbix/issues/314 if PY2: - template_content = re.sub(r'\\\\u([0-9a-z]{,4})', r'\\u\1', template_content) + template_content = re.sub(r"\\\\u([0-9a-z]{,4})", r"\\u\1", template_content) - import_data = {'format': template_type, 'source': template_content, 'rules': update_rules} + import_data = {"format": template_type, "source": template_content, "rules": update_rules} self._zapi.configuration.import_(import_data) except Exception as e: - self._module.fail_json(msg='Unable to import template', details=to_native(e), + self._module.fail_json(msg="Unable to import template", details=to_native(e), exception=traceback.format_exc()) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - template_name=dict(type='str', required=False), - template_json=dict(type='json', required=False), - template_xml=dict(type='str', required=False), - template_groups=dict(type='list', required=False), - link_templates=dict(type='list', required=False), - clear_templates=dict(type='list', required=False), + template_name=dict(type="str", required=False), + template_json=dict(type="json", required=False), + template_xml=dict(type="str", required=False), + template_groups=dict(type="list", required=False, elements="str"), + link_templates=dict(type="list", required=False, elements="str"), + clear_templates=dict(type="list", required=False, elements="str"), macros=dict( - type='list', - elements='dict', + type="list", + elements="dict", options=dict( - macro=dict(type='str', required=True), - value=dict(type='str', required=True) + macro=dict(type="str", required=True), + value=dict(type="str", required=True) ) ), tags=dict( - type='list', - elements='dict', + type="list", + elements="dict", options=dict( - tag=dict(type='str', required=True), - value=dict(type='str', default='') + tag=dict(type="str", required=True), + value=dict(type="str", default="") ) ), - omit_date=dict(type='bool', required=False, default=False), - dump_format=dict(type='str', required=False, default='json', choices=['json', 'xml']), - state=dict(type='str', default="present", choices=['present', 'absent', 'dump']), + state=dict(type="str", default="present", choices=["present", "absent"]), )) module = AnsibleModule( argument_spec=argument_spec, required_one_of=[ - ['template_name', 'template_json', 'template_xml'] + ["template_name", "template_json", "template_xml"] ], mutually_exclusive=[ - ['template_name', 'template_json', 'template_xml'] + ["template_name", "template_json", "template_xml"] ], required_if=[ - ['state', 'absent', ['template_name']], - ['state', 'dump', ['template_name']] + ["state", "absent", ["template_name"]] ], supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - template_name = module.params['template_name'] - template_json = module.params['template_json'] - template_xml = module.params['template_xml'] - template_groups = module.params['template_groups'] - link_templates = module.params['link_templates'] - clear_templates = module.params['clear_templates'] - template_macros = module.params['macros'] - template_tags = module.params['tags'] - omit_date = module.params['omit_date'] - dump_format = module.params['dump_format'] - state = module.params['state'] + template_name = module.params["template_name"] + template_json = module.params["template_json"] + template_xml = module.params["template_xml"] + template_groups = module.params["template_groups"] + link_templates = module.params["link_templates"] + clear_templates = module.params["clear_templates"] + template_macros = module.params["macros"] + template_tags = module.params["tags"] + state = module.params["state"] template = Template(module) # Identify template names for IDs retrieval - # Template names are expected to reside in ['zabbix_export']['templates'][*]['template'] for both data types + # Template names are expected to reside in ["zabbix_export"]["templates"][*]["template"] for both data types template_content, template_type = None, None if template_json is not None: - template_type = 'json' + template_type = "json" template_content = template_json json_parsed = template.load_json_template(template_content) - template_names = list(t['template'] for t in json_parsed['zabbix_export']['templates']) + template_names = list(t["template"] for t in json_parsed["zabbix_export"]["templates"]) elif template_xml is not None: - template_type = 'xml' + template_type = "xml" template_content = template_xml xml_parsed = template.load_xml_template(template_content) - template_names = list(t.find('template').text for t in list(xml_parsed.find('templates'))) + template_names = list(t.find("template").text for t in list(xml_parsed.find("templates"))) else: template_names = [template_name] @@ -858,17 +698,6 @@ def main(): template.delete_template(template_ids) module.exit_json(changed=True, result="Successfully deleted template %s" % template_name) - elif state == "dump": - module.deprecate("The 'dump' state has been deprecated and will be removed, use 'zabbix_template_info' module instead.", - collection_name="community.zabbix", version='3.0.0') # was 2.14 - if not template_ids: - module.fail_json(msg='Template not found: %s' % template_name) - - if dump_format == 'json': - module.exit_json(changed=False, template_json=template.dump_template(template_ids, template_type='json', omit_date=omit_date)) - elif dump_format == 'xml': - module.exit_json(changed=False, template_xml=template.dump_template(template_ids, template_type='xml', omit_date=omit_date)) - elif state == "present": # Load all subelements for template that were provided by user group_ids = None @@ -895,14 +724,14 @@ def main(): tagitem[key] = str(tagitem[key]) if not template_ids: - # Assume new templates are being added when no ID's were found + # Assume new templates are being added when no ID"s were found if template_content is not None: template.import_template(template_content, template_type) module.exit_json(changed=True, result="Template import successful") else: if group_ids is None: - module.fail_json(msg='template_groups are required when creating a new Zabbix template') + module.fail_json(msg="template_groups are required when creating a new Zabbix template") template.add_template(template_name, group_ids, link_template_ids, template_macros, template_tags) module.exit_json(changed=True, result="Successfully added template: %s" % template_name) @@ -924,5 +753,5 @@ def main(): module.exit_json(changed=changed, result="Template successfully updated") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_template_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_template_info.py index acd5b5055..140233e1a 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_template_info.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_template_info.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ module: zabbix_template_info short_description: Gather information about Zabbix template author: @@ -16,7 +16,7 @@ author: description: - This module allows you to search for Zabbix template. requirements: - - "python >= 2.6" + - "python >= 3.9" options: template_name: description: @@ -26,8 +26,7 @@ options: format: description: - Format to use when dumping template. - - C(yaml) works only with Zabbix >= 5.2. - choices: ['json', 'xml', 'yaml', 'none'] + choices: ["json", "xml", "yaml", "none"] default: json type: str omit_date: @@ -38,23 +37,19 @@ options: default: false extends_documentation_fragment: - community.zabbix.zabbix +""" -notes: -- there where breaking changes in the Zabbix API with version 5.4 onwards (especially UUIDs) which may - require you to export the templates again (see version tag >= 5.4 in the resulting file/data). -''' - -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Get Zabbix template as JSON @@ -65,7 +60,7 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template_info: template_name: Template @@ -81,7 +76,7 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template_info: template_name: Template @@ -97,7 +92,7 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template_info: template_name: Template @@ -113,15 +108,15 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_template_info: template_name: Template format: none register: template -''' +""" -RETURN = ''' +RETURN = """ --- template_id: description: The ID of the template @@ -133,38 +128,33 @@ template_json: returned: when format is json and omit_date is true type: str sample: { + "changed": false, + "failed": false, + "template_id": "10529", + "template_json": { "zabbix_export": { - "version": "4.0", - "groups": [ - { - "name": "Templates" - } - ], - "templates": [ - { - "template": "Test Template", - "name": "Template for Testing", - "description": "Testing template import", - "groups": [ + "groups": [ { - "name": "Templates" + "name": "Templates", + "uuid": "7df96b18c230490a9a0a9e2307226338" } - ], - "applications": [ + ], + "templates": [ { - "name": "Test Application" + "groups": [ + { + "name": "Templates" + } + ], + "name": "ExampleTemplateForTempleteInfoModule", + "template": "ExampleTemplateForTempleteInfoModule", + "uuid": "615e9b0662bb4399a2503a9aaa743517" } - ], - "items": [], - "discovery_rules": [], - "httptests": [], - "macros": [], - "templates": [], - "screens": [] - } - ] + ], + "version": "6.0" } - } + } + } template_xml: description: The XML of the template @@ -172,34 +162,23 @@ template_xml: type: str sample: >- <zabbix_export> - <version>4.0</version> - <date>2019-10-27T14:49:57Z</date> + <version>6.0</version> <groups> <group> + <uuid>7df96b18c230490a9a0a9e2307226338</uuid> <name>Templates</name> </group> </groups> <templates> <template> - <template>Test Template</template> - <name>Template for Testing</name> - <description>Testing template import</description> + <uuid>9a83162273f74032a1005fdb13943038</uuid> + <template>ExampleTemplateForTempleteInfoModule</template> + <name>ExampleTemplateForTempleteInfoModule</name> <groups> <group> <name>Templates</name> </group> </groups> - <applications> - <application> - <name>Test Application</name> - </application> - </applications> - <items /> - <discovery_rules /> - <httptests /> - <macros /> - <templates /> - <screens /> </template> </templates> </zabbix_export> @@ -210,22 +189,20 @@ template_yaml: type: str sample: >- zabbix_export: - version: '6.0' - date: '2022-07-09T13:25:18Z' + version: "6.0" groups: - uuid: 7df96b18c230490a9a0a9e2307226338 name: Templates - templates: - - - uuid: 88a9ad240f924f669eb7d4eed736320c - template: 'Test Template' - name: 'Template for Testing' - description: 'Testing template import' - groups: + templates: - - name: Templates -''' + uuid: 67b075276bf047d3aeb8f7d5c2121c6a + template: ExampleTemplateForTempleteInfoModule + name: ExampleTemplateForTempleteInfoModule + groups: + - + name: Templatesn +""" import traceback @@ -244,13 +221,13 @@ class TemplateInfo(ZabbixBase): def get_template_id(self, template_name): template_id = [] try: - template_list = self._zapi.template.get({'output': ['templateid'], - 'filter': {'host': template_name}}) + template_list = self._zapi.template.get({"output": ["templateid"], + "filter": {"host": template_name}}) except Exception as e: - self._module.fail_json(msg='Failed to get template: %s' % e) + self._module.fail_json(msg="Failed to get template: %s" % e) if template_list: - template_id.append(template_list[0]['templateid']) + template_id.append(template_list[0]["templateid"]) return template_id @@ -258,92 +235,86 @@ class TemplateInfo(ZabbixBase): try: jsondoc = json.loads(template_json) # remove date field if requested - if omit_date and 'date' in jsondoc['zabbix_export']: - del jsondoc['zabbix_export']['date'] + if omit_date and "date" in jsondoc["zabbix_export"]: + del jsondoc["zabbix_export"]["date"] return jsondoc except ValueError as e: - self._module.fail_json(msg='Invalid JSON provided', details=to_native(e), exception=traceback.format_exc()) + self._module.fail_json(msg="Invalid JSON provided", details=to_native(e), exception=traceback.format_exc()) def load_yaml_template(self, template_yaml, omit_date=False): if omit_date: yaml_lines = template_yaml.splitlines(True) for index, line in enumerate(yaml_lines): - if 'date:' in line: + if "date:" in line: del yaml_lines[index] - return ''.join(yaml_lines) + return "".join(yaml_lines) else: return template_yaml - def dump_template(self, template_id, template_type='json', omit_date=False): + def dump_template(self, template_id, template_type="json", omit_date=False): try: - dump = self._zapi.configuration.export({'format': template_type, 'options': {'templates': template_id}}) - if template_type == 'xml': - xmlroot = ET.fromstring(dump.encode('utf-8')) + dump = self._zapi.configuration.export({"format": template_type, "options": {"templates": template_id}}) + if template_type == "xml": + xmlroot = ET.fromstring(dump.encode("utf-8")) # remove date field if requested if omit_date: date = xmlroot.find(".date") if date is not None: xmlroot.remove(date) if PY2: - return str(ET.tostring(xmlroot, encoding='utf-8')) + return str(ET.tostring(xmlroot, encoding="utf-8")) else: - return str(ET.tostring(xmlroot, encoding='utf-8').decode('utf-8')) - elif template_type == 'yaml': + return str(ET.tostring(xmlroot, encoding="utf-8").decode("utf-8")) + elif template_type == "yaml": return self.load_yaml_template(dump, omit_date) else: return self.load_json_template(dump, omit_date) except Exception as e: - self._module.fail_json(msg='Unable to export template: %s' % e) + self._module.fail_json(msg="Unable to export template: %s" % e) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - template_name=dict(type='str', required=True), - omit_date=dict(type='bool', required=False, default=False), - format=dict(type='str', choices=['json', 'xml', 'yaml', 'none'], default='json') + template_name=dict(type="str", required=True), + omit_date=dict(type="bool", required=False, default=False), + format=dict(type="str", choices=["json", "xml", "yaml", "none"], default="json") )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - template_name = module.params['template_name'] - omit_date = module.params['omit_date'] - format = module.params['format'] + template_name = module.params["template_name"] + omit_date = module.params["omit_date"] + format = module.params["format"] template_info = TemplateInfo(module) template_id = template_info.get_template_id(template_name) if not template_id: - module.fail_json(msg='Template not found: %s' % template_name) + module.fail_json(msg="Template not found: %s" % template_name) - if format == 'json': + if format == "json": module.exit_json( changed=False, template_id=template_id[0], - template_json=template_info.dump_template(template_id, template_type='json', omit_date=omit_date) + template_json=template_info.dump_template(template_id, template_type="json", omit_date=omit_date) ) - elif format == 'xml': + elif format == "xml": module.exit_json( changed=False, template_id=template_id[0], - template_xml=template_info.dump_template(template_id, template_type='xml', omit_date=omit_date) + template_xml=template_info.dump_template(template_id, template_type="xml", omit_date=omit_date) ) - elif format == 'yaml': + elif format == "yaml": module.exit_json( changed=False, template_id=template_id[0], - template_yaml=template_info.dump_template(template_id, template_type='yaml', omit_date=omit_date) + template_yaml=template_info.dump_template(template_id, template_type="yaml", omit_date=omit_date) ) - elif format == 'none': + elif format == "none": module.exit_json(changed=False, template_id=template_id[0]) diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_templategroup.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_templategroup.py new file mode 100644 index 000000000..7ab39d8fc --- /dev/null +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_templategroup.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = r''' +--- +module: zabbix_templategroup +short_description: Create/delete Zabbix template groups +description: + - Create template groups if they do not exist. + - Delete existing template groups if they exist. +author: + - "Cove (@cove)" + - "Tony Minfei Ding (!UNKNOWN)" + - "Harrison Gu (@harrisongu)" +requirements: + - "python >= 2.6" +options: + state: + description: + - Create or delete template group. + required: false + type: str + default: "present" + choices: [ "present", "absent" ] + template_groups: + description: + - List of template groups to create or delete. + required: true + type: list + elements: str + aliases: [ "template_group" ] + +extends_documentation_fragment: +- community.zabbix.zabbix + +notes: + - Too many concurrent updates to the same group may cause Zabbix to return errors, see examples for a workaround if needed. +''' + +EXAMPLES = r''' +# If you want to use Username and Password to be authenticated by Zabbix Server +- name: Set credentials to access Zabbix Server API + ansible.builtin.set_fact: + ansible_user: Admin + ansible_httpapi_pass: zabbix + +# If you want to use API token to be authenticated by Zabbix Server +# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens +- name: Set API token + ansible.builtin.set_fact: + ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 + +# Base create template groups example +- name: Create template groups + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_group: + state: present + template_groups: + - Example group1 + - Example group2 + +# Limit the Zabbix group creations to one template since Zabbix can return an error when doing concurrent updates +- name: Create template groups + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_group: + state: present + template_groups: + - Example group1 + - Example group2 + when: inventory_hostname==groups['group_name'][0] +''' + + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase +import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils + + +class TemplateGroup(ZabbixBase): + # create template group(s) if not exists + def create_template_group(self, group_names): + try: + group_add_list = [] + for group_name in group_names: + result = self._zapi.templategroup.get({'filter': {'name': group_name}}) + if not result: + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.templategroup.create({'name': group_name}) + group_add_list.append(group_name) + return group_add_list + except Exception as e: + self._module.fail_json(msg="Failed to create template group(s): %s" % e) + + # delete template group(s) + def delete_template_group(self, group_ids): + try: + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.templategroup.delete(group_ids) + except Exception as e: + self._module.fail_json(msg="Failed to delete template group(s), Exception: %s" % e) + + # get group ids by name + def get_group_ids(self, template_groups): + group_ids = [] + + group_list = self._zapi.templategroup.get({'output': 'extend', 'filter': {'name': template_groups}}) + for group in group_list: + group_id = group['groupid'] + group_ids.append(group_id) + return group_ids, group_list + + +def main(): + argument_spec = zabbix_utils.zabbix_common_argument_spec() + argument_spec.update(dict( + template_groups=dict(type='list', required=True, aliases=['template_group'], elements='str'), + state=dict(type='str', default="present", choices=['present', 'absent']), + )) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True + ) + + template_groups = module.params['template_groups'] + state = module.params['state'] + + templateGroup = TemplateGroup(module) + + group_ids = [] + group_list = [] + if template_groups: + group_ids, group_list = templateGroup.get_group_ids(template_groups) + + if state == "absent": + # delete template groups + if group_ids: + delete_group_names = [] + templateGroup.delete_template_group(group_ids) + for group in group_list: + delete_group_names.append(group['name']) + module.exit_json(changed=True, + result="Successfully deleted template group(s): %s." % ",".join(delete_group_names)) + else: + module.exit_json(changed=False, result="No template group(s) to delete.") + else: + # create template groups + group_add_list = templateGroup.create_template_group(template_groups) + if len(group_add_list) > 0: + module.exit_json(changed=True, result="Successfully created template group(s): %s" % group_add_list) + else: + module.exit_json(changed=False) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_token.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_token.py new file mode 100644 index 000000000..fc4d4c791 --- /dev/null +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_token.py @@ -0,0 +1,288 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2023, ONODERA Masaru <masaru-onodera@ieee.org> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +DOCUMENTATION = """ +--- +module: zabbix_token + +short_description: Create/Update/Generate/Delete Zabbix token. + +description: + - This module allows you to create, update, generate and delete Zabbix token. + +author: + - ONODERA Masaru(@masa-orca) + +requirements: + - "python >= 3.9" + +version_added: 2.1.0 + +options: + name: + description: + - Name of the token. + required: true + type: str + description: + description: + - Description of the token. + required: false + type: str + username: + description: + - Name of user who is the token assinged to. + required: true + type: str + status: + description: + - Status of the token. + required: false + type: bool + expires_at: + description: + - A timestamp of the token will be expired. + - The token will never expire if C(0) + required: false + type: int + generate_token: + description: + - New token string will be generated if C(true). + required: false + type: bool + default: false + state: + description: + - Create or delete token. + type: str + default: present + choices: + - present + - absent + +extends_documentation_fragment: + - community.zabbix.zabbix +""" + +EXAMPLES = """ +# If you want to use Username and Password to be authenticated by Zabbix Server +- name: Set credentials to access Zabbix Server API + ansible.builtin.set_fact: + ansible_user: Admin + ansible_httpapi_pass: zabbix + +# If you want to use API token to be authenticated by Zabbix Server +# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens +- name: Set API token + ansible.builtin.set_fact: + ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 + +- name: Create Zabbix token and generate token string + # set task level variables as we change ansible_connection plugin here + vars: + ansible_network_os: community.zabbix.zabbix + ansible_connection: httpapi + ansible_httpapi_port: 443 + ansible_httpapi_use_ssl: true + ansible_httpapi_validate_certs: false + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_host: zabbix-example-fqdn.org + community.zabbix.zabbix_token: + name: test token + description: Admin test token + username: Admin + status: true + expires_at: 1700000000 + generate_token: true + state: present +""" + +RETURN = """ +msg: + description: The result of the operation + returned: success + type: str + sample: "Successfully created token" +token: + description: Generated token string + returned: I(generate_token=true) + type: str + sample: "8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895" +""" + +from ansible.module_utils.basic import AnsibleModule + +from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase +import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils + + +class Token(ZabbixBase): + def get_userid_from_name(self, username): + try: + userids = self._zapi.user.get( + {"output": "userid", "filter": {"username": username}} + ) + if not userids or len(userids) > 1: + self._module.fail_json("User '%s' cannot be found" % username) + return userids[0]["userid"] + except Exception as e: + self._module.fail_json(msg="Failed to get userid: %s" % e) + + # get token + def get_token(self, name, userid): + try: + return self._zapi.token.get( + {"output": "extend", "userids": [userid], "filter": {"name": name}} + ) + except Exception as e: + self._module.fail_json(msg="Failed to get token: %s" % e) + + def create_token( + self, name, description, userid, status, expires_at, generate_token + ): + try: + params = {} + params["name"] = name + if isinstance(description, str): + params["description"] = description + + params["userid"] = userid + + if isinstance(status, bool): + if status: + params["status"] = "1" + else: + params["status"] = "0" + + if isinstance(expires_at, str): + params["expires_at"] = str(expires_at) + + if self._module.check_mode: + self._module.exit_json(changed=True) + result = self._zapi.token.create(params) + + if generate_token: + generated_tokens = self._zapi.token.generate(result["tokenids"]) + self._module.exit_json( + changed=True, + msg="Successfully created token.", + token=generated_tokens[0]["token"], + ) + else: + self._module.exit_json(changed=True, msg="Successfully created token.") + + except Exception as e: + self._module.fail_json(msg="Failed to create token: %s" % e) + + def update_token( + self, token, name, description, status, expires_at, generate_token + ): + try: + params = {} + params["tokenid"] = token["tokenid"] + params["name"] = name + if isinstance(description, str) and description != token["description"]: + params["description"] = description + + if isinstance(status, bool): + if status: + if token["status"] != "0": + params["status"] = "0" + else: + if token["status"] != "1": + params["status"] = "1" + + if isinstance(expires_at, int) and str(expires_at) != token["expires_at"]: + params["expires_at"] = str(expires_at) + + # If params does not have any parameter except tokenid and name, no need to update. + if len(params.keys()) == 2: + if not generate_token: + self._module.exit_json(changed=False) + elif self._module.check_mode: + self._module.exit_json(changed=True) + else: + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.token.update(params) + + if generate_token: + generated_tokens = self._zapi.token.generate([token["tokenid"]]) + self._module.exit_json( + changed=True, + msg="Successfully updated token.", + token=generated_tokens[0]["token"], + ) + else: + self._module.exit_json(changed=True, msg="Successfully updated token.") + + except Exception as e: + self._module.fail_json(msg="Failed to update token: %s" % e) + + # delete token + def delete_token(self, token): + try: + tokenid = token["tokenid"] + if self._module.check_mode: + self._module.exit_json(changed=True) + self._zapi.token.delete([tokenid]) + self._module.exit_json(changed=True, msg="Successfully deleted token.") + except Exception as e: + self._module.fail_json(msg="Failed to delete token: %s" % e) + + +def main(): + argument_spec = zabbix_utils.zabbix_common_argument_spec() + argument_spec.update( + dict( + name=dict(type="str", required=True), + description=dict(type="str"), + username=dict(type="str", required=True), + status=dict(type="bool"), + expires_at=dict(type="int"), + generate_token=dict(type="bool", default=False), + state=dict(type="str", choices=["present", "absent"], default="present"), + ) + ) + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + name = module.params["name"] + description = module.params["description"] + username = module.params["username"] + status = module.params["status"] + expires_at = module.params["expires_at"] + generate_token = module.params["generate_token"] + state = module.params["state"] + + token_class_obj = Token(module) + userid = token_class_obj.get_userid_from_name(username) + tokens = token_class_obj.get_token(name, userid) + if state == "absent": + if len(tokens) == 1: + token_class_obj.delete_token(tokens[0]) + else: + module.exit_json(changed=False) + else: + if len(tokens) == 1: + token_class_obj.update_token( + tokens[0], name, description, status, expires_at, generate_token + ) + else: + token_class_obj.create_token( + name, description, userid, status, expires_at, generate_token + ) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_user.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_user.py index 3c655ffe8..92f04b989 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_user.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_user.py @@ -6,9 +6,10 @@ from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" module: zabbix_user short_description: Create/update/delete Zabbix users author: @@ -16,14 +17,12 @@ author: description: - This module allows you to create, modify and delete Zabbix users. requirements: - - "python >= 2.6" + - "python >= 3.9" options: username: description: - - Name of the user alias in Zabbix. + - Username. - username is the unique identifier used and cannot be updated using this module. - - alias must be replaced with username since Zabbix 6.4. - aliases: [ alias ] required: true type: str name: @@ -45,7 +44,6 @@ options: description: - User's password. - Required unless all of the I(usrgrps) are set to use LDAP as frontend access. - - Always required for Zabbix versions lower than 4.0. required: false type: str override_passwd: @@ -54,37 +52,43 @@ options: - Password will not be updated on subsequent runs without setting this value to yes. default: no type: bool + current_passwd: + description: + - Current password for the user when overriding its password. + - Required when overriding the logged in user's password. + - https://www.zabbix.com/documentation/6.4/en/manual/api/reference/user/update + required: false + type: str lang: description: - Language code of the user's language. - - C(default) can be used with Zabbix version 5.2 or higher. choices: - - 'en_GB' - - 'en_US' - - 'zh_CN' - - 'cs_CZ' - - 'fr_FR' - - 'he_IL' - - 'it_IT' - - 'ko_KR' - - 'ja_JP' - - 'nb_NO' - - 'pl_PL' - - 'pt_BR' - - 'pt_PT' - - 'ru_RU' - - 'sk_SK' - - 'tr_TR' - - 'uk_UA' - - 'default' + - "en_GB" + - "en_US" + - "zh_CN" + - "cs_CZ" + - "fr_FR" + - "he_IL" + - "it_IT" + - "ko_KR" + - "ja_JP" + - "nb_NO" + - "pl_PL" + - "pt_BR" + - "pt_PT" + - "ru_RU" + - "sk_SK" + - "tr_TR" + - "uk_UA" + - "default" type: str theme: description: - User's theme. choices: - - 'default' - - 'blue-theme' - - 'dark-theme' + - "default" + - "blue-theme" + - "dark-theme" type: str autologin: description: @@ -116,7 +120,7 @@ options: mediatype: description: - Media type name to set. - default: 'Email' + default: "Email" type: str sendto: description: @@ -128,8 +132,8 @@ options: description: - Time when the notifications can be sent as a time period or user macros separated by a semicolon. - Please review the documentation for more information on the supported time period. - - https://www.zabbix.com/documentation/4.0/manual/appendix/time_period - default: '1-7,00:00-24:00' + - https://www.zabbix.com/documentation/current/en/manual/appendix/time_period + default: "1-7,00:00-24:00" type: str severity: description: @@ -180,26 +184,15 @@ options: type: bool type: list elements: dict - type: - description: - - Type of the user. - - I(type) can be used when Zabbix version is 5.0 or lower. - choices: - - 'Zabbix user' - - 'Zabbix admin' - - 'Zabbix super admin' - type: str timezone: description: - User's time zone. - - I(timezone) can be used with Zabbix version 5.2 or higher. - For the full list of supported time zones please refer to U(https://www.php.net/manual/en/timezones.php) type: str version_added: 1.2.0 role_name: description: - User's role. - - I(role_name) can be used when Zabbix version is 5.2 or higher. - Default is C(User role) when creating a new user. - The default value will be removed at the version 2.0.0. type: str @@ -209,25 +202,25 @@ options: - State of the user. - On C(present), it will create if user does not exist or update the user if the associated data is different. - On C(absent) will remove a user if it exists. - default: 'present' - choices: ['present', 'absent'] + default: "present" + choices: ["present", "absent"] type: str extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: create a new zabbix user. @@ -238,7 +231,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user: username: example @@ -251,10 +244,10 @@ EXAMPLES = r''' lang: en_GB theme: blue-theme autologin: no - autologout: '0' - refresh: '30' - rows_per_page: '200' - after_login_url: '' + autologout: "0" + refresh: "30" + rows_per_page: "200" + after_login_url: "" user_medias: - mediatype: Email sendto: @@ -269,7 +262,6 @@ EXAMPLES = r''' high: yes disaster: yes active: no - type: Zabbix super admin state: present - name: delete existing zabbix user. @@ -280,20 +272,20 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user: username: example state: absent -''' +""" -RETURN = r''' +RETURN = r""" user_ids: description: User id created or changed returned: success type: dict sample: { "userids": [ "5" ] } -''' +""" import copy @@ -301,44 +293,40 @@ import copy from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase -from ansible_collections.community.zabbix.plugins.module_utils.helpers import helper_normalize_data +from ansible_collections.community.zabbix.plugins.module_utils.helpers import ( + helper_normalize_data, +) from ansible.module_utils.compat.version import LooseVersion import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils class User(ZabbixBase): - - def username_key(self): - """ Returns the key name for 'username', which was 'alias' - before Zabbix 5.4. - """ - if LooseVersion(self._zbx_api_version) < LooseVersion('5.4'): - return 'alias' - return 'username' - def get_default_authentication(self): - auth = self._zapi.authentication.get({'output': 'extend'}) + auth = self._zapi.authentication.get({"output": "extend"}) try: if auth["authentication_type"] == "0": return "internal" elif auth["authentication_type"] == "1": return "LDAP" else: - self._module.fail_json(msg="Failed to query authentication type. Unknown authentication type %s" % auth) + self._module.fail_json( + msg="Failed to query authentication type. Unknown authentication type %s" + % auth + ) except Exception as e: - self._module.fail_json(msg="Unhandled error while querying authentication type. %s" % (e)) + self._module.fail_json( + msg="Unhandled error while querying authentication type. %s" % (e) + ) def get_usergroups_by_name(self, usrgrps): params = { - 'output': ['usrgrpid', 'name', 'gui_access'], - 'filter': { - 'name': usrgrps - } + "output": ["usrgrpid", "name", "gui_access"], + "filter": {"name": usrgrps}, } res = self._zapi.usergroup.get(params) if res: - ids = [{'usrgrpid': g['usrgrpid']} for g in res] + ids = [{"usrgrpid": g["usrgrpid"]} for g in res] # User can be created password-less only when all groups are of non-internal # authentication types # 0 = use system default authentication method @@ -346,199 +334,248 @@ class User(ZabbixBase): # 2 = use LDAP authentication # 3 = disable access to the frontend - if bool([g for g in res if g['gui_access'] == '1']): + if bool([g for g in res if g["gui_access"] == "1"]): require_password = True - elif bool([g for g in res if g['gui_access'] == '2' or g['gui_access'] == '3']): + elif bool( + [g for g in res if g["gui_access"] == "2" or g["gui_access"] == "3"] + ): require_password = False - elif bool([g for g in res if g['gui_access'] == '0']): + elif bool([g for g in res if g["gui_access"] == "0"]): # Zabbix API for versions < 5.2 does not have a way to query the default auth type # so we must assume its set to internal - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.2'): - default_authentication = self.get_default_authentication() - require_password = True if default_authentication == 'internal' else False - else: - default_authentication = "internal" - require_password = True + default_authentication = self.get_default_authentication() + require_password = ( + True if default_authentication == "internal" else False + ) - not_found_groups = set(usrgrps) - set([g['name'] for g in res]) + not_found_groups = set(usrgrps) - set([g["name"] for g in res]) if not_found_groups: - self._module.fail_json(msg='User groups not found: %s' % not_found_groups) + self._module.fail_json( + msg="User groups not found: %s" % not_found_groups + ) return ids, require_password else: - self._module.fail_json(msg='No user groups found') + self._module.fail_json(msg="No user groups found") def check_user_exist(self, username): - zbx_user = self._zapi.user.get({'output': 'extend', 'filter': {self.username_key(): username}, - 'getAccess': True, 'selectMedias': 'extend', - 'selectUsrgrps': 'extend'}) + zbx_user = self._zapi.user.get( + { + "output": "extend", + "filter": {"username": username}, + "getAccess": True, + "selectMedias": "extend", + "selectUsrgrps": "extend", + } + ) return zbx_user def convert_user_medias_parameter_types(self, user_medias): copy_user_medias = copy.deepcopy(user_medias) for user_media in copy_user_medias: - media_types = self._zapi.mediatype.get({'output': 'extend'}) + media_types = self._zapi.mediatype.get({"output": "extend"}) for media_type in media_types: - if LooseVersion(self._zbx_api_version) < LooseVersion('4.4'): - if media_type['description'] == user_media['mediatype']: - user_media['mediatypeid'] = media_type['mediatypeid'] - user_media['mediatype'] = media_type['type'] - break - else: - if media_type['name'] == user_media['mediatype']: - user_media['mediatypeid'] = media_type['mediatypeid'] - user_media['mediatype'] = media_type['type'] - break - if 'mediatypeid' not in user_media: - self._module.fail_json(msg="Media type not found: %s" % user_media['mediatype']) + if media_type["name"] == user_media["mediatype"]: + user_media["mediatypeid"] = media_type["mediatypeid"] + user_media["mediatype"] = media_type["type"] + break + if "mediatypeid" not in user_media: + self._module.fail_json( + msg="Media type not found: %s" % user_media["mediatype"] + ) else: - if user_media['mediatype'] == '0': # E-Mail + if user_media["mediatype"] == "0": # E-Mail # Because user media sendto parameter is raw in parameters specs perform explicit check on type - if not (isinstance(user_media['sendto'], list) or isinstance(user_media['sendto'], str)): - self._module.fail_json('For Email media type sendto parameter must be of type list or str.') - if isinstance(user_media['sendto'], str): + if not ( + isinstance(user_media["sendto"], list) + or isinstance(user_media["sendto"], str) + ): + self._module.fail_json( + "For Email media type sendto parameter must be of type list or str." + ) + if isinstance(user_media["sendto"], str): # sendto should be a list for Email media type - user_media['sendto'] = [user_media['sendto']] + user_media["sendto"] = [user_media["sendto"]] else: - if not isinstance(user_media['sendto'], str): - self._module.fail_json(user_media) - self._module.fail_json('For any other than Email media type sendto parameter must be of type str.') - del user_media['mediatype'] - - severity_binary_number = '' - for severity_key in 'disaster', 'high', 'average', 'warning', 'information', 'not_classified': - if user_media['severity'][severity_key]: - severity_binary_number = severity_binary_number + '1' + if not isinstance(user_media["sendto"], str): + self._module.fail_json( + "For any other than Email media type sendto parameter must be of type str." + ) + del user_media["mediatype"] + + severity_binary_number = "" + for severity_key in ( + "disaster", + "high", + "average", + "warning", + "information", + "not_classified", + ): + if user_media["severity"][severity_key]: + severity_binary_number = severity_binary_number + "1" else: - severity_binary_number = severity_binary_number + '0' - user_media['severity'] = str(int(severity_binary_number, 2)) + severity_binary_number = severity_binary_number + "0" + user_media["severity"] = str(int(severity_binary_number, 2)) - if user_media['active']: - user_media['active'] = '0' + if user_media["active"]: + user_media["active"] = "0" else: - user_media['active'] = '1' + user_media["active"] = "1" return copy_user_medias def get_roleid_by_name(self, role_name): - roles = self._zapi.role.get({'output': 'extend'}) + roles = self._zapi.role.get({"output": "extend"}) for role in roles: - if role['name'] == role_name: - return role['roleid'] + if role["name"] == role_name: + return role["roleid"] self._module.fail_json(msg="Role not found: %s" % role_name) - def user_parameter_difference_check(self, zbx_user, username, name, surname, user_group_ids, passwd, lang, theme, - autologin, autologout, refresh, rows_per_page, url, user_medias, user_type, - timezone, role_name, override_passwd): + def user_parameter_difference_check( + self, + zbx_user, + username, + name, + surname, + user_group_ids, + passwd, + lang, + theme, + autologin, + autologout, + refresh, + rows_per_page, + url, + user_medias, + timezone, + role_name, + override_passwd, + ): # existing data existing_data = copy.deepcopy(zbx_user[0]) usrgrpids = [] - for usrgrp in existing_data['usrgrps']: - usrgrpids.append({'usrgrpid': usrgrp['usrgrpid']}) - existing_data['usrgrps'] = sorted(usrgrpids, key=lambda x: x['usrgrpid']) - existing_data['user_medias'] = existing_data['medias'] - for del_key in ['medias', 'attempt_clock', 'attempt_failed', 'attempt_ip', 'debug_mode', 'users_status', - 'gui_access']: + for usrgrp in existing_data["usrgrps"]: + usrgrpids.append({"usrgrpid": usrgrp["usrgrpid"]}) + existing_data["usrgrps"] = sorted(usrgrpids, key=lambda x: x["usrgrpid"]) + existing_data["user_medias"] = existing_data["medias"] + for del_key in [ + "medias", + "attempt_clock", + "attempt_failed", + "attempt_ip", + "debug_mode", + "users_status", + "gui_access", + ]: del existing_data[del_key] - if 'user_medias' in existing_data and existing_data['user_medias']: - for user_media in existing_data['user_medias']: - for del_key in ['mediaid', 'userid']: + if "user_medias" in existing_data and existing_data["user_medias"]: + for user_media in existing_data["user_medias"]: + for del_key in ["mediaid", "userid"]: del user_media[del_key] # request data request_data = { - 'userid': zbx_user[0]['userid'], - self.username_key(): username, - 'name': name, - 'surname': surname, - 'usrgrps': sorted(user_group_ids, key=lambda x: x['usrgrpid']), - 'lang': lang, - 'theme': theme, - 'autologin': autologin, - 'autologout': autologout, - 'refresh': refresh, - 'rows_per_page': rows_per_page, - 'url': url, + "userid": zbx_user[0]["userid"], + "username": username, + "name": name, + "surname": surname, + "usrgrps": sorted(user_group_ids, key=lambda x: x["usrgrpid"]), + "lang": lang, + "theme": theme, + "autologin": autologin, + "autologout": autologout, + "refresh": refresh, + "rows_per_page": rows_per_page, + "url": url, } if user_medias: - request_data['user_medias'] = user_medias + request_data["user_medias"] = user_medias else: - if 'user_medias' in existing_data and existing_data['user_medias']: - del existing_data['user_medias'] + if "user_medias" in existing_data and existing_data["user_medias"]: + del existing_data["user_medias"] if override_passwd: - request_data['passwd'] = passwd + request_data["passwd"] = passwd - # The type key has changed to roleid key since Zabbix 5.2 - if LooseVersion(self._zbx_api_version) < LooseVersion('5.2'): - request_data['type'] = user_type - else: - request_data['roleid'] = self.get_roleid_by_name(role_name) if role_name else None - request_data['timezone'] = timezone + request_data["roleid"] = ( + self.get_roleid_by_name(role_name) if role_name else None + ) + request_data["timezone"] = timezone request_data, del_keys = helper_normalize_data(request_data) existing_data, _del_keys = helper_normalize_data(existing_data, del_keys) user_parameter_difference_check_result = True diff_dict = {} - if not zabbix_utils.helper_compare_dictionaries(request_data, existing_data, diff_dict): + if not zabbix_utils.helper_compare_dictionaries( + request_data, existing_data, diff_dict + ): user_parameter_difference_check_result = False - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.4'): + if LooseVersion(self._zbx_api_version) >= LooseVersion("6.4"): if user_medias: - request_data['medias'] = user_medias - del request_data['user_medias'] + request_data["medias"] = user_medias + del request_data["user_medias"] - diff_params = { - "before": existing_data, - "after": request_data - } + diff_params = {"before": existing_data, "after": request_data} return user_parameter_difference_check_result, diff_params - def add_user(self, username, name, surname, user_group_ids, passwd, lang, theme, autologin, autologout, refresh, - rows_per_page, url, user_medias, user_type, require_password, timezone, role_name): - - if role_name is None and LooseVersion(self._zbx_api_version) >= LooseVersion('5.2'): - # This variable is to set the default value because the module must have a backward-compatible. - # The default value will be removed at the version 2.0.0. - # https://github.com/ansible-collections/community.zabbix/pull/382 + def add_user( + self, + username, + name, + surname, + user_group_ids, + passwd, + lang, + theme, + autologin, + autologout, + refresh, + rows_per_page, + url, + user_medias, + require_password, + timezone, + role_name, + ): + + if role_name is None: role_name = "User role" user_ids = {} request_data = { - self.username_key(): username, - 'name': name, - 'surname': surname, - 'usrgrps': user_group_ids, - 'lang': lang, - 'theme': theme, - 'autologin': autologin, - 'autologout': autologout, - 'refresh': refresh, - 'rows_per_page': rows_per_page, - 'url': url, + "username": username, + "name": name, + "surname": surname, + "usrgrps": user_group_ids, + "lang": lang, + "theme": theme, + "autologin": autologin, + "autologout": autologout, + "refresh": refresh, + "rows_per_page": rows_per_page, + "url": url, } if user_medias: - if LooseVersion(self._zbx_api_version) <= LooseVersion('6.2'): - request_data['user_medias'] = user_medias + if LooseVersion(self._zbx_api_version) <= LooseVersion("6.2"): + request_data["user_medias"] = user_medias else: - request_data['medias'] = user_medias + request_data["medias"] = user_medias - if LooseVersion(self._zbx_api_version) < LooseVersion('4.0') or require_password: - request_data['passwd'] = passwd + if (require_password): + request_data["passwd"] = passwd # The type key has changed to roleid key since Zabbix 5.2 - if LooseVersion(self._zbx_api_version) < LooseVersion('5.2'): - request_data['type'] = user_type - else: - request_data['roleid'] = self.get_roleid_by_name(role_name) - request_data['timezone'] = timezone + request_data["roleid"] = self.get_roleid_by_name(role_name) + request_data["timezone"] = timezone request_data, _del_keys = helper_normalize_data(request_data) @@ -547,79 +584,84 @@ class User(ZabbixBase): try: user_ids = self._zapi.user.create(request_data) except Exception as e: - self._module.fail_json(msg="Failed to create user %s: %s" % (username, e)) + self._module.fail_json( + msg="Failed to create user %s: %s" % (username, e) + ) else: - diff_params = { - "before": "", - "after": request_data - } + diff_params = {"before": "", "after": request_data} return user_ids, diff_params - def update_user(self, zbx_user, username, name, surname, user_group_ids, passwd, lang, theme, autologin, autologout, - refresh, rows_per_page, url, user_medias, user_type, timezone, role_name, override_passwd): + def update_user( + self, + zbx_user, + username, + name, + surname, + user_group_ids, + passwd, + lang, + theme, + autologin, + autologout, + refresh, + rows_per_page, + url, + user_medias, + timezone, + role_name, + override_passwd, + current_passwd, + ): user_ids = {} request_data = { - 'userid': zbx_user[0]['userid'], - self.username_key(): username, - 'name': name, - 'surname': surname, - 'usrgrps': user_group_ids, - 'lang': lang, - 'theme': theme, - 'autologin': autologin, - 'autologout': autologout, - 'refresh': refresh, - 'rows_per_page': rows_per_page, - 'url': url, + "userid": zbx_user[0]["userid"], + "username": username, + "name": name, + "surname": surname, + "usrgrps": user_group_ids, + "lang": lang, + "theme": theme, + "autologin": autologin, + "autologout": autologout, + "refresh": refresh, + "rows_per_page": rows_per_page, + "url": url, } if override_passwd: - request_data['passwd'] = passwd + request_data["passwd"] = passwd + if current_passwd: + request_data["current_passwd"] = current_passwd - # The type key has changed to roleid key since Zabbix 5.2 - if LooseVersion(self._zbx_api_version) < LooseVersion('5.2'): - request_data['type'] = user_type - else: - request_data['roleid'] = self.get_roleid_by_name(role_name) if role_name else None - request_data['timezone'] = timezone + request_data["roleid"] = ( + self.get_roleid_by_name(role_name) if role_name else None + ) + request_data["timezone"] = timezone request_data, _del_keys = helper_normalize_data(request_data) - # In the case of zabbix 3.2 or less, it is necessary to use updatemedia method to update media. - if LooseVersion(self._zbx_api_version) <= LooseVersion('3.2'): - try: - user_ids = self._zapi.user.update(request_data) - except Exception as e: - self._module.fail_json(msg="Failed to update user %s: %s" % (username, e)) - + if LooseVersion(self._zbx_api_version) < LooseVersion("6.4"): try: if user_medias: - user_ids = self._zapi.user.updatemedia({ - 'users': [{'userid': zbx_user[0]['userid']}], - 'medias': user_medias - }) - except Exception as e: - self._module.fail_json(msg="Failed to update user medias %s: %s" % (username, e)) - - if (LooseVersion(self._zbx_api_version) >= LooseVersion('3.4') - and LooseVersion(self._zbx_api_version) < LooseVersion('6.4')): - try: - if user_medias: - request_data['user_medias'] = user_medias + request_data["user_medias"] = user_medias user_ids = self._zapi.user.update(request_data) except Exception as e: - self._module.fail_json(msg="Failed to update user %s: %s" % (username, e)) + self._module.fail_json( + msg="Failed to update user %s: %s" % (username, e) + ) - if LooseVersion(self._zbx_api_version) >= LooseVersion('6.4'): + if LooseVersion(self._zbx_api_version) >= LooseVersion("6.4"): try: if user_medias: - request_data['medias'] = user_medias + request_data["medias"] = user_medias user_ids = self._zapi.user.update(request_data) except Exception as e: - self._module.fail_json(msg="Failed to update user %s: %s" % (username, e)) + self._module.fail_json( + msg="Failed to update user %s: %s" % (username, e) + ) return user_ids @@ -629,107 +671,123 @@ class User(ZabbixBase): if not self._module.check_mode: try: - user_ids = self._zapi.user.delete([zbx_user[0]['userid']]) + user_ids = self._zapi.user.delete([zbx_user[0]["userid"]]) except Exception as e: - self._module.fail_json(msg="Failed to delete user %s: %s" % (username, e)) + self._module.fail_json( + msg="Failed to delete user %s: %s" % (username, e) + ) else: - diff_params = { - "before": zbx_user[0], - "after": "" - } + diff_params = {"before": zbx_user[0], "after": ""} return user_ids, diff_params def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() - argument_spec.update(dict( - username=dict(type='str', required=True, aliases=['alias']), - name=dict(type='str'), - surname=dict(type='str'), - usrgrps=dict(type='list'), - passwd=dict(type='str', required=False, no_log=True), - override_passwd=dict(type='bool', required=False, default=False, no_log=False), - lang=dict(type='str', choices=['en_GB', 'en_US', 'zh_CN', 'cs_CZ', 'fr_FR', - 'he_IL', 'it_IT', 'ko_KR', 'ja_JP', 'nb_NO', - 'pl_PL', 'pt_BR', 'pt_PT', 'ru_RU', 'sk_SK', - 'tr_TR', 'uk_UA', 'default']), - theme=dict(type='str', choices=['default', 'blue-theme', 'dark-theme']), - autologin=dict(type='bool'), - autologout=dict(type='str'), - refresh=dict(type='str'), - rows_per_page=dict(type='str'), - after_login_url=dict(type='str'), - user_medias=dict(type='list', elements='dict', - options=dict(mediatype=dict(type='str', default='Email'), - sendto=dict(type='raw', required=True), - period=dict(type='str', default='1-7,00:00-24:00'), - severity=dict(type='dict', - options=dict( - not_classified=dict(type='bool', default=True), - information=dict(type='bool', default=True), - warning=dict(type='bool', default=True), - average=dict(type='bool', default=True), - high=dict(type='bool', default=True), - disaster=dict(type='bool', default=True)), - default=dict( - not_classified=True, - information=True, - warning=True, - average=True, - high=True, - disaster=True)), - active=dict(type='bool', default=True))), - timezone=dict(type='str'), - role_name=dict(type='str'), - type=dict(type='str', choices=['Zabbix user', 'Zabbix admin', 'Zabbix super admin']), - state=dict(type='str', default="present", choices=['present', 'absent']) - )) + argument_spec.update( + dict( + username=dict(type="str", required=True), + name=dict(type="str"), + surname=dict(type="str"), + usrgrps=dict(type="list", elements="str"), + passwd=dict(type="str", required=False, no_log=True), + override_passwd=dict( + type="bool", required=False, default=False, no_log=False + ), + current_passwd=dict(type="str", required=False, no_log=True), + lang=dict( + type="str", + choices=[ + "en_GB", + "en_US", + "zh_CN", + "cs_CZ", + "fr_FR", + "he_IL", + "it_IT", + "ko_KR", + "ja_JP", + "nb_NO", + "pl_PL", + "pt_BR", + "pt_PT", + "ru_RU", + "sk_SK", + "tr_TR", + "uk_UA", + "default", + ], + ), + theme=dict(type="str", choices=["default", "blue-theme", "dark-theme"]), + autologin=dict(type="bool"), + autologout=dict(type="str"), + refresh=dict(type="str"), + rows_per_page=dict(type="str"), + after_login_url=dict(type="str"), + user_medias=dict( + type="list", + elements="dict", + options=dict( + mediatype=dict(type="str", default="Email"), + sendto=dict(type="raw", required=True), + period=dict(type="str", default="1-7,00:00-24:00"), + severity=dict( + type="dict", + options=dict( + not_classified=dict(type="bool", default=True), + information=dict(type="bool", default=True), + warning=dict(type="bool", default=True), + average=dict(type="bool", default=True), + high=dict(type="bool", default=True), + disaster=dict(type="bool", default=True), + ), + default=dict( + not_classified=True, + information=True, + warning=True, + average=True, + high=True, + disaster=True, + ), + ), + active=dict(type="bool", default=True), + ), + ), + timezone=dict(type="str"), + role_name=dict(type="str"), + state=dict(type="str", default="present", choices=["present", "absent"]), + ) + ) module = AnsibleModule( argument_spec=argument_spec, - required_if=[ - ['state', 'present', ['usrgrps']] - ], - supports_check_mode=True + required_if=[["state", "present", ["usrgrps"]]], + supports_check_mode=True, ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - username = module.params['username'] - name = module.params['name'] - surname = module.params['surname'] - usrgrps = module.params['usrgrps'] - passwd = module.params['passwd'] - override_passwd = module.params['override_passwd'] - lang = module.params['lang'] - theme = module.params['theme'] - autologin = module.params['autologin'] - autologout = module.params['autologout'] - refresh = module.params['refresh'] - rows_per_page = module.params['rows_per_page'] - after_login_url = module.params['after_login_url'] - user_medias = module.params['user_medias'] - user_type = module.params['type'] - timezone = module.params['timezone'] - role_name = module.params['role_name'] - state = module.params['state'] + username = module.params["username"] + name = module.params["name"] + surname = module.params["surname"] + usrgrps = module.params["usrgrps"] + passwd = module.params["passwd"] + override_passwd = module.params["override_passwd"] + current_passwd = module.params["current_passwd"] + lang = module.params["lang"] + theme = module.params["theme"] + autologin = module.params["autologin"] + autologout = module.params["autologout"] + refresh = module.params["refresh"] + rows_per_page = module.params["rows_per_page"] + after_login_url = module.params["after_login_url"] + user_medias = module.params["user_medias"] + timezone = module.params["timezone"] + role_name = module.params["role_name"] + state = module.params["state"] if autologin is not None: if autologin: - autologin = '1' + autologin = "1" else: - autologin = '0' - - user_type_dict = { - 'Zabbix user': '1', - 'Zabbix admin': '2', - 'Zabbix super admin': '3' - } - user_type = user_type_dict[user_type] if user_type else None + autologin = "0" user = User(module) @@ -738,31 +796,78 @@ def main(): user_ids = {} zbx_user = user.check_user_exist(username) - if state == 'present': + if state == "present": user_group_ids, require_password = user.get_usergroups_by_name(usrgrps) - if LooseVersion(user._zbx_api_version) < LooseVersion('4.0') or require_password: + if (require_password): if passwd is None: - module.fail_json(msg='User password is required. One or more groups are not LDAP based.') + module.fail_json( + msg="User password is required. One or more groups are not LDAP based." + ) if zbx_user: - diff_check_result, diff_params = user.user_parameter_difference_check(zbx_user, username, name, surname, - user_group_ids, passwd, lang, theme, - autologin, autologout, refresh, - rows_per_page, after_login_url, - user_medias, user_type, timezone, - role_name, override_passwd) + diff_check_result, diff_params = user.user_parameter_difference_check( + zbx_user, + username, + name, + surname, + user_group_ids, + passwd, + lang, + theme, + autologin, + autologout, + refresh, + rows_per_page, + after_login_url, + user_medias, + timezone, + role_name, + override_passwd, + ) if not module.check_mode and diff_check_result: - user_ids = user.update_user(zbx_user, username, name, surname, user_group_ids, passwd, lang, - theme, autologin, autologout, refresh, rows_per_page, after_login_url, - user_medias, user_type, timezone, role_name, override_passwd) + user_ids = user.update_user( + zbx_user, + username, + name, + surname, + user_group_ids, + passwd, + lang, + theme, + autologin, + autologout, + refresh, + rows_per_page, + after_login_url, + user_medias, + timezone, + role_name, + override_passwd, + current_passwd, + ) else: diff_check_result = True - user_ids, diff_params = user.add_user(username, name, surname, user_group_ids, passwd, lang, theme, autologin, - autologout, refresh, rows_per_page, after_login_url, user_medias, - user_type, require_password, timezone, role_name) - - if state == 'absent': + user_ids, diff_params = user.add_user( + username, + name, + surname, + user_group_ids, + passwd, + lang, + theme, + autologin, + autologout, + refresh, + rows_per_page, + after_login_url, + user_medias, + require_password, + timezone, + role_name, + ) + + if state == "absent": if zbx_user: diff_check_result = True user_ids, diff_params = user.delete_user(zbx_user, username) diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_user_directory.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_user_directory.py index 818fe98c0..b383fcdcf 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_user_directory.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_user_directory.py @@ -4,10 +4,11 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_user_directory short_description: Create/update/delete Zabbix user directories @@ -29,7 +30,7 @@ options: - This parameter is available since Zabbix 6.4. required: false type: str - choices: ['ldap', 'saml'] + choices: ["ldap", "saml"] provision_status: description: - User directory provisioning status. @@ -63,7 +64,7 @@ options: - User directory description. required: false type: str - default: '' + default: "" group_membership: description: - LDAP property containing groups of user. E.g. I(memberOf) @@ -150,7 +151,7 @@ options: - LDAP bind distinguished name string. Can be empty for anonymous binding. required: false type: str - default: '' + default: "" idp_entityid: description: - SAML URI that identifies the IdP in SAML messages. @@ -167,7 +168,7 @@ options: type: str sso_url: description: - - SAML URL of the IdP's SAML SSO service, to which Zabbix will send SAML authentication requests. + - SAML URL of the IdP"s SAML SSO service, to which Zabbix will send SAML authentication requests. - required if C(idp_type) is set to I(saml). - This parameter is available since Zabbix 6.4. required: false @@ -302,27 +303,27 @@ options: - State of the user directory. - On C(present), it will create if user directory does not exist or update it if the associated data is different. - On C(absent) will remove the user directory if it exists. - choices: ['present', 'absent'] - default: 'present' + choices: ["present", "absent"] + default: "present" type: str extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" --- # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create new user directory or update existing info (Zabbix <= 6.2) @@ -333,18 +334,18 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user_directory: state: present name: TestUserDirectory - host: 'test.com' + host: "test.com" port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - bind_dn: 'cn=ldap_search,dc=example,dc=org' - description: 'Test user directory' - search_filter: '(%{attr}=test_user)' + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + bind_dn: "cn=ldap_search,dc=example,dc=org" + description: "Test user directory" + search_filter: "(%{attr}=test_user)" start_tls: 0 - name: Create new user directory with LDAP IDP or update existing info (Zabbix >= 6.4) @@ -355,22 +356,22 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user_directory: state: present name: TestUserDirectory idp_type: ldap - host: 'test.ca' + host: "test.ca" port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" provision_status: true group_name: cn group_basedn: ou=Group,dc=example,dc=org group_member: member user_ref_attr: uid - group_filter: '(member=uid=%{ref},ou=Users,dc=example,dc=com)' + group_filter: "(member=uid=%{ref},ou=Users,dc=example,dc=com)" user_username: first_name user_lastname: last_name provision_media: @@ -391,7 +392,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user_directory: state: present @@ -414,7 +415,7 @@ EXAMPLES = r''' role: Guest role user_groups: - Guests -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -426,220 +427,305 @@ import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabb def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() - argument_spec.update(dict( - name=dict(type='str', required=True), - idp_type=dict(type='str', required=False, choices=['ldap', 'saml']), - host=dict(type='str', required=False), - port=dict(type='int', required=False), - base_dn=dict(type='str', required=False), - search_attribute=dict(type='str', required=False), - bind_dn=dict(type='str', required=False, default=''), - bind_password=dict(type='str', required=False, no_log=True), - description=dict(type='str', required=False, default=''), - search_filter=dict(type='str', default='(%{attr}=%{user})', required=False), - start_tls=dict(type='int', required=False, choices=[0, 1], default=0), - idp_entityid=dict(type='str', required=False), - sp_entityid=dict(type='str', required=False), - sso_url=dict(type='str', required=False), - slo_url=dict(type='str', required=False), - username_attribute=dict(type='str', required=False), - nameid_format=dict(type='str', required=False), - scim_status=dict(type='bool', required=False, default=False), - encrypt_nameid=dict(type='bool', required=False, default=False), - encrypt_assertions=dict(type='bool', required=False, default=False), - sign_messages=dict(type='bool', required=False, default=False), - sign_assertions=dict(type='bool', required=False, default=False), - sign_authn_requests=dict(type='bool', required=False, default=False), - sign_logout_requests=dict(type='bool', required=False, default=False), - sign_logout_responses=dict(type='bool', required=False, default=False), - provision_status=dict(type='bool', required=False, default=False), - group_basedn=dict(type='str', required=False), - group_filter=dict(type='str', required=False), - group_member=dict(type='str', required=False), - group_membership=dict(type='str', required=False), - group_name=dict(type='str', required=False), - user_lastname=dict(type='str', required=False), - user_ref_attr=dict(type='str', required=False), - user_username=dict(type='str', required=False), - provision_media=dict( - type='list', - required=False, - elements='dict', - options=dict( - name=dict(type='str', required=True), - mediatype=dict(type='str', required=True), - attribute=dict(type='str', required=True) - ) - ), - provision_groups=dict( - type='list', - required=False, - elements='dict', - options=dict( - name=dict(type='str', required=True), - role=dict(type='str', required=True), - user_groups=dict(type='list', elements='str', required=True) - ) - ), - state=dict(type='str', default='present', choices=['present', 'absent']) - )) - - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True + argument_spec.update( + dict( + name=dict(type="str", required=True), + idp_type=dict(type="str", required=False, choices=["ldap", "saml"]), + host=dict(type="str", required=False), + port=dict(type="int", required=False), + base_dn=dict(type="str", required=False), + search_attribute=dict(type="str", required=False), + bind_dn=dict(type="str", required=False, default=""), + bind_password=dict(type="str", required=False, no_log=True), + description=dict(type="str", required=False, default=""), + search_filter=dict(type="str", default="(%{attr}=%{user})", required=False), + start_tls=dict(type="int", required=False, choices=[0, 1], default=0), + idp_entityid=dict(type="str", required=False), + sp_entityid=dict(type="str", required=False), + sso_url=dict(type="str", required=False), + slo_url=dict(type="str", required=False), + username_attribute=dict(type="str", required=False), + nameid_format=dict(type="str", required=False), + scim_status=dict(type="bool", required=False, default=False), + encrypt_nameid=dict(type="bool", required=False, default=False), + encrypt_assertions=dict(type="bool", required=False, default=False), + sign_messages=dict(type="bool", required=False, default=False), + sign_assertions=dict(type="bool", required=False, default=False), + sign_authn_requests=dict(type="bool", required=False, default=False), + sign_logout_requests=dict(type="bool", required=False, default=False), + sign_logout_responses=dict(type="bool", required=False, default=False), + provision_status=dict(type="bool", required=False, default=False), + group_basedn=dict(type="str", required=False), + group_filter=dict(type="str", required=False), + group_member=dict(type="str", required=False), + group_membership=dict(type="str", required=False), + group_name=dict(type="str", required=False), + user_lastname=dict(type="str", required=False), + user_ref_attr=dict(type="str", required=False), + user_username=dict(type="str", required=False), + provision_media=dict( + type="list", + required=False, + elements="dict", + options=dict( + name=dict(type="str", required=True), + mediatype=dict(type="str", required=True), + attribute=dict(type="str", required=True), + ), + ), + provision_groups=dict( + type="list", + required=False, + elements="dict", + options=dict( + name=dict(type="str", required=True), + role=dict(type="str", required=True), + user_groups=dict(type="list", elements="str", required=True), + ), + ), + state=dict(type="str", default="present", choices=["present", "absent"]), + ) ) - ''' For future when < 6.4 disappears we should use this, now we cannot do this as at this point Zabbix version is unknown + + module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + """ For future when < 6.4 disappears we should use this, now we cannot do this as at this point Zabbix version is unknown module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ - ('state', 'present', ('idp_type',)), - ('idp_type', 'ldap', ('host', 'port', 'base_dn', 'search_attribute'), False), - ('idp_type', 'saml', ('idp_entityid', 'sp_entityid', 'sso_url', 'username_attribute'), False), - ('provision_status', 'true', ('provision_groups')) + ("state", "present", ("idp_type",)), + ("idp_type", "ldap", ("host", "port", "base_dn", "search_attribute"), False), + ("idp_type", "saml", ("idp_entityid", "sp_entityid", "sso_url", "username_attribute"), False), + ("provision_status", "true", ("provision_groups")) ] ) - ''' - - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - parameters = { - 'name': module.params['name'] - } - for p in ['host', 'port', 'base_dn', 'search_attribute', 'bind_dn', 'bind_password', 'description', 'start_tls']: + """ + + parameters = {"name": module.params["name"]} + for p in [ + "host", + "port", + "base_dn", + "search_attribute", + "bind_dn", + "bind_password", + "description", + "start_tls", + ]: if module.params[p]: - if p in ['port', 'start_tls']: + if p in ["port", "start_tls"]: parameters[p] = str(module.params[p]) else: parameters[p] = module.params[p] - state = module.params['state'] + state = module.params["state"] user_directory = ZabbixBase(module) - if LooseVersion(user_directory._zbx_api_version) < LooseVersion('6.2'): - module.fail_json(msg='Zabbix < 6.2 does not support user directories.') + if LooseVersion(user_directory._zbx_api_version) < LooseVersion("6.2"): + module.fail_json(msg="Zabbix < 6.2 does not support user directories.") - if LooseVersion(user_directory._zbx_api_version) < LooseVersion('6.4'): - parameters['search_filter'] = module.params['search_filter'] - directory = user_directory._zapi.userdirectory.get({'filter': {'name': parameters['name']}}) + if LooseVersion(user_directory._zbx_api_version) < LooseVersion("6.4"): + parameters["search_filter"] = module.params["search_filter"] + directory = user_directory._zapi.userdirectory.get( + {"filter": {"name": parameters["name"]}} + ) else: # Zabbix >= 6.4 # Mandatory parameters check - if state == 'present' and not module.params['idp_type']: - module.fail_json('"idp_type" parameter must be provided when state is "present"') - if module.params['idp_type']: - if (module.params['idp_type'] == 'ldap' - and (not module.params['host'] or not module.params['port'] or not module.params['base_dn'] or not module.params['search_attribute'])): - module.fail_json('"host", "port", "base_dn", "search_attribute" must be provided when idp_type is "ldap"') - if (module.params['idp_type'] == 'saml' - and (not module.params['idp_entityid'] or not module.params['sp_entityid'] - or not module.params['sso_url'] or not module.params['username_attribute'])): - module.fail_json('"idp_entityid", "sp_entityid", "sso_url", "username_attribute" must be provided when idp_type is "ldap"') + if state == "present" and not module.params["idp_type"]: + module.fail_json( + "'idp_type' parameter must be provided when state is 'present'" + ) + if module.params["idp_type"]: + if module.params["idp_type"] == "ldap" and ( + not module.params["host"] + or not module.params["port"] + or not module.params["base_dn"] + or not module.params["search_attribute"] + ): + module.fail_json( + "'host', 'port', 'base_dn', 'search_attribute' must be provided when idp_type is 'ldap'" + ) + if module.params["idp_type"] == "saml" and ( + not module.params["idp_entityid"] + or not module.params["sp_entityid"] + or not module.params["sso_url"] + or not module.params["username_attribute"] + ): + module.fail_json( + "'idp_entityid', 'sp_entityid', 'sso_url', 'username_attribute' must be provided when idp_type is 'ldap'" + ) directory = user_directory._zapi.userdirectory.get( { - 'search': {'name': parameters['name']}, - 'selectProvisionMedia': 'extend', - 'selectProvisionGroups': 'extend' - }) - parameters['idp_type'] = str(zabbix_utils.helper_to_numeric_value(['', 'ldap', 'saml'], module.params['idp_type'])) - if parameters['idp_type'] == '1': + "search": {"name": parameters["name"]}, + "selectProvisionMedia": "extend", + "selectProvisionGroups": "extend", + } + ) + parameters["idp_type"] = str( + zabbix_utils.helper_to_numeric_value( + ["", "ldap", "saml"], module.params["idp_type"] + ) + ) + if parameters["idp_type"] == "1": # idp_type is ldap - parameters['search_filter'] = module.params['search_filter'] - elif parameters['idp_type'] == '2': + parameters["search_filter"] = module.params["search_filter"] + elif parameters["idp_type"] == "2": # idp_type is saml - for p in ['idp_entityid', 'sso_url', 'username_attribute', 'sp_entityid', 'slo_url', 'nameid_format']: + for p in [ + "idp_entityid", + "sso_url", + "username_attribute", + "sp_entityid", + "slo_url", + "nameid_format", + ]: # str parameters if module.params[p]: parameters[p] = module.params[p] - for p in ['scim_status', 'encrypt_nameid', 'encrypt_assertions', 'sign_messages', 'sign_assertions', - 'sign_authn_requests', 'sign_logout_requests', 'sign_logout_responses']: + for p in [ + "scim_status", + "encrypt_nameid", + "encrypt_assertions", + "sign_messages", + "sign_assertions", + "sign_authn_requests", + "sign_logout_requests", + "sign_logout_responses", + ]: # boolean parameters if module.params[p]: parameters[p] = str(int(module.params[p])) - if module.params['provision_status']: - parameters['provision_status'] = int(module.params['provision_status']) + if module.params["provision_status"]: + parameters["provision_status"] = int(module.params["provision_status"]) - if module.params['provision_media']: - if 'provision_status' not in parameters or not parameters['provision_status']: - module.fail_json('"provision_status" must be True to define "provision_media"') - parameters['provision_media'] = [] - for media in module.params['provision_media']: - media_type_name = media['mediatype'] - media_type_ids = user_directory._zapi.mediatype.get({'filter': {'name': media_type_name}}) + if module.params["provision_media"]: + if ( + "provision_status" not in parameters + or not parameters["provision_status"] + ): + module.fail_json( + "'provision_status' must be True to define 'provision_media'" + ) + parameters["provision_media"] = [] + for media in module.params["provision_media"]: + media_type_name = media["mediatype"] + media_type_ids = user_directory._zapi.mediatype.get( + {"filter": {"name": media_type_name}} + ) if not media_type_ids: - module.fail_json('Mediatype "%s" cannot be found' % media_type_name) - parameters['provision_media'].append( + module.fail_json("Mediatype '%s' cannot be found" % media_type_name) + parameters["provision_media"].append( { - 'name': media['name'], - 'mediatypeid': media_type_ids[0]['mediatypeid'], - 'attribute': media['attribute'] + "name": media["name"], + "mediatypeid": media_type_ids[0]["mediatypeid"], + "attribute": media["attribute"], } ) - if module.params['provision_groups']: - if 'provision_status' not in parameters or not parameters['provision_status']: - module.fail_json('"provision_status" must be True to define "provision_groups"') - parameters['provision_groups'] = [] - for group in module.params['provision_groups']: - role_name = group['role'] - role_ids = user_directory._zapi.role.get({'filter': {'name': role_name}}) + if module.params["provision_groups"]: + if ( + "provision_status" not in parameters + or not parameters["provision_status"] + ): + module.fail_json( + "'provision_status' must be True to define 'provision_groups'" + ) + parameters["provision_groups"] = [] + for group in module.params["provision_groups"]: + role_name = group["role"] + role_ids = user_directory._zapi.role.get( + {"filter": {"name": role_name}} + ) if not role_ids: - module.fail_json('Role "%s" cannot be found' % role_name) + module.fail_json("Role '%s' cannot be found" % role_name) user_groups = [] - for user_group in group['user_groups']: - ug_ids = user_directory._zapi.usergroup.get({'filter': {'name': user_group}}) + for user_group in group["user_groups"]: + ug_ids = user_directory._zapi.usergroup.get( + {"filter": {"name": user_group}} + ) if not ug_ids: - module.fail_json('User group "%s" cannot be found' % user_group) - user_groups.append({'usrgrpid': ug_ids[0]['usrgrpid']}) - parameters['provision_groups'].append( + module.fail_json("User group '%s' cannot be found" % user_group) + user_groups.append({"usrgrpid": ug_ids[0]["usrgrpid"]}) + parameters["provision_groups"].append( { - 'name': group['name'], - 'roleid': role_ids[0]['roleid'], - 'user_groups': user_groups + "name": group["name"], + "roleid": role_ids[0]["roleid"], + "user_groups": user_groups, } ) - for p in ['group_basedn', 'group_filter', 'group_member', 'group_membership', 'group_name', 'group_name', - 'user_lastname', 'user_ref_attr', 'user_username']: + for p in [ + "group_basedn", + "group_filter", + "group_member", + "group_membership", + "group_name", + "group_name", + "user_lastname", + "user_ref_attr", + "user_username", + ]: if module.params[p]: parameters[p] = module.params[p] if not directory: # No User Directory found with given name - if state == 'absent': - module.exit_json(changed=False, msg='User directory not found. Not changed: %s' % parameters['name']) + if state == "absent": + module.exit_json( + changed=False, + msg="User directory not found. Not changed: %s" % parameters["name"], + ) - elif state == 'present': + elif state == "present": if module.check_mode: module.exit_json(changed=True) else: user_directory._zapi.userdirectory.create(parameters) - module.exit_json(changed=True, result='Successfully added user directory %s' % parameters['name']) + module.exit_json( + changed=True, + result="Successfully added user directory %s" % parameters["name"], + ) else: # User Directory with given name exists - if state == 'absent': - user_directory._zapi.userdirectory.delete([directory[0]['userdirectoryid']]) - module.exit_json(changed=True, result='Successfully deleted user directory %s' % parameters['name']) - elif state == 'present': + if state == "absent": + if module.check_mode: + module.exit_json(changed=True) + user_directory._zapi.userdirectory.delete([directory[0]["userdirectoryid"]]) + module.exit_json( + changed=True, + result="Successfully deleted user directory %s" % parameters["name"], + ) + elif state == "present": diff_dict = {} - if 'provision_status' in directory[0]: + if "provision_status" in directory[0]: # Zabbix API returns provision_status as str we need it as int to correctly compare - directory[0]['provision_status'] = int(directory[0]['provision_status']) - if zabbix_utils.helper_compare_dictionaries(parameters, directory[0], diff_dict): - parameters['userdirectoryid'] = directory[0]['userdirectoryid'] + directory[0]["provision_status"] = int(directory[0]["provision_status"]) + if zabbix_utils.helper_compare_dictionaries( + parameters, directory[0], diff_dict + ): + parameters["userdirectoryid"] = directory[0]["userdirectoryid"] + if module.check_mode: + module.exit_json(changed=True) user_directory._zapi.userdirectory.update(parameters) - module.exit_json(changed=True, result='Successfully updated user directory %s' % parameters['name']) + module.exit_json( + changed=True, + result="Successfully updated user directory %s" + % parameters["name"], + ) else: - module.exit_json(changed=False, result='User directory %s is up-to date' % parameters['name']) + module.exit_json( + changed=False, + result="User directory %s is up-to date" % parameters["name"], + ) - module.exit_json(changed=False, result='User directory %s is up-to date' % parameters['name']) + module.exit_json( + changed=False, + result="User directory %s is up-to date" % parameters["name"], + ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_user_info.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_user_info.py index 8fd0323c4..c71479532 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_user_info.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_user_info.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = ''' +DOCUMENTATION = """ module: zabbix_user_info short_description: Gather information about Zabbix user author: @@ -16,32 +16,30 @@ author: description: - This module allows you to search for Zabbix user entries. requirements: - - "python >= 2.6" + - "python >= 3.9" options: username: description: - - Name of the user alias in Zabbix. - - username is the unique identifier used and cannot be updated using this module. - - alias should be replaced with username - aliases: [ alias ] + - User name. + - sername is the unique identifier used and cannot be updated using this module. required: true type: str extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = ''' +EXAMPLES = """ # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Get zabbix user info @@ -52,13 +50,13 @@ EXAMPLES = ''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user_info: username: example -''' +""" -RETURN = ''' +RETURN = """ zabbix_user: description: example returned: always @@ -103,11 +101,10 @@ zabbix_user: } ] } -''' +""" from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.compat.version import LooseVersion from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils @@ -117,13 +114,10 @@ class User(ZabbixBase): def get_user_by_user_username(self, username): zabbix_user = "" try: - data = {'output': 'extend', 'filter': {}, - 'getAccess': True, 'selectMedias': 'extend', - 'selectUsrgrps': 'extend'} - if LooseVersion(self._zbx_api_version) >= LooseVersion('5.4'): - data['filter']['username'] = username - else: - data['filter']['alias'] = username + data = {"output": "extend", "filter": {}, + "getAccess": True, "selectMedias": "extend", + "selectUsrgrps": "extend"} + data["filter"]["username"] = username zabbix_user = self._zapi.user.get(data) except Exception as e: @@ -141,20 +135,14 @@ class User(ZabbixBase): def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - username=dict(type='str', required=True, aliases=['alias']), + username=dict(type="str", required=True), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - username = module.params['username'] + username = module.params["username"] user = User(module) zabbix_user = user.get_user_by_user_username(username) diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_user_role.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_user_role.py index 596ef5570..3495f39e1 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_user_role.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_user_role.py @@ -8,7 +8,7 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" module: zabbix_user_role short_description: Adds or removes zabbix roles author: @@ -16,15 +16,15 @@ author: description: - This module adds or removes zabbix roles requirements: - - "python >= 2.6" + - "python >= 3.9" options: state: description: - State of the user_role. - On C(present), it will create if user_role does not exist or update the user_role if the associated data is different. - On C(absent) will remove a user_role if it exists. - default: 'present' - choices: ['present', 'absent'] + default: "present" + choices: ["present", "absent"] type: str required: false name: @@ -47,19 +47,19 @@ options: required: false extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 # Create user role Operators with ui elements monitoring.hosts @@ -73,7 +73,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_user_role: state: present @@ -86,21 +86,21 @@ EXAMPLES = r''' status: 0 - name: "monitoring.maps" status: 1 -''' +""" -RETURN = r''' +RETURN = r""" # Return values msg: description: The result of the action type: str returned: always - sample: 'No action' + sample: "No action" changed: description: The consequence of the action type: bool returned: always sample: false -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -135,7 +135,7 @@ class UserRole(ZabbixBase): verdict = True for rule, value in inp.items(): if not isinstance(value, list): - verdict = verdict and self.__find_val(out.get(rule, ''), value) + verdict = verdict and self.__find_val(out.get(rule, ""), value) else: if len(value): if not isinstance(value[0], dict): @@ -162,10 +162,10 @@ def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - state=dict(type='str', required=False, default='present', choices=['present', 'absent']), - name=dict(type='str', required=True), - type=dict(type='str', required=False, choices=["User", "Admin", "Super Admin"], default='User'), - rules=dict(type='dict', required=False, default={}), + state=dict(type="str", required=False, default="present", choices=["present", "absent"]), + name=dict(type="str", required=True), + type=dict(type="str", required=False, choices=["User", "Admin", "Super Admin"], default="User"), + rules=dict(type="dict", required=False, default={}), )) # the AnsibleModule object @@ -174,19 +174,12 @@ def main(): supports_check_mode=False ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection ' - 'and will be removed in the next release' % p) - - state = module.params['state'] - name = module.params['name'] + state = module.params["state"] + name = module.params["name"] type = zabbix_utils.helper_to_numeric_value( - ['', 'user', 'admin', 'super admin'], module.params['type'].lower() + ["", "user", "admin", "super admin"], module.params["type"].lower() ) - rules = module.params['rules'] + rules = module.params["rules"] user_role = UserRole(module) @@ -194,19 +187,19 @@ def main(): if result: if len(result) == 1: role = result[0] - if role['readonly'] != 1: - roleid = role['roleid'] - if state == 'absent': + if role["readonly"] != 1: + roleid = role["roleid"] + if state == "absent": result = user_role._zapi.role.delete([f"{roleid}"]) changed = True msg = "Role deleted" else: - if not user_role.is_part_of(rules, role['rules']): + if not user_role.is_part_of(rules, role["rules"]): result = user_role._zapi.role.update({"roleid": roleid, "rules": rules}) changed = True msg = "Role updated" else: - module.fail_json(msg='Too many role matches') + module.fail_json(msg="Too many role matches") else: user_role._zapi.role.create({ "name": name, @@ -219,5 +212,5 @@ def main(): module.exit_json(msg=msg, changed=changed) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_usergroup.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_usergroup.py index b2a341472..14539d932 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_usergroup.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_usergroup.py @@ -5,9 +5,10 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_usergroup short_description: Create/delete/update Zabbix user groups @@ -18,7 +19,7 @@ description: author: - "Tobias Birkefeld (@tcraxs)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: name: description: @@ -126,13 +127,13 @@ options: - Tag name. required: false type: str - default: '' + default: "" value: description: - Tag value. required: false type: str - default: '' + default: "" userdirectory: description: - Authentication user directory when gui_access set to LDAP or System default. @@ -148,23 +149,22 @@ options: type: str default: "present" choices: [ "present", "absent" ] -notes: - - Only Zabbix >= 4.0 is supported. + extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 # Base create user group example @@ -176,10 +176,11 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME + userdirectory: LDAP infra 1 state: present # Base create user group with selected user directory for LDAP authentication @@ -191,7 +192,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME @@ -207,7 +208,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME @@ -222,7 +223,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME @@ -242,7 +243,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME @@ -267,7 +268,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME @@ -289,35 +290,35 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_usergroup: name: ACME state: absent -''' +""" -RETURN = r''' +RETURN = r""" state: description: User group state at the end of execution. returned: on success type: str - sample: 'present' + sample: "present" usergroup: description: User group name. returned: on success type: str - sample: 'ACME' + sample: "ACME" usrgrpid: description: User group id, if created, changed or deleted. returned: on success type: str - sample: '42' + sample: "42" msg: description: The result of the operation returned: always type: str - sample: 'User group created: ACME, ID: 42' -''' + sample: "User group created: ACME, ID: 42" +""" from ansible.module_utils.basic import AnsibleModule @@ -341,16 +342,15 @@ class Rights(ZabbixBase): host group matching host group name. """ try: - _hostgroup = self._zapi.hostgroup.get({ - 'output': 'extend', - 'filter': {'name': [name]} - }) + _hostgroup = self._zapi.hostgroup.get( + {"output": "extend", "filter": {"name": [name]}} + ) if len(_hostgroup) < 1: - self._module.fail_json(msg='Host group not found: %s' % name) + self._module.fail_json(msg="Host group not found: %s" % name) else: return _hostgroup[0] except Exception as e: - self._module.fail_json(msg='Failed to get host group "%s": %s' % (name, e)) + self._module.fail_json(msg="Failed to get host group '%s': %s" % (name, e)) def construct_the_data(self, _rights): """Construct the user defined rights to fit the Zabbix API requirements @@ -366,13 +366,12 @@ class Rights(ZabbixBase): constructed_data = [] for right in _rights: constructed_right = { - 'id': self.get_hostgroup_by_hostgroup_name(right.get('host_group'))['groupid'], - 'permission': zabbix_utils.helper_to_numeric_value([ - 'denied', - None, - 'read-only', - 'read-write'], right.get('permission') - ) + "id": self.get_hostgroup_by_hostgroup_name(right.get("host_group"))[ + "groupid" + ], + "permission": zabbix_utils.helper_to_numeric_value( + ["denied", None, "read-only", "read-write"], right.get("permission") + ), } constructed_data.append(constructed_right) return zabbix_utils.helper_cleanup_data(constructed_data) @@ -394,15 +393,15 @@ class HostgroupRights(ZabbixBase): """ try: _hostgroup = self._zapi.hostgroup.get({ - 'output': 'extend', - 'filter': {'name': [name]} + "output": "extend", + "filter": {"name": [name]} }) if len(_hostgroup) < 1: - self._module.fail_json(msg='Host group not found: %s' % name) + self._module.fail_json(msg="Host group not found: %s" % name) else: return _hostgroup[0] except Exception as e: - self._module.fail_json(msg='Failed to get host group "%s": %s' % (name, e)) + self._module.fail_json(msg="Failed to get host group '%s': %s" % (name, e)) def construct_the_data(self, _rights): """Construct the user defined host group rights to fit the Zabbix API requirements @@ -418,12 +417,12 @@ class HostgroupRights(ZabbixBase): constructed_data = [] for right in _rights: constructed_right = { - 'id': self.get_hostgroup_by_hostgroup_name(right.get('host_group'))['groupid'], - 'permission': zabbix_utils.helper_to_numeric_value([ - 'denied', + "id": self.get_hostgroup_by_hostgroup_name(right.get("host_group"))["groupid"], + "permission": zabbix_utils.helper_to_numeric_value([ + "denied", None, - 'read-only', - 'read-write'], right.get('permission') + "read-only", + "read-write"], right.get("permission") ) } constructed_data.append(constructed_right) @@ -446,15 +445,15 @@ class TemplategroupRights(ZabbixBase): """ try: _templategroup = self._zapi.templategroup.get({ - 'output': 'extend', - 'filter': {'name': [name]} + "output": "extend", + "filter": {"name": [name]} }) if len(_templategroup) < 1: - self._module.fail_json(msg='Template group not found: %s' % name) + self._module.fail_json(msg="Template group not found: %s" % name) else: return _templategroup[0] except Exception as e: - self._module.fail_json(msg='Failed to get template group "%s": %s' % (name, e)) + self._module.fail_json(msg="Failed to get template group '%s': %s" % (name, e)) def construct_the_data(self, _rights): """Construct the user defined template rights to fit the Zabbix API requirements @@ -470,12 +469,12 @@ class TemplategroupRights(ZabbixBase): constructed_data = [] for right in _rights: constructed_right = { - 'id': self.get_templategroup_by_templategroup_name(right.get('template_group'))['groupid'], - 'permission': zabbix_utils.helper_to_numeric_value([ - 'denied', + "id": self.get_templategroup_by_templategroup_name(right.get("template_group"))["groupid"], + "permission": zabbix_utils.helper_to_numeric_value([ + "denied", None, - 'read-only', - 'read-write'], right.get('permission') + "read-only", + "read-write"], right.get("permission") ) } constructed_data.append(constructed_right) @@ -501,9 +500,11 @@ class TagFilters(Rights): constructed_data = [] for tag_filter in _tag_filters: constructed_tag_filter = { - 'groupid': self.get_hostgroup_by_hostgroup_name(tag_filter.get('host_group'))['groupid'], - 'tag': tag_filter.get('tag'), - 'value': tag_filter.get('value') + "groupid": self.get_hostgroup_by_hostgroup_name( + tag_filter.get("host_group") + )["groupid"], + "tag": tag_filter.get("tag"), + "value": tag_filter.get("value"), } constructed_data.append(constructed_tag_filter) return zabbix_utils.helper_cleanup_data(constructed_data) @@ -520,46 +521,50 @@ class UserGroup(ZabbixBase): dict: dictionary of specified parameters """ _params = { - 'name': kwargs['name'], - 'gui_access': zabbix_utils.helper_to_numeric_value([ - 'default', - 'internal', - 'LDAP', - 'disable'], kwargs['gui_access'] + "name": kwargs["name"], + "gui_access": zabbix_utils.helper_to_numeric_value( + ["default", "internal", "LDAP", "disable"], kwargs["gui_access"] ), - 'debug_mode': zabbix_utils.helper_to_numeric_value([ - 'disabled', - 'enabled'], kwargs['debug_mode'] + "debug_mode": zabbix_utils.helper_to_numeric_value( + ["disabled", "enabled"], kwargs["debug_mode"] ), - 'users_status': zabbix_utils.helper_to_numeric_value([ - 'enabled', - 'disabled'], kwargs['status'] + "users_status": zabbix_utils.helper_to_numeric_value( + ["enabled", "disabled"], kwargs["status"] ), - 'tag_filters': kwargs['tag_filters'] + "tag_filters": kwargs["tag_filters"], } - if LooseVersion(self._zbx_api_version) < LooseVersion('6.2'): - _params['rights'] = kwargs['rights'] + if LooseVersion(self._zbx_api_version) < LooseVersion("6.2"): + _params["rights"] = kwargs["rights"] else: - _params['hostgroup_rights'] = kwargs['hostgroup_rights'] - _params['templategroup_rights'] = kwargs['templategroup_rights'] + _params["hostgroup_rights"] = kwargs["hostgroup_rights"] + _params["templategroup_rights"] = kwargs["templategroup_rights"] - if kwargs['userdirectory']: + if kwargs["userdirectory"]: try: - if LooseVersion(self._zbx_api_version) <= LooseVersion('6.2'): - _userdir = self._zapi.userdirectory.get({ - 'output': 'extend', - 'filter': {'name': [kwargs['userdirectory']]} - }) + if LooseVersion(self._zbx_api_version) <= LooseVersion("6.2"): + _userdir = self._zapi.userdirectory.get( + { + "output": "extend", + "filter": {"name": [kwargs["userdirectory"]]}, + } + ) else: - _userdir = self._zapi.userdirectory.get({ - 'output': 'extend', - 'search': {'name': [kwargs['userdirectory']]} - }) + _userdir = self._zapi.userdirectory.get( + { + "output": "extend", + "search": {"name": [kwargs["userdirectory"]]}, + } + ) except Exception as e: - self._module.fail_json(msg='Failed to get user directory "%s": %s' % (kwargs['userdirectory'], e)) + self._module.fail_json( + msg="Failed to get user directory '%s': %s" + % (kwargs["userdirectory"], e) + ) if len(_userdir) == 0: - self._module.fail_json(msg='User directory "%s" not found' % kwargs['userdirectory']) - _params['userdirectoryid'] = _userdir[0]['userdirectoryid'] + self._module.fail_json( + msg="User directory '%s' not found" % kwargs["userdirectory"] + ) + _params["userdirectoryid"] = _userdir[0]["userdirectoryid"] return _params @@ -573,14 +578,15 @@ class UserGroup(ZabbixBase): The return value. True for success, False otherwise. """ try: - _usergroup = self._zapi.usergroup.get({ - 'output': 'extend', - 'filter': {'name': [name]} - }) + _usergroup = self._zapi.usergroup.get( + {"output": "extend", "filter": {"name": [name]}} + ) if len(_usergroup) > 0: return _usergroup except Exception as e: - self._module.fail_json(msg='Failed to check if user group "%s" exists: %s' % (name, e)) + self._module.fail_json( + msg="Failed to check if user group '%s' exists: %s" % (name, e) + ) def get_usergroup_by_usergroup_name(self, name): """Get user group by user group name. @@ -592,28 +598,32 @@ class UserGroup(ZabbixBase): User group matching user group name. """ try: - if LooseVersion(self._zbx_api_version) < LooseVersion('6.2'): - _usergroup = self._zapi.usergroup.get({ - 'output': 'extend', - 'selectTagFilters': 'extend', - 'selectRights': 'extend', - 'filter': {'name': [name]} - }) + if LooseVersion(self._zbx_api_version) < LooseVersion("6.2"): + _usergroup = self._zapi.usergroup.get( + { + "output": "extend", + "selectTagFilters": "extend", + "selectRights": "extend", + "filter": {"name": [name]}, + } + ) else: - _usergroup = self._zapi.usergroup.get({ - 'output': 'extend', - 'selectTagFilters': 'extend', - 'selectHostGroupRights': 'extend', - 'selectTemplateGroupRights': 'extend', - 'filter': {'name': [name]} - }) + _usergroup = self._zapi.usergroup.get( + { + "output": "extend", + "selectTagFilters": "extend", + "selectHostGroupRights": "extend", + "selectTemplateGroupRights": "extend", + "filter": {"name": [name]}, + } + ) if len(_usergroup) < 1: - self._module.fail_json(msg='User group not found: %s' % name) + self._module.fail_json(msg="User group not found: %s" % name) else: return _usergroup[0] except Exception as e: - self._module.fail_json(msg='Failed to get user group "%s": %s' % (name, e)) + self._module.fail_json(msg="Failed to get user group '%s': %s" % (name, e)) def check_difference(self, **kwargs): """Check difference between user group and user specified parameters. @@ -624,10 +634,16 @@ class UserGroup(ZabbixBase): Returns: dict: dictionary of differences """ - existing_usergroup = zabbix_utils.helper_convert_unicode_to_str(self.get_usergroup_by_usergroup_name(kwargs['name'])) - parameters = zabbix_utils.helper_convert_unicode_to_str(self._construct_parameters(**kwargs)) + existing_usergroup = zabbix_utils.helper_convert_unicode_to_str( + self.get_usergroup_by_usergroup_name(kwargs["name"]) + ) + parameters = zabbix_utils.helper_convert_unicode_to_str( + self._construct_parameters(**kwargs) + ) change_parameters = {} - _diff = zabbix_utils.helper_compare_dictionaries(parameters, existing_usergroup, change_parameters) + _diff = zabbix_utils.helper_compare_dictionaries( + parameters, existing_usergroup, change_parameters + ) return _diff def update(self, **kwargs): @@ -644,7 +660,9 @@ class UserGroup(ZabbixBase): self._module.exit_json(changed=True) return self._zapi.usergroup.update(kwargs) except Exception as e: - self._module.fail_json(msg='Failed to update user group "%s": %s' % (kwargs['usrgrpid'], e)) + self._module.fail_json( + msg="Failed to update user group '%s': %s" % (kwargs["usrgrpid"], e) + ) def add(self, **kwargs): """Add user group. @@ -660,9 +678,11 @@ class UserGroup(ZabbixBase): self._module.exit_json(changed=True) parameters = self._construct_parameters(**kwargs) usergroup = self._zapi.usergroup.create(parameters) - return usergroup['usrgrpids'][0] + return usergroup["usrgrpids"][0] except Exception as e: - self._module.fail_json(msg='Failed to create user group "%s": %s' % (kwargs['name'], e)) + self._module.fail_json( + msg="Failed to create user group '%s': %s" % (kwargs["name"], e) + ) def delete(self, usrgrpid): """Delete user group. @@ -679,62 +699,102 @@ class UserGroup(ZabbixBase): else: return self._zapi.usergroup.delete([usrgrpid]) except Exception as e: - self._module.fail_json(msg='Failed to delete user group "%s": %s' % (usrgrpid, e)) + self._module.fail_json( + msg="Failed to delete user group '%s': %s" % (usrgrpid, e) + ) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update( - name=dict(type='str', required=True, aliases=['user_group']), - gui_access=dict(type='str', required=False, default='default', choices=['default', 'internal', 'LDAP', 'disable']), - debug_mode=dict(type='str', required=False, default='disabled', choices=['disabled', 'enabled']), - status=dict(type='str', required=False, default='enabled', choices=['enabled', 'disabled']), - rights=dict(type='list', elements='dict', required=False, options=dict( - host_group=dict(type='str', required=True), - permission=dict(type='str', required=True, choices=['denied', 'read-only', 'read-write']) - )), - hostgroup_rights=dict(type='list', elements='dict', required=False, options=dict( - host_group=dict(type='str', required=True), - permission=dict(type='str', required=True, choices=['denied', 'read-only', 'read-write']) - )), - templategroup_rights=dict(type='list', elements='dict', required=False, options=dict( - template_group=dict(type='str', required=True), - permission=dict(type='str', required=True, choices=['denied', 'read-only', 'read-write']) - )), - tag_filters=dict(type='list', elements='dict', required=False, options=dict( - host_group=dict(type='str', required=True), - tag=dict(type='str', default=''), - value=dict(type='str', default='') - )), - userdirectory=dict(type='str', required=False), - state=dict(type='str', default='present', choices=['present', 'absent']) - ) - - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True + name=dict(type="str", required=True, aliases=["user_group"]), + gui_access=dict( + type="str", + required=False, + default="default", + choices=["default", "internal", "LDAP", "disable"], + ), + debug_mode=dict( + type="str", + required=False, + default="disabled", + choices=["disabled", "enabled"], + ), + status=dict( + type="str", + required=False, + default="enabled", + choices=["enabled", "disabled"], + ), + rights=dict( + type="list", + elements="dict", + required=False, + options=dict( + host_group=dict(type="str", required=True), + permission=dict( + type="str", + required=True, + choices=["denied", "read-only", "read-write"], + ), + ), + ), + hostgroup_rights=dict( + type="list", + elements="dict", + required=False, + options=dict( + host_group=dict(type="str", required=True), + permission=dict( + type="str", + required=True, + choices=["denied", "read-only", "read-write"], + ), + ), + ), + templategroup_rights=dict( + type="list", + elements="dict", + required=False, + options=dict( + template_group=dict(type="str", required=True), + permission=dict( + type="str", + required=True, + choices=["denied", "read-only", "read-write"], + ), + ), + ), + tag_filters=dict( + type="list", + elements="dict", + required=False, + options=dict( + host_group=dict(type="str", required=True), + tag=dict(type="str", default=""), + value=dict(type="str", default=""), + ), + ), + userdirectory=dict(type="str", required=False), + state=dict(type="str", default="present", choices=["present", "absent"]), ) - zabbix_utils.require_creds_params(module) + module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) - - name = module.params['name'] - gui_access = module.params['gui_access'] - debug_mode = module.params['debug_mode'] - status = module.params['status'] - rights = module.params['rights'] - hostgroup_rights = module.params['hostgroup_rights'] - templategroup_rights = module.params['templategroup_rights'] - tag_filters = module.params['tag_filters'] - userdirectory = module.params['userdirectory'] - state = module.params['state'] + name = module.params["name"] + gui_access = module.params["gui_access"] + debug_mode = module.params["debug_mode"] + status = module.params["status"] + rights = module.params["rights"] + hostgroup_rights = module.params["hostgroup_rights"] + templategroup_rights = module.params["templategroup_rights"] + tag_filters = module.params["tag_filters"] + userdirectory = module.params["userdirectory"] + state = module.params["state"] userGroup = UserGroup(module) zbx = userGroup._zapi - if LooseVersion(userGroup._zbx_api_version) < LooseVersion('6.2'): + if LooseVersion(userGroup._zbx_api_version) < LooseVersion("6.2"): rgts = Rights(module, zbx) else: hostgroup_rgts = HostgroupRights(module, zbx) @@ -744,12 +804,18 @@ def main(): usergroup_exists = userGroup.check_if_usergroup_exists(name) if usergroup_exists: - usrgrpid = userGroup.get_usergroup_by_usergroup_name(name)['usrgrpid'] - if state == 'absent': + usrgrpid = userGroup.get_usergroup_by_usergroup_name(name)["usrgrpid"] + if state == "absent": userGroup.delete(usrgrpid) - module.exit_json(changed=True, state=state, usergroup=name, usrgrpid=usrgrpid, msg='User group deleted: %s, ID: %s' % (name, usrgrpid)) + module.exit_json( + changed=True, + state=state, + usergroup=name, + usrgrpid=usrgrpid, + msg="User group deleted: %s, ID: %s" % (name, usrgrpid), + ) else: - if LooseVersion(userGroup._zbx_api_version) < LooseVersion('6.2'): + if LooseVersion(userGroup._zbx_api_version) < LooseVersion("6.2"): difference = userGroup.check_difference( usrgrpid=usrgrpid, name=name, @@ -757,7 +823,7 @@ def main(): debug_mode=debug_mode, status=status, rights=rgts.construct_the_data(rights), - tag_filters=tgflts.construct_the_data(tag_filters) + tag_filters=tgflts.construct_the_data(tag_filters), ) else: difference = userGroup.check_difference( @@ -766,31 +832,49 @@ def main(): gui_access=gui_access, debug_mode=debug_mode, status=status, - hostgroup_rights=hostgroup_rgts.construct_the_data(hostgroup_rights), - templategroup_rights=templategroup_rgts.construct_the_data(templategroup_rights), + hostgroup_rights=hostgroup_rgts.construct_the_data( + hostgroup_rights + ), + templategroup_rights=templategroup_rgts.construct_the_data( + templategroup_rights + ), tag_filters=tgflts.construct_the_data(tag_filters), - userdirectory=userdirectory + userdirectory=userdirectory, ) if difference == {}: - module.exit_json(changed=False, state=state, usergroup=name, usrgrpid=usrgrpid, msg='User group is up to date: %s' % name) + module.exit_json( + changed=False, + state=state, + usergroup=name, + usrgrpid=usrgrpid, + msg="User group is up to date: %s" % name, + ) else: - userGroup.update( + userGroup.update(usrgrpid=usrgrpid, **difference) + module.exit_json( + changed=True, + state=state, + usergroup=name, usrgrpid=usrgrpid, - **difference + msg="User group updated: %s, ID: %s" % (name, usrgrpid), ) - module.exit_json(changed=True, state=state, usergroup=name, usrgrpid=usrgrpid, msg='User group updated: %s, ID: %s' % (name, usrgrpid)) else: - if state == 'absent': - module.exit_json(changed=False, state=state, usergroup=name, msg='User group %s does not exists, nothing to delete' % name) + if state == "absent": + module.exit_json( + changed=False, + state=state, + usergroup=name, + msg="User group %s does not exists, nothing to delete" % name, + ) else: - if LooseVersion(userGroup._zbx_api_version) < LooseVersion('6.2'): + if LooseVersion(userGroup._zbx_api_version) < LooseVersion("6.2"): usrgrpid = userGroup.add( name=name, gui_access=gui_access, debug_mode=debug_mode, status=status, rights=rgts.construct_the_data(rights), - tag_filters=tgflts.construct_the_data(tag_filters) + tag_filters=tgflts.construct_the_data(tag_filters), ) else: usrgrpid = userGroup.add( @@ -798,13 +882,23 @@ def main(): gui_access=gui_access, debug_mode=debug_mode, status=status, - hostgroup_rights=hostgroup_rgts.construct_the_data(hostgroup_rights), - templategroup_rights=templategroup_rgts.construct_the_data(templategroup_rights), + hostgroup_rights=hostgroup_rgts.construct_the_data( + hostgroup_rights + ), + templategroup_rights=templategroup_rgts.construct_the_data( + templategroup_rights + ), tag_filters=tgflts.construct_the_data(tag_filters), - userdirectory=userdirectory + userdirectory=userdirectory, ) - module.exit_json(changed=True, state=state, usergroup=name, usrgrpid=usrgrpid, msg='User group created: %s, ID: %s' % (name, usrgrpid)) + module.exit_json( + changed=True, + state=state, + usergroup=name, + usrgrpid=usrgrpid, + msg="User group created: %s, ID: %s" % (name, usrgrpid), + ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/plugins/modules/zabbix_valuemap.py b/ansible_collections/community/zabbix/plugins/modules/zabbix_valuemap.py index 196f8ff7e..3d9a64954 100644 --- a/ansible_collections/community/zabbix/plugins/modules/zabbix_valuemap.py +++ b/ansible_collections/community/zabbix/plugins/modules/zabbix_valuemap.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function __metaclass__ = type -DOCUMENTATION = r''' +DOCUMENTATION = r""" --- module: zabbix_valuemap short_description: Create/update/delete Zabbix value maps @@ -17,56 +17,56 @@ description: author: - "Ruben Tsirunyan (@rubentsirunyan)" requirements: - - "python >= 2.6" + - "python >= 3.9" options: name: - type: 'str' + type: "str" description: - Name of the value map. required: true state: - type: 'str' + type: "str" description: - State of the value map. - On C(present), it will create a value map if it does not exist or update the value map if the associated data is different. - On C(absent), it will remove the value map if it exists. - choices: ['present', 'absent'] - default: 'present' + choices: ["present", "absent"] + default: "present" mappings: - type: 'list' + type: "list" elements: dict description: - List of value mappings for the value map. - Required when I(state=present). suboptions: value: - type: 'str' + type: "str" description: Original value. required: true map_to: - type: 'str' + type: "str" description: Value to which the original value is mapped to. required: true extends_documentation_fragment: - community.zabbix.zabbix -''' +""" -RETURN = r''' -''' +RETURN = r""" +""" -EXAMPLES = r''' +EXAMPLES = r""" # If you want to use Username and Password to be authenticated by Zabbix Server - name: Set credentials to access Zabbix Server API - set_fact: + ansible.builtin.set_fact: ansible_user: Admin ansible_httpapi_pass: zabbix # If you want to use API token to be authenticated by Zabbix Server # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens - name: Set API token - set_fact: + ansible.builtin.set_fact: ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 - name: Create a value map @@ -77,7 +77,7 @@ EXAMPLES = r''' ansible_httpapi_port: 443 ansible_httpapi_use_ssl: true ansible_httpapi_validate_certs: false - ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu + ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu ansible_host: zabbix-example-fqdn.org community.zabbix.zabbix_valuemap: name: Numbers @@ -87,7 +87,7 @@ EXAMPLES = r''' - value: 2 map_to: two state: present -''' +""" from ansible.module_utils.basic import AnsibleModule @@ -104,31 +104,31 @@ def construct_parameters(**kwargs): Returns: A dictionary of arguments in a format that is understandable by Zabbix API. """ - if kwargs['mappings'] is None: + if kwargs["mappings"] is None: return dict( - name=kwargs['name'] + name=kwargs["name"] ) return dict( - name=kwargs['name'], + name=kwargs["name"], mappings=[ dict( - value=mapping['value'], - newvalue=mapping['map_to'] - ) for mapping in kwargs['mappings'] + value=mapping["value"], + newvalue=mapping["map_to"] + ) for mapping in kwargs["mappings"] ] ) def diff(existing, new): - """Constructs the diff for Ansible's --diff option. + """Constructs the diff for Ansible"s --diff option. Args: existing (dict): Existing valuemap data. new (dict): New valuemap data. Returns: - A dictionary like {'before': existing, 'after': new} + A dictionary like {"before": existing, "after": new} with filtered empty values. """ before = {} @@ -136,11 +136,11 @@ def diff(existing, new): for key in new: before[key] = existing[key] if new[key] is None: - after[key] = '' + after[key] = "" else: after[key] = new[key] - return {'before': before, 'after': after} + return {"before": before, "after": after} def get_update_params(existing_valuemap, **kwargs): @@ -158,8 +158,8 @@ def get_update_params(existing_valuemap, **kwargs): """ params_to_update = {} - if sorted(existing_valuemap['mappings'], key=lambda k: k['value']) != sorted(kwargs['mappings'], key=lambda k: k['value']): - params_to_update['mappings'] = kwargs['mappings'] + if sorted(existing_valuemap["mappings"], key=lambda k: k["value"]) != sorted(kwargs["mappings"], key=lambda k: k["value"]): + params_to_update["mappings"] = kwargs["mappings"] return params_to_update, diff(existing_valuemap, kwargs) @@ -176,9 +176,9 @@ class ValuemapModule(ZabbixBase): """ try: valuemap_list = self._zapi.valuemap.get({ - 'output': 'extend', - 'selectMappings': 'extend', - 'filter': {'name': [name]} + "output": "extend", + "selectMappings": "extend", + "filter": {"name": [name]} }) if len(valuemap_list) < 1: return False, None @@ -197,26 +197,26 @@ class ValuemapModule(ZabbixBase): try: self._zapi.valuemap.update(kwargs) except Exception as e: - self._module.fail_json(msg="Failed to update valuemap '{_id}': {e}".format(_id=kwargs['valuemapid'], e=e)) + self._module.fail_json(msg="Failed to update valuemap '{_id}': {e}".format(_id=kwargs["valuemapid"], e=e)) def create(self, **kwargs): try: self._zapi.valuemap.create(kwargs) except Exception as e: - self._module.fail_json(msg="Failed to create valuemap '{name}': {e}".format(name=kwargs['description'], e=e)) + self._module.fail_json(msg="Failed to create valuemap '{name}': {e}".format(name=kwargs["description"], e=e)) def main(): argument_spec = zabbix_utils.zabbix_common_argument_spec() argument_spec.update(dict( - name=dict(type='str', required=True), - state=dict(type='str', default='present', choices=['present', 'absent']), + name=dict(type="str", required=True), + state=dict(type="str", default="present", choices=["present", "absent"]), mappings=dict( - type='list', - elements='dict', + type="list", + elements="dict", options=dict( - value=dict(type='str', required=True), - map_to=dict(type='str', required=True) + value=dict(type="str", required=True), + map_to=dict(type="str", required=True) ) ) )) @@ -224,20 +224,15 @@ def main(): argument_spec=argument_spec, supports_check_mode=True, required_if=[ - ['state', 'present', ['mappings']], + ["state", "present", ["mappings"]], ] ) - zabbix_utils.require_creds_params(module) - - for p in ['server_url', 'login_user', 'login_password', 'timeout', 'validate_certs']: - if p in module.params and not module.params[p] is None: - module.warn('Option "%s" is deprecated with the move to httpapi connection and will be removed in the next release' % p) vm = ValuemapModule(module) - name = module.params['name'] - state = module.params['state'] - mappings = module.params['mappings'] + name = module.params["name"] + state = module.params["state"] + mappings = module.params["mappings"] valuemap_exists, valuemap_object = vm.check_if_valuemap_exists(name) @@ -247,8 +242,8 @@ def main(): ) if valuemap_exists: - valuemap_id = valuemap_object['valuemapid'] - if state == 'absent': + valuemap_id = valuemap_object["valuemapid"] + if state == "absent": if module.check_mode: module.exit_json( changed=True, @@ -313,5 +308,5 @@ def main(): ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/README.md b/ansible_collections/community/zabbix/roles/zabbix_agent/README.md index f3fe06c9d..aa73fab3a 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/README.md +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/README.md @@ -44,15 +44,10 @@ This role will work on the following operating systems: * Red Hat - * Fedora * Debian * Ubuntu - * opensuse * Windows (Best effort) - * macOS - -So, you'll need one of those operating systems.. :-) -Please send Pull Requests or suggestions when you want to use this role for other Operating systems. + * macOS (Best effort) ## Ansible 2.10 and higher @@ -62,7 +57,7 @@ With the release of Ansible 2.10, modules have been moved into collections. Wit ansible-galaxy collection install ansible.posix ansible-galaxy collection install community.general ``` -If you are willing to create host_groups and hosts in Zabbix via API as a part of this role execution then you need to install `ansible.netcommon` collection too: +If you are wanting to create host_groups and hosts in Zabbix via API as a part of this role execution then you need to install `ansible.netcommon` collection too: ``` ansible-galaxy collection install ansible.netcommon @@ -95,24 +90,18 @@ To successfully complete the install the role requires `python-netaddr` on the c See the following list of supported Operating systems with the Zabbix releases: -| Zabbix | 6.4 | 6.2 | 6.0 | 5.4 | 5.2 | 5.0 (LTS)| 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----|-----|-----|----------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | V | V | V | V | V | V | V | V | V | -| Red Hat Fam 6 | V | V | V | V | V | V | | | V | -| Red Hat Fam 5 | | | V | V | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | V | V | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | V | V | V | V | V | V | V | V | | -| Ubuntu 14.04 trusty | V | V | V | V | V | V | V | V | V | -| Debian 10 buster | V | V | V | V | V | V | V | | | -| Debian 9 stretch | V | V | | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Red Hat Fam 7 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | V | V | V | +| Debian 12 bookworm | V | V | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | V | V | V | + # Getting started @@ -124,7 +113,7 @@ In order to get the Zabbix Agent running, you'll have to define the following pr * `zabbix_agent(2)_server` * `zabbix_agent(2)_serveractive` (When using active checks) -The `zabbix_agent_version` is optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_agent_version: 4.0`, `zabbix_agent_version: 3.4` or `zabbix_agent_version: 2.2`. +The `zabbix_agent_version` is optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_agent_version: 6.0`. The `zabbix_agent(2)_server` (and `zabbix_agent(2)_serveractive`) should contain the ip or fqdn of the host running the Zabbix Server. @@ -140,16 +129,13 @@ The following is an overview of all available configuration default for this rol ### Overall Zabbix -* `zabbix_agent_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. +* `zabbix_agent_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.4, 6.2, or 6.0 * `zabbix_agent_version_minor`: When you want to specify a minor version to be installed. Is also used for `zabbix_sender` and `zabbix_get`. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. +* `zabbix_agent_disable_repo`: A list of repos to disable during install. Default `epel`. +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_agent_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### SElinux @@ -158,7 +144,7 @@ The following is an overview of all available configuration default for this rol ### Zabbix Agent * `zabbix_agent_ip`: The IP address of the host. When not provided, it will be determined via the `ansible_default_ipv4` fact. -* `zabbix_agent2`: Default: `False`. When you want to install the `Zabbix Agent2` instead of the "old" `Zabbix Agent`. +* `zabbix_agent2`: Default: `False`. When you want to install the `Zabbix Agent2` instead of the "old" `Zabbix Agent`.zabbix_agent_version * `zabbix_agent_listeninterface`: Interface zabbix-agent listens on. Leave blank for all. * `zabbix_agent_package_remove`: If `zabbix_agent2: True` and you want to remove the old installation. Default: `False`. * `zabbix_agent_package`: The name of the zabbix-agent package. Default: `zabbix-agent`. In case for EPEL, it is automatically renamed. @@ -174,7 +160,6 @@ The following is an overview of all available configuration default for this rol * `zabbix_agent_userparameters_scripts_src`: indicates the relative path (from `files/`) where userparameter scripts are searched * `zabbix_agent_runas_user`: Drop privileges to a specific, existing user on the system. Only has effect if run as 'root' and AllowRoot is disabled. * `zabbix_agent_become_on_localhost`: Default: `True`. Set to `False` if you don't need to elevate privileges on localhost to install packages locally with pip. -* `zabbix_install_pip_packages`: Default: `True`. Set to `False` if you don't want to install the required pip packages. Useful when you control your environment completely. * `zabbix_agent_apt_priority`: Add a weight (`Pin-Priority`) for the APT repository. * `zabbix_agent_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. * `zabbix_agent_dont_detect_ip`: Default `false`. When set to `true`, it won't detect available ip addresses on the host and no need for the Python module `netaddr` to be installed. @@ -193,6 +178,7 @@ Otherwise it just for the Zabbix Agent or for the Zabbix Agent 2. * `zabbix_agent(2)_pidfile`: name of pid file. * `zabbix_agent(2)_logfile`: name of log file. * `zabbix_agent(2)_logfilesize`: maximum size of log file in mb. +* `zabbix_agent(2)_additional_include`: A list of additional complete paths to include in configuration * `zabbix_agent(2)_logtype`: Specifies where log messages are written to * `zabbix_agent(2)_debuglevel`: specifies debug level * `zabbix_agent(2)_sourceip`: source ip address for outgoing connections. @@ -261,16 +247,17 @@ These variables need to be overridden when you want to make use of the Zabbix AP Host encryption configuration will be set to match agent configuration. -* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth. -* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth. -* `zabbix_api_create_hosts`: Default: `False`. When you want to enable the Zabbix API to create/delete the host. This has to be set to `True` if you want to make use of `zabbix_agent_host_state`. -* `zabbix_api_create_hostgroup`: When you want to enable the Zabbix API to create/delete the hostgroups. This has to be set to `True` if you want to make use of `zabbix_agent_hostgroups_state`.Default: `False` * `zabbix_api_server_host`: The IP or hostname/FQDN of Zabbix server. Example: zabbix.example.com -* `zabbix_api_server_port`: TCP port to use to connect to Zabbix server. Example: 8080 -* `zabbix_api_use_ssl`: yes (Default) if we need to connect to Zabbix server over HTTPS -* `zabbix_api_validate_certs` : yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used +* `zabbix_api_use_ssl`: Is SSL required to connect to the Zabbix API server? Default: `false` +* `zabbix_api_server_port`: 80 if `zabbix_api_use_ssl` is `false` and 443 if `true` (Default) TCP port to use to connect to Zabbix server. Example: 8080 * `zabbix_api_login_user`: Username of user which has API access. * `zabbix_api_login_pass`: Password for the user which has API access. +* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_validate_certs`: yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used. +* `zabbix_api_timeout`: How many seconds to wait for API response (default 30s). +* `zabbix_api_create_hosts`: Default: `False`. When you want to enable the Zabbix API to create/delete the host. This has to be set to `True` if you want to make use of `zabbix_agent_host_state`. +* `zabbix_api_create_hostgroup`: When you want to enable the Zabbix API to create/delete the hostgroups. This has to be set to `True` if you want to make use of `zabbix_agent_hostgroups_state`.Default: `False` * `ansible_zabbix_url_path`: URL path if Zabbix WebUI running on non-default (zabbix) path, e.g. if http://<FQDN>/zabbixeu then set to `zabbixeu` * `zabbix_agent_hostgroups_state`: present (Default) if the hostgroup needs to be created or absent if you want to delete it. This only works when `zabbix_api_create_hostgroup` is set to `True`. * `zabbix_host_status`: enabled (Default) when host in monitored, disabled when host is disabled for monitoring. @@ -290,7 +277,7 @@ Host encryption configuration will be set to match agent configuration. **NOTE** -_Supporting Windows is a best effort (I don't have the possibility to either test/verify changes on the various amount of available Windows instances). PRs specific to Windows will almost immediately be merged, unless someone is able to provide a Windows test mechanism via Travis for Pull Requests._ +_Supporting Windows is a best effort (We don't have the possibility to either test/verify changes on the various amount of available Windows instances). PRs specific to Windows will almost immediately be merged, unless someone is able to provide a Windows test mechanism via Travis for Pull Requests._ When `(2)` is used in the name of the property, like `zabbix_agent(2)_win_logfile`, it will show that you can configure `zabbix_agent_win_logfile` for the Zabbix Agent configuration file and `zabbix_agent2_win_logfile` for the Zabbix Agent 2 configuration file. Otherwise it just for the Zabbix Agent or for the Zabbix Agent 2. @@ -308,6 +295,10 @@ Otherwise it just for the Zabbix Agent or for the Zabbix Agent 2. ## macOS Variables +**NOTE** + +_Supporting Windows is a best effort (We don't have the possibility to either test/verify changes on the various amount of available Windows instances). PRs specific to Windows will almost immediately be merged, unless someone is able to provide a Windows test mechanism via Travis for Pull Requests._ + * `zabbix_version_long`: The long (major.minor.patch) version of the Zabbix Agent. This will be used to generate the `zabbix_mac_download_link` link. * `zabbix_mac_download_link`: The download url to the `pkg` file. @@ -344,17 +335,6 @@ Keep in mind that using the Zabbix Agent in a Container requires changes to the * `zabbix_agent_docker_volumes`: A list with all directories that needs to be available in the Container. * `zabbix_agent_docker_env`: A dict with all environment variables that needs to be set for the Container. -## FirewallD/Iptables - -* `zabbix_agent_firewall_enable`: If IPtables needs to be updated by opening an TCP port for port configured in `zabbix_agent_listenport`. -* `zabbix_agent_firewall_source`: When provided, IPtables will be configuring to only allow traffic from this IP address/range. -* `zabbix_agent_firewalld_enable`: If firewalld needs to be updated by opening an TCP port for port configured in `zabbix_agent_listenport` and `zabbix_agent_jmx_listenport` if defined. -* `zabbix_agent_firewalld_source`: When provided, firewalld will be configuring to only allow traffic for IP configured in `zabbix_agent_server`. -* `zabbix_agent_firewalld_zone`: When provided, the firewalld rule will be attached to this zone (only if zabbix_agent_firewalld_enable is set to true). The default behavior is to use the default zone define by the remote host firewalld configuration. -* `zabbix_agent_firewall_action`: Default: `insert`. When to `insert` the rule or to `append` to IPTables. -* `zabbix_agent_firewall_chain`: Default `INPUT`. Which `chain` to add the rule to IPTables. - - ## IPMI variables * `zabbix_agent_ipmi_authtype`: IPMI authentication algorithm. Possible values are 1 (callback), 2 (user), 3 (operator), 4 (admin), 5 (OEM), with 2 being the API default. @@ -369,6 +349,17 @@ When the target host does not have access to the internet, but you do have a pro * `zabbix_http_proxy` * `zabbix_https_proxy` +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Dependencies There are no dependencies on other roles. @@ -440,10 +431,11 @@ Including an example of how to use your role (for instance, with variables passe - role: community.zabbix.zabbix_agent zabbix_agent_server: 192.168.33.30 zabbix_agent_serveractive: 192.168.33.30 - zabbix_api_server_url: http://zabbix.example.com - zabbix_api_use: true # use zabbix_api_create_hosts and/or zabbix_api_create_hostgroup from 0.8.0 + zabbix_api_server_host: zabbix.example.com zabbix_api_login_user: Admin zabbix_api_login_pass: zabbix + zabbix_api_create_hostgroup: true + zabbix_api_create_hosts: true zabbix_agent_host_state: present zabbix_host_groups: - Linux Servers @@ -465,10 +457,11 @@ You can also use the group_vars or the host_vars files for setting the variables ```yaml zabbix_agent_server: 192.168.33.30 zabbix_agent_serveractive: 192.168.33.30 - zabbix_api_server_url: http://zabbix.example.com - zabbix_api_use: true # use zabbix_api_create_hosts and/or zabbix_api_create_hostgroup from 0.8.0 + zabbix_api_server_host: zabbix.example.com zabbix_api_login_user: Admin zabbix_api_login_pass: zabbix + zabbix_api_create_hostgroup: true + zabbix_api_create_hosts: true zabbix_agent_host_state: present zabbix_host_groups: - Linux Servers diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/defaults/main.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/defaults/main.yml index 5fc96071a..dbd5db5db 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/defaults/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/defaults/main.yml @@ -2,11 +2,9 @@ # defaults file for zabbix_agent zabbix_agent2: false -# zabbix_agent_version: 6.0 +# zabbix_agent_version: 6.4 zabbix_agent_version_minor: "*" -zabbix_version: "{{ zabbix_agent_version }}" zabbix_version_patch: 0 -zabbix_repo: zabbix zabbix_agent_package_remove: false zabbix_agent_package: zabbix-agent zabbix_sender_package: zabbix-sender @@ -17,7 +15,6 @@ zabbix_agent_serveractive: zabbix_agent2_server: "{{ zabbix_agent_server }}" zabbix_agent2_serveractive: "{{ zabbix_agent_serveractive }}" zabbix_selinux: false -zabbix_agent_src_reinstall: false zabbix_agent_apt_priority: zabbix_agent_conf_mode: "0644" zabbix_agent_dont_detect_ip: false @@ -36,22 +33,20 @@ zabbix_agent_packages: - "{{ zabbix_get_package }}" # Zabbix role related vars -zabbix_install_pip_packages: true zabbix_apt_force_apt_get: true zabbix_apt_install_recommends: false # Override Ansible specific facts zabbix_agent_distribution_major_version: "{{ ansible_distribution_major_version }}" zabbix_agent_distribution_release: "{{ ansible_distribution_release }}" -zabbix_agent_os_family: "{{ ansible_os_family }}" zabbix_repo_yum_gpgcheck: 0 zabbix_repo_yum_schema: https -zabbix_repo_yum_disabled: "*" -zabbix_repo_yum_enabled: [] +zabbix_agent_disable_repo: + - epel zabbix_repo_yum: - name: zabbix description: Zabbix Official Repository - $basearch - baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_version }}/rhel/{{ zabbix_agent_distribution_major_version }}/$basearch/" + baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_agent_version }}/rhel/{{ zabbix_agent_distribution_major_version }}/$basearch/" mode: "0644" gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX @@ -71,48 +66,32 @@ zabbix_repo_yum: gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX state: present +zabbix_repo_deb_component: main + # Zabbix API stuff -zabbix_validate_certs: true # Will be deprecated in 2.0.0 -zabbix_api_validate_certs: "{{ zabbix_validate_certs }}" -zabbix_agent_server_url: http://localhost # Will be deprecated in 2.0.0 -zabbix_url: "{{ zabbix_agent_server_url }}" # Will be deprecated in 2.0.0 -zabbix_api_server_url: "{{ zabbix_agent_server_url }}" -zabbix_api_server_host: "{{ zabbix_api_server_url | urlsplit('hostname') }}" -zabbix_api_port_from_url: "{{ zabbix_api_server_port | default(zabbix_api_server_url | urlsplit('port')) }}" -zabbix_api_scheme_from_url: "{{ zabbix_api_server_url | urlsplit('scheme') }}" -zabbix_api_port_from_shema: "{{ (zabbix_api_scheme_from_url == 'https') | ternary(443, 80) }}" -# zabbix_http_user: admin # Will be deprecated in 2.0.0 -# zabbix_http_password: admin # Will be deprecated in 2.0.0 -# zabbix_api_http_user: admin -# zabbix_api_http_password: admin -zabbix_api_user: Admin # Will be deprecated in 2.0.0 -zabbix_api_pass: !unsafe zabbix # Will be deprecated in 2.0.0 -zabbix_api_login_user: "{{ zabbix_api_user }}" -zabbix_api_login_pass: "{{ zabbix_api_pass }}" +zabbix_api_server_host: localhost +# zabbix_api_server_port: 80 +zabbix_api_login_user: Admin +zabbix_api_use_ssl: false +zabbix_api_login_pass: !unsafe zabbix +zabbix_api_validate_certs: false ansible_httpapi_pass: "{{ zabbix_api_login_pass }}" -ansible_httpapi_port: "{{ (zabbix_api_port_from_url == '') | ternary(zabbix_api_port_from_shema, zabbix_api_port_from_url) }}" -ansible_httpapi_use_ssl: "{{ zabbix_api_use_ssl | default((zabbix_api_scheme_from_url == 'https') | ternary(true, false)) }}" +ansible_httpapi_port: "{{ zabbix_api_server_port }}" ansible_httpapi_validate_certs: "{{ zabbix_api_validate_certs }}" +zabbix_api_timeout: 30 zabbix_api_create_hostgroup: false zabbix_api_create_hosts: false -zabbix_api_timeout: 30 -zabbix_create_hostgroup: present # or absent # Will be deprecated in 2.0.0 -zabbix_agent_hostgroups_state: "{{ zabbix_create_hostgroup }}" -zabbix_create_host: present # or absent # Will be deprecated in 2.0.0 -zabbix_agent_host_state: "{{ zabbix_create_host }}" -zabbix_update_host: true # Will be deprecated in 2.0.0 -zabbix_agent_host_update: "{{ zabbix_update_host }}" +zabbix_agent_hostgroups_state: present # or absent +zabbix_agent_host_state: present # or absent +zabbix_agent_host_update: true zabbix_host_status: enabled # or disabled -zabbix_proxy: null # Will be deprecated in 2.0.0 -zabbix_agent_proxy: "{{ zabbix_proxy }}" -zabbix_inventory_mode: disabled # Will be deprecated in 2.0.0 -zabbix_agent_inventory_mode: "{{ zabbix_inventory_mode }}" +zabbix_agent_proxy: null +zabbix_agent_inventory_mode: disabled zabbix_useuip: 1 zabbix_host_groups: - Linux servers -zabbix_link_templates: # Will be deprecated in 2.0.0 +zabbix_agent_link_templates: - Template Linux by Zabbix agent -zabbix_agent_link_templates: "{{ zabbix_link_templates }}" zabbix_agent_interfaces: - type: 1 @@ -122,14 +101,6 @@ zabbix_agent_interfaces: dns: "{{ ansible_fqdn }}" port: "{{ (zabbix_agent2 == True) | ternary(zabbix_agent2_listenport, zabbix_agent_listenport) }}" -zabbix_agent_firewall_enable: false -zabbix_agent_firewalld_enable: false -zabbix_agent_firewalld_source: "{{ zabbix_agent_server }}" -zabbix_agent_firewall_action: insert -zabbix_agent_firewall_chain: INPUT - -# By default, a null zone will trigger the use of the default zone on the remote host -zabbix_agent_firewalld_zone: # Zabbix configuration variables zabbix_agent_pidfile: /var/run/zabbix/zabbix_agentd.pid zabbix_agent_logtype: file @@ -171,8 +142,7 @@ zabbix_agent_become_on_localhost: true zabbix_agent_description: zabbix_agent_inventory_zabbix: {} zabbix_agent_heartbeatfrequency: 60 -zabbix_macros: [] # Will be deprecated in 2.0.0 -zabbix_agent_macros: "{{ zabbix_macros }}" +zabbix_agent_macros: [] zabbix_agent_tags: [] zabbix_agent_chassis: false @@ -272,7 +242,7 @@ zabbix_agent_docker: false zabbix_agent_docker_state: started zabbix_agent_docker_name: zabbix-agent zabbix_agent_docker_image: "zabbix/zabbix-agent" -zabbix_agent_docker_image_tag: "ubuntu-{{ zabbix_version }}.{{ zabbix_version_patch }}" +zabbix_agent_docker_image_tag: "ubuntu-{{ zabbix_agent_version }}.{{ zabbix_version_patch }}" zabbix_agent_docker_user_gid: 101 zabbix_agent_docker_user_uid: 101 zabbix_agent_docker_network_mode: host diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/handlers/main.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/handlers/main.yml index cd0f9d932..9f04b1a9b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/handlers/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/handlers/main.yml @@ -2,17 +2,17 @@ # handlers file for zabbix-agent - name: restart zabbix-agent - service: + ansible.builtin.service: name: "{{ zabbix_agent_service }}" state: restarted enabled: true become: true when: - not zabbix_agent_docker - - zabbix_agent_os_family != "Windows" and zabbix_agent_os_family != "Darwin" + - ansible_os_family != "Windows" and ansible_os_family != "Darwin" - name: firewalld-reload - command: "firewall-cmd --reload" + ansible.builtin.command: "firewall-cmd --reload" become: true when: - ansible_facts.services["firewalld"] is defined @@ -23,17 +23,17 @@ name: "{{ zabbix_win_svc_name }}" state: restarted when: - - zabbix_agent_os_family == "Windows" + - ansible_os_family == "Windows" - name: restart mac zabbix agent - command: "launchctl kickstart -k system/{{ zabbix_agent_service }}" + ansible.builtin.command: "launchctl kickstart -k system/{{ zabbix_agent_service }}" become: true when: - not zabbix_agent_docker - - zabbix_agent_os_family == "Darwin" + - ansible_os_family == "Darwin" - name: "clean repo files from proxy creds" - shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true + ansible.builtin.shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true become: true when: - ansible_os_family == 'RedHat' diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/molecule.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/molecule.yml index e7b8e06ae..137eac314 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/molecule.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/molecule.yml @@ -3,9 +3,6 @@ dependency: name: galaxy driver: name: docker -lint: - name: yamllint - platforms: - name: zabbix-server-centos image: milcom/centos7-systemd:latest @@ -46,12 +43,9 @@ provisioner: docker: create: ../default/create.yml destroy: ../default/destroy.yml - lint: - name: ansible-lint inventory: group_vars: all: - zabbix_agent_src_reinstall: false zabbix_api_create_hosts: true zabbix_api_create_hostgroup: true zabbix_api_server_url: http://zabbix-server-centos @@ -77,5 +71,3 @@ scenario: verifier: name: testinfra - lint: - name: flake8 diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/playbook.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/playbook.yml index e1bb7d8d4..2f0795448 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/playbook.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/playbook.yml @@ -3,7 +3,7 @@ hosts: all:!zabbix_server pre_tasks: - name: "Get IP Server" - shell: grep $(hostname) /etc/hosts | awk '{ print $1 }' | tail -n 1 + ansible.builtin.shell: grep $(hostname) /etc/hosts | awk '{ print $1 }' | tail -n 1 register: ip_address delegate_to: zabbix-server-centos changed_when: false @@ -11,7 +11,7 @@ - skip_ansible_lint - name: "Get IP hosts" - shell: grep $(hostname) /etc/hosts | awk '{ print $1 }' | tail -n 1 + ansible.builtin.shell: grep $(hostname) /etc/hosts | awk '{ print $1 }' | tail -n 1 register: ip_address_host changed_when: false tags: diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/prepare.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/prepare.yml index 6722e5fea..582006d4e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/prepare.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/molecule/with-server/prepare.yml @@ -3,14 +3,14 @@ hosts: zabbix_server pre_tasks: - name: "Installing EPEL" - yum: + ansible.builtin.yum: name: - epel-release state: present when: ansible_distribution == 'CentOS' - name: "Installing packages" - yum: + ansible.builtin.yum: name: - net-tools - which @@ -21,7 +21,7 @@ when: ansible_distribution == 'CentOS' - name: "Installing which on NON-CentOS" - apt: + ansible.builtin.apt: name: - net-tools - python-pip @@ -30,19 +30,19 @@ when: ansible_distribution != 'CentOS' - name: "Configure SUDO." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/sudoers line: "Defaults !requiretty" state: present - name: "Make sure the docs are installed." - lineinfile: + ansible.builtin.lineinfile: dest: /etc/yum.conf line: "tsflags=nodocs" state: absent - name: "Installing some python dependencies" - pip: + ansible.builtin.pip: name: py-zabbix state: present @@ -55,7 +55,7 @@ hosts: all:!zabbix_server:!docker tasks: - name: "Installing packages on CentOS family" - yum: + ansible.builtin.yum: name: - net-tools - which @@ -64,7 +64,7 @@ - ansible_os_family == 'RedHat' - name: "Installing packages on Debian family" - apt: + ansible.builtin.apt: name: - net-tools state: present @@ -75,7 +75,7 @@ hosts: docker tasks: - name: "Download Docker CE repo file" - get_url: + ansible.builtin.get_url: url: https://download.docker.com/linux/centos/docker-ce.repo dest: /etc/yum.repos.d/docker-ce.repo mode: 0644 @@ -83,7 +83,7 @@ until: zabbix_agent_prepare_docker_repo is succeeded - name: "Installing Epel" - package: + ansible.builtin.package: pkg: - epel-release state: present @@ -91,7 +91,7 @@ until: zabbix_agent_prepare_docker_install is succeeded - name: "Installing Docker" - package: + ansible.builtin.package: pkg: - docker-ce - python-pip @@ -101,7 +101,7 @@ until: zabbix_agent_prepare_docker_install is succeeded - name: "Installing Docker Python" - pip: + ansible.builtin.pip: name: - docker state: present @@ -109,6 +109,6 @@ until: zabbix_agent_prepare_docker_install is succeeded - name: "Starting Docker service" - service: + ansible.builtin.service: name: docker state: started diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Darwin.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Darwin.yml deleted file mode 100644 index e98576f61..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Darwin.yml +++ /dev/null @@ -1,177 +0,0 @@ ---- - -- name: "Set default ip address for zabbix_agent_ip" - set_fact: - zabbix_agent_ip: "{{ hostvars[inventory_hostname]['ansible_default_ipv4'].address }}" - when: - - zabbix_agent_ip is not defined - - "'ansible_default_ipv4' in hostvars[inventory_hostname]" - -- name: "Get Total Private IP Addresses" - set_fact: - total_private_ip_addresses: "{{ ansible_all_ipv4_addresses | ansible.netcommon.ipaddr('private') | length }}" - when: - - ansible_all_ipv4_addresses is defined - -- name: "Set first public ip address for zabbix_agent_ip" - set_fact: - zabbix_agent_ip: "{{ ansible_all_ipv4_addresses | ansible.netcommon.ipaddr('public') | first }}" - zabbix_agent_server: "{{ zabbix_agent_server_public_ip | default(zabbix_agent_server) }}" - zabbix_agent_serveractive: "{{ zabbix_agent_serveractive_public_ip | default(zabbix_agent_serveractive) }}" - zabbix_agent2_server: "{{ zabbix_agent_server_public_ip | default(zabbix_agent2_server) }}" - zabbix_agent2_serveractive: "{{ zabbix_agent_serveractive_public_ip | default(zabbix_agent2_serveractive) }}" - when: - - zabbix_agent_ip is not defined - - total_private_ip_addresses is defined - - total_private_ip_addresses == '0' - -- name: "Set first private ip address for zabbix_agent_ip" - set_fact: - zabbix_agent_ip: "{{ ansible_all_ipv4_addresses | ansible.netcommon.ipaddr('private') | first }}" - when: - - zabbix_agent_ip is not defined - - total_private_ip_addresses is defined - - total_private_ip_addresses != '0' - -- name: "Fail invalid specified agent_listeninterface" - fail: - msg: "The specified network interface does not exist" - when: - - zabbix_agent_listeninterface - - (zabbix_agent_listeninterface not in ansible_all_ipv4_addresses) - tags: - - zabbix-agent - - config - -- name: "Set network interface" - set_fact: - network_interface: ansible_{{ zabbix_agent_listeninterface }} - when: - - zabbix_agent_listeninterface - - not zabbix_agent_listenip - -- name: "Get IP of agent_listeninterface when no agent_listenip specified" - set_fact: - zabbix_agent_listenip: "{{ hostvars[inventory_hostname][network_interface]['ipv4'].address | default('0.0.0.0') }}" - zabbix_agent_ip: "{{ hostvars[inventory_hostname][network_interface]['ipv4'].address | default('0.0.0.0') }}" - when: - - zabbix_agent_listeninterface - - not zabbix_agent_listenip - tags: - - zabbix-agent - - config - - api - -- name: "Default agent_listenip to all when not specified" - set_fact: - zabbix_agent_listenip: '0.0.0.0' - when: - - not zabbix_agent_listenip - tags: - - zabbix-agent - - config - -- name: "Fail invalid specified agent_listenip" - fail: - msg: "The agent_listenip does not exist" - when: - - zabbix_agent_listenip != '0.0.0.0' - - zabbix_agent_listenip != '127.0.0.1' - - (zabbix_agent_listenip not in ansible_all_ipv4_addresses) - tags: - - zabbix-agent - - config - -- name: "Installing Agent" - include_tasks: macOS.yml - tags: - - always - -- name: "Configure zabbix-agent" - template: - src: zabbix_agentd.conf.j2 - dest: "/usr/local/etc/zabbix/{{ zabbix_agent_conf }}" - owner: zabbix - group: wheel - mode: 0644 - notify: - - restart mac zabbix agent - become: true - when: - - not (zabbix_agent_docker | bool) - tags: - - zabbix-agent - - config - - init - -- name: "Create directory for PSK file if not exist." - file: - path: "{{ zabbix_agent_tlspskfile | dirname }}" - mode: 0755 - state: directory - become: true - when: - - zabbix_agent_tlspskfile is defined - -- name: "Place TLS PSK File" - copy: - dest: "{{ zabbix_agent_tlspskfile }}" - content: "{{ zabbix_agent_tlspsk_secret }}" - owner: zabbix - group: zabbix - mode: 0400 - become: true - when: - - zabbix_agent_tlspskfile is defined - - zabbix_agent_tlspsk_secret is defined - notify: - - restart mac zabbix agent - -- name: "Create include dir zabbix-agent" - file: - path: "{{ zabbix_agent_include }}" - owner: zabbix - group: zabbix - mode: 0750 - state: directory - become: true - tags: - - config - - include - -- name: "Create pid file directory for zabbix-agent" - file: - path: /var/run/zabbix - state: directory - owner: zabbix - group: zabbix - mode: 0755 - become: true - -- name: "Install the Docker container" - include_tasks: Docker.yml - when: - - zabbix_agent_docker | bool - -- name: "Check if zabbix-agent service is running" - shell: | - set -o pipefail - launchctl list | grep com.zabbix.zabbix_agentd | awk '{print $1}' - register: launchctl_pid - check_mode: false - changed_when: false - failed_when: launchctl_pid.rc == 2 - become: true - tags: - - init - - service - -- name: "Make sure the zabbix-agent service is running" - command: launchctl start com.zabbix.zabbix_agentd - become: true - when: - - not (zabbix_agent_docker | bool) - - launchctl_pid.stdout == "-" - tags: - - init - - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Debian.yml index ec4a01879..6ded0ba03 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Debian.yml @@ -1,17 +1,16 @@ --- # Tasks specific for Debian/Ubuntu Systems -- name: "Include Zabbix gpg ids" - include_vars: zabbix.yml - -- name: "Set short version name" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - zabbix_underscore_version: "{{ zabbix_version | regex_replace('\\.', '_') }}" +- name: "Debian | Set some variables" + ansible.builtin.set_fact: + zabbix_short_version: "{{ zabbix_agent_version | regex_replace('\\.', '') }}" + zabbix_underscore_version: "{{ zabbix_agent_version | regex_replace('\\.', '_') }}" + tags: + - always -- name: "Debian | Installing gnupg" - apt: - pkg: gnupg +- name: "Debian | Installing lsb-release" + ansible.builtin.apt: + pkg: lsb-release update_cache: true cache_valid_time: 3600 force: true @@ -19,174 +18,111 @@ environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: gnupg_installed - until: gnupg_installed is succeeded - become: true - -- name: "Debian | Install gpg key" - apt_key: - id: "{{ sign_keys[zabbix_short_version][zabbix_agent_distribution_release]['sign_key'] }}" - url: http://repo.zabbix.com/zabbix-official-repo.key - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - zabbix_repo == "zabbix" become: true tags: - - zabbix-agent - - init + - install -- name: "Debian | Check for zabbix repositories" - find: - paths: /etc/apt/sources.list.d - patterns: repo_zabbix_com_zabbix*.list - excludes: "repo_zabbix_com_zabbix_{{ zabbix_underscore_version }}_ubuntu.list" - register: repositories - become: true - when: - - ansible_distribution in ['Ubuntu', 'Debian'] - - zabbix_repo == "zabbix" - tags: - - zabbix-agent - - init +- name: "Debian | Update ansible_lsb fact" + ansible.builtin.setup: + gather_subset: + - lsb -- name: "Debian | Remove unecessary zabbix repositories" - file: - path: "{{ item.path }}" - state: absent - loop: "{{ repositories.files }}" +- name: "Debian | Repo URL" + ansible.builtin.set_fact: + zabbix_repo_deb_url: "{{ _zabbix_repo_deb_url }}/{{ ansible_lsb.id.lower() }}{{ '-arm64' if ansible_machine == 'aarch64' and ansible_lsb.id == 'debian' else ''}}" when: - - ansible_distribution in ['Ubuntu', 'Debian'] - - zabbix_repo == "zabbix" - - zabbix_agent_src_reinstall - become: true + - zabbix_repo_deb_url is undefined tags: - - zabbix-agent - - init + - always -- name: "Debian | Installing deb-src repository Debian" - apt_repository: - repo: "deb-src http://repo.zabbix.com/zabbix/{{ zabbix_version }}/debian/ {{ zabbix_agent_distribution_release }} main" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - ansible_distribution == "Debian" - - zabbix_repo == "zabbix" - become: true - tags: - - zabbix-agent - - init - -- name: "Debian | Installing deb repository Debian" - apt_repository: - repo: "deb http://repo.zabbix.com/zabbix/{{ zabbix_version }}/debian/ {{ zabbix_agent_distribution_release }} main" +- name: "Debian | Installing gnupg" + ansible.builtin.apt: + pkg: gnupg + update_cache: true + cache_valid_time: 3600 + force: true state: present environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - ansible_distribution == "Debian" - - zabbix_repo == "zabbix" + register: gnupg_installed + until: gnupg_installed is succeeded become: true tags: - - zabbix-agent - - init - -- name: "Debian | Installing deb-src repository Ubuntu Arm64" - apt_repository: - repo: "deb-src http://repo.zabbix.com/zabbix/{{ zabbix_version }}/ubuntu-arm64/ {{ zabbix_agent_distribution_release }} main" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - ansible_distribution == "Ubuntu" - - ansible_machine == "aarch64" - - zabbix_repo == "zabbix" + - install + +# In releases older than Debian 12 and Ubuntu 22.04, /etc/apt/keyrings does not exist by default. +# It SHOULD be created with permissions 0755 if it is needed and does not already exist. +# See: https://wiki.debian.org/DebianRepository/UseThirdParty +- name: "Debian | Create /etc/apt/keyrings/ on older versions" + ansible.builtin.file: + path: /etc/apt/keyrings/ + state: directory + mode: "0755" become: true - tags: - - zabbix-agent - - init - -- name: "Debian | Installing deb repository Ubuntu Arm64" - apt_repository: - repo: "deb http://repo.zabbix.com/zabbix/{{ zabbix_version }}/ubuntu-arm64/ {{ zabbix_agent_distribution_release }} main" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" when: - - ansible_distribution == "Ubuntu" - - ansible_machine == "aarch64" - - zabbix_repo == "zabbix" - become: true - tags: - - zabbix-agent - - init + - (ansible_distribution == "Ubuntu" and ansible_distribution_major_version < "22") or + (ansible_distribution == "Debian" and ansible_distribution_major_version < "12") -- name: "Debian | Installing deb-src repository Ubuntu" - apt_repository: - repo: "deb-src http://repo.zabbix.com/zabbix/{{ zabbix_version }}/ubuntu/ {{ zabbix_agent_distribution_release }} main" - state: present +- name: "Debian | Download gpg key" + ansible.builtin.get_url: + url: http://repo.zabbix.com/zabbix-official-repo.key + dest: "{{ zabbix_gpg_key }}" + mode: "0644" + force: true environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - ansible_distribution == "Ubuntu" - - ansible_machine != "aarch64" - - zabbix_repo == "zabbix" become: true tags: - - zabbix-agent - - init + - install -- name: "Debian | Installing deb repository Ubuntu" - apt_repository: - repo: "deb http://repo.zabbix.com/zabbix/{{ zabbix_version }}/ubuntu/ {{ zabbix_agent_distribution_release }} main" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - ansible_distribution == "Ubuntu" - - ansible_machine != "aarch64" - - zabbix_repo == "zabbix" +- name: "Debian | Installing repository {{ ansible_distribution }}" + ansible.builtin.copy: + dest: /etc/apt/sources.list.d/zabbix.sources + owner: root + group: root + mode: 0644 + content: | + Types: deb deb-src + Enabled: yes + URIs: {{ zabbix_repo_deb_url }} + Suites: {{ ansible_distribution_release }} + Components: {{ zabbix_repo_deb_component }} + Architectures: {{ 'amd64' if ansible_machine != 'aarch64' else 'arm64'}} + Signed-By: {{ zabbix_gpg_key }} become: true tags: - - zabbix-agent - - init + - install - name: "Debian | Create /etc/apt/preferences.d/" - file: + ansible.builtin.file: path: /etc/apt/preferences.d/ state: directory - mode: '0755' + mode: "0755" when: - zabbix_agent_apt_priority | int become: true + tags: + - install - name: "Debian | Configuring the weight for APT" - copy: + ansible.builtin.copy: dest: "/etc/apt/preferences.d/zabbix-agent-{{ zabbix_underscore_version }}" content: | Package: {{ zabbix_agent_package }} Pin: origin repo.zabbix.com Pin-Priority: {{ zabbix_agent_apt_priority | int }} owner: root - mode: '0644' + mode: "0644" when: - zabbix_agent_apt_priority | int become: true + tags: + - install -# Note: set cache_valid_time=0 to ensure that an apt-get update after the added repo-key -# else you often get 'WARNING: The following packages cannot be authenticated! -# See also: -# http://askubuntu.com/questions/75565/why-am-i-getting-authentication-errors-for-packages-from-an-ubuntu-repository - name: "Debian | Installing zabbix-agent" - apt: + ansible.builtin.apt: pkg: "{{ zabbix_agent_package }}" state: "{{ zabbix_agent_package_state }}" update_cache: true @@ -196,16 +132,14 @@ environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: ansible_distribution in ['Ubuntu', 'Debian'] register: zabbix_agent_package_installed until: zabbix_agent_package_installed is succeeded become: true tags: - - zabbix-agent - - init + - install - name: "Debian | Installing zabbix-{sender,get}" - apt: + ansible.builtin.apt: pkg: - "{{ zabbix_sender_package }}" - "{{ zabbix_get_package }}" @@ -218,42 +152,19 @@ http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" when: - - ansible_distribution in ['Ubuntu', 'Debian'] - not zabbix_agent_install_agent_only register: zabbix_agent_package_installed until: zabbix_agent_package_installed is succeeded become: true check_mode: false tags: - - zabbix-agent - - init - -- name: "Mint | Installing zabbix-agent" - apt: - pkg: "zabbix-agent" - state: "{{ zabbix_agent_package_state }}" - update_cache: true - cache_valid_time: 0 - force_apt_get: "{{ zabbix_apt_force_apt_get }}" - install_recommends: "{{ zabbix_apt_install_recommends }}" - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: ansible_distribution not in ['Ubuntu', 'Debian'] - register: zabbix_agent_package_installed - until: zabbix_agent_package_installed is succeeded - become: true - tags: - - zabbix-agent - - init + - install - name: "Debian | Enable the service" - service: + ansible.builtin.service: name: "{{ zabbix_agent_service }}" enabled: true use: service become: true tags: - - zabbix-agent - - init - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Docker.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Docker.yml index cbbef204d..031a5fe61 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Docker.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Docker.yml @@ -1,7 +1,6 @@ --- - - name: "Create volume mount string" - set_fact: + ansible.builtin.set_fact: volume_mount: "{{ zabbix_agent_tlspskfile }}:/var/lib/zabbix/enc/tlspskfile" tls_key: ZBX_TLSPSKFILE: tlspskfile @@ -9,7 +8,7 @@ - zabbix_agent_tlspskfile is defined - name: "Add zabbix_agent_tlspskfile to volume mount" - set_fact: + ansible.builtin.set_fact: zabbix_agent_docker_volumes: "{{ zabbix_agent_docker_volumes + [ volume_mount ] }}" zabbix_agent_docker_env: "{{ zabbix_agent_docker_env | combine(tls_key) }}" when: diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Linux.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Linux.yml index d2c0ba82c..c4c8fc401 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Linux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Linux.yml @@ -1,21 +1,24 @@ --- - - name: "Set default ip address for zabbix_agent_ip" - set_fact: + ansible.builtin.set_fact: zabbix_agent_ip: "{{ hostvars[inventory_hostname]['ansible_default_ipv4'].address }}" when: - zabbix_agent_ip is not defined - "'ansible_default_ipv4' in hostvars[inventory_hostname]" + tags: + - config - name: "Get Total Private IP Addresses" - set_fact: + ansible.builtin.set_fact: total_private_ip_addresses: "{{ ansible_all_ipv4_addresses | ansible.utils.ipaddr('private') | length }}" when: - ansible_all_ipv4_addresses is defined - not (zabbix_agent_dont_detect_ip) + tags: + - config - name: "Set first public ip address for zabbix_agent_ip" - set_fact: + ansible.builtin.set_fact: zabbix_agent_ip: "{{ ansible_all_ipv4_addresses | ansible.netcommon.ipaddr('public') | first }}" zabbix_agent_server: "{{ zabbix_agent_server_public_ip | default(zabbix_agent_server) }}" zabbix_agent_serveractive: "{{ zabbix_agent_serveractive_public_ip | default(zabbix_agent_serveractive) }}" @@ -25,79 +28,83 @@ - zabbix_agent_ip is not defined - total_private_ip_addresses is defined - total_private_ip_addresses == '0' + tags: + - config - name: "Set first private ip address for zabbix_agent_ip" - set_fact: + ansible.builtin.set_fact: zabbix_agent_ip: "{{ ansible_all_ipv4_addresses | ansible.netcommon.ipaddr('private') | first }}" when: - zabbix_agent_ip is not defined - total_private_ip_addresses is defined - total_private_ip_addresses != '0' + tags: + - config - name: "Fail invalid specified agent_listeninterface" - fail: + ansible.builtin.fail: msg: "The specified network interface does not exist" when: - (zabbix_agent_listeninterface) - (zabbix_agent_listeninterface not in ansible_interfaces) tags: - - zabbix-agent - config - name: "Set network interface" - set_fact: + ansible.builtin.set_fact: network_interface: ansible_{{ zabbix_agent_listeninterface }} when: - (zabbix_agent_listeninterface) - not zabbix_agent_listenip + tags: + - config - name: "Get IP of agent_listeninterface when no agent_listenip specified" - set_fact: + ansible.builtin.set_fact: zabbix_agent_listenip: "{{ hostvars[inventory_hostname][network_interface]['ipv4'].address | default('0.0.0.0') }}" when: - (zabbix_agent_listeninterface) - not zabbix_agent_listenip tags: - - zabbix-agent - config - api - name: "Default agent_listenip to all when not specified" - set_fact: - zabbix_agent_listenip: '0.0.0.0' + ansible.builtin.set_fact: + zabbix_agent_listenip: "0.0.0.0" when: - not (zabbix_agent_listenip) tags: - - zabbix-agent - config - name: "Fail invalid specified agent_listenip" - fail: + ansible.builtin.fail: msg: "The agent_listenip does not exist" when: - zabbix_agent_listenip != '0.0.0.0' - zabbix_agent_listenip != '127.0.0.1' - (zabbix_agent_listenip not in ansible_all_ipv4_addresses) tags: - - zabbix-agent - config - name: "Configure SELinux when enabled" - include_tasks: selinux.yml + ansible.builtin.include_tasks: selinux.yml when: - zabbix_selinux | bool - name: "Adding zabbix group" - group: + ansible.builtin.group: name: zabbix state: present gid: "{{ zabbix_agent_docker_user_gid | default(omit) }}" become: true when: - zabbix_agent_docker | bool + tags: + - config - name: "Adding zabbix user" - user: + ansible.builtin.user: name: zabbix group: zabbix state: present @@ -108,9 +115,11 @@ become: true when: - zabbix_agent_docker | bool + tags: + - config - name: "Configure zabbix-agent" - template: + ansible.builtin.template: src: "{{ 'zabbix_agentd.conf.j2' if not zabbix_agent2 else 'zabbix_agent2.conf.j2' }}" dest: "/etc/zabbix/{{ zabbix_agent_conf if not zabbix_agent2 else zabbix_agent2_conf }}" owner: root @@ -122,34 +131,36 @@ when: - not (zabbix_agent_docker | bool) tags: - - zabbix-agent - config - - init - name: "Create directory for PSK file if not exist." - file: + ansible.builtin.file: path: "{{ zabbix_agent_tlspskfile | dirname }}" mode: 0755 state: directory become: true when: - zabbix_agent_tlspskfile is defined - - zabbix_agent_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 + - zabbix_agent_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 - not (zabbix_agent2 | bool) + tags: + - config - name: "Create directory for PSK file if not exist (zabbix-agent2)" - file: + ansible.builtin.file: path: "{{ zabbix_agent2_tlspskfile | dirname }}" mode: 0755 state: directory become: true when: - zabbix_agent2_tlspskfile is defined - - zabbix_agent2_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 + - zabbix_agent2_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 - zabbix_agent2 | bool + tags: + - config - name: "Place TLS PSK File" - copy: + ansible.builtin.copy: dest: "{{ zabbix_agent_tlspskfile }}" content: "{{ zabbix_agent_tlspsk_secret }}" owner: zabbix @@ -158,14 +169,16 @@ become: true when: - zabbix_agent_tlspskfile is defined - - zabbix_agent_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 + - zabbix_agent_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 - zabbix_agent_tlspsk_secret is defined - not (zabbix_agent2 | bool) notify: - restart zabbix-agent + tags: + - config - name: "Place TLS PSK File (zabbix-agent2)" - copy: + ansible.builtin.copy: dest: "{{ zabbix_agent2_tlspskfile }}" content: "{{ zabbix_agent2_tlspsk_secret }}" owner: zabbix @@ -174,14 +187,16 @@ become: true when: - zabbix_agent2_tlspskfile is defined - - zabbix_agent2_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 + - zabbix_agent2_tlspskfile # https://github.com/ansible-collections/community.zabbix/issues/680 - zabbix_agent2_tlspsk_secret is defined - zabbix_agent2 | bool notify: - restart zabbix-agent + tags: + - config - name: "Create include dir zabbix-agent" - file: + ansible.builtin.file: path: "{{ zabbix_agent_include if not zabbix_agent2 else zabbix_agent2_include }}" owner: root group: zabbix @@ -190,26 +205,20 @@ become: true tags: - config - - include - name: "Install the Docker container" - include_tasks: Docker.yml + ansible.builtin.include_tasks: Docker.yml when: - zabbix_agent_docker | bool -- name: "Configure the firewall(d|iptables)" - include_tasks: firewall.yml - when: - - (zabbix_agent_firewall_enable | bool) or (zabbix_agent_firewalld_enable | bool) - - name: "Remove zabbix-agent installation when zabbix-agent2 is used." - include_tasks: remove.yml + ansible.builtin.include_tasks: remove.yml when: - zabbix_agent2 | bool - zabbix_agent_package_remove - name: "Make sure the zabbix-agent service is running" - service: + ansible.builtin.service: name: "{{ zabbix_agent_service }}" state: started enabled: true @@ -217,12 +226,14 @@ when: - not (zabbix_agent_docker | bool) tags: - - init - service - name: "Give zabbix-agent access to system.hw.chassis info" - file: + ansible.builtin.file: path: /sys/firmware/dmi/tables/DMI owner: root group: zabbix + become: true when: zabbix_agent_chassis | bool + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/RedHat.yml index ef8cfaf09..f23cb46ad 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/RedHat.yml @@ -1,133 +1,53 @@ --- # Tasks specific for RedHat systems -- name: "RedHat | Use EPEL package name" - set_fact: - zabbix_agent_package: "zabbix{{ zabbix_version | regex_replace('\\.', '') }}-agent" - zabbix_sender_package: "zabbix{{ zabbix_version | regex_replace('\\.', '') }}-sender" - zabbix_get_package: "zabbix{{ zabbix_version | regex_replace('\\.', '') }}-get" - when: - - zabbix_repo == "epel" - tags: - - zabbix-agent - - init - -- name: "RedHat | Set zabbix_agent_distribution_major_version to 6 when Amazon" - set_fact: - zabbix_agent_distribution_major_version: 6 - when: - - ansible_distribution == "Amazon" - - ansible_distribution_major_version == "NA" - -- name: "RedHat | Set zabbix_agent_distribution_major_version to 6 when Major Version is 2018.03" - set_fact: - zabbix_agent_distribution_major_version: 6 - when: - - ansible_distribution == "Amazon" - - ansible_distribution_major_version == "2018" - -- name: "RedHat | Set zabbix_agent_distribution_major_version to 7 when Amazon 2" - set_fact: - zabbix_agent_distribution_major_version: 7 - when: - - ansible_distribution == "Amazon" - - ansible_distribution_major_version == "2" - -- name: "Fedora | Override zabbix_agent_distribution_major_version for Fedora <= 27" - set_fact: - zabbix_agent_distribution_major_version: 7 - when: - - ansible_distribution == "Fedora" - - ansible_distribution_major_version <= "27" - -- name: "Fedora | Override zabbix_agent_distribution_major_version for Fedora >= 27" - set_fact: - zabbix_agent_distribution_major_version: 8 - when: - - ansible_distribution == "Fedora" - - ansible_distribution_major_version >= "27" - -- name: "XCP-ng | Override zabbix_agent_distribution_major_version for XCP-ng" - set_fact: - zabbix_agent_distribution_major_version: 7 - when: - - ansible_distribution == "XCP-ng" - - name: "RedHat | Install basic repo file" - yum_repository: + ansible.builtin.yum_repository: name: "{{ item.name }}" description: "{{ item.description }}" baseurl: "{{ item.baseurl }}" gpgcheck: "{{ item.gpgcheck }}" gpgkey: "{{ item.gpgkey }}" mode: "{{ item.mode | default('0644') }}" - priority: "{{ item.priority | default('98') }}" + priority: "{{ item.priority | default('99') }}" state: "{{ item.state | default('present') }}" proxy: "{{ zabbix_http_proxy | default(omit) }}" with_items: "{{ zabbix_repo_yum }}" register: yum_repo_installed become: true - when: - zabbix_repo == "zabbix" notify: - "clean repo files from proxy creds" tags: - - zabbix-agent + - install - name: Check if warn parameter can be used for shell module - set_fact: + ansible.builtin.set_fact: produce_warn: False when: ansible_version.full is version("2.14", "<") - -- name: "Do a yum clean" - shell: yum clean all - args: - warn: "{{ produce_warn | default(omit) }}" - when: yum_repo_installed.changed - become: true tags: - - skip_ansible_lint + - always - name: "RedHat | Installing zabbix-agent" - package: + ansible.builtin.package: pkg: - "{{ zabbix_agent_package }}-{{ zabbix_agent_version }}.{{ zabbix_agent_version_minor }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_agent_disable_repo | default(omit) }}" state: "{{ zabbix_agent_package_state }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" register: zabbix_agent_package_installed until: zabbix_agent_package_installed is succeeded - when: - zabbix_repo != "other" become: true tags: - - init - - zabbix-agent - -- name: "RedHat | Installing zabbix-agent (When zabbix_repo == other)" - package: - pkg: - - "{{ zabbix_agent_package }}-{{ zabbix_agent_version }}.{{ zabbix_agent_version_minor }}" - state: "{{ zabbix_agent_package_state }}" - register: zabbix_agent_package_installed - until: zabbix_agent_package_installed is succeeded - when: - zabbix_repo == "other" - become: true - tags: - - init - - zabbix-agent + - install - name: "RedHat | Installing zabbix-{sender,get}" - package: + ansible.builtin.package: pkg: - "{{ zabbix_sender_package }}-{{ zabbix_agent_version }}.{{ zabbix_agent_version_minor }}" - "{{ zabbix_get_package }}-{{ zabbix_agent_version }}.{{ zabbix_agent_version_minor }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_agent_disable_repo | default(omit) }}" state: "{{ zabbix_agent_package_state }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" @@ -135,36 +55,16 @@ register: zabbix_agent_package_installed until: zabbix_agent_package_installed is succeeded when: - - zabbix_repo not in ['epel', 'other'] - - not zabbix_agent_install_agent_only - become: true - tags: - - init - - zabbix-agent - -- name: "RedHat | Installing zabbix-{sender,get} (When zabbix_repo == other)" - package: - pkg: - - "{{ zabbix_sender_package }}-{{ zabbix_agent_version }}.{{ zabbix_agent_version_minor }}" - - "{{ zabbix_get_package }}-{{ zabbix_agent_version }}.{{ zabbix_agent_version_minor }}" - state: "{{ zabbix_agent_package_state }}" - register: zabbix_agent_package_installed - until: zabbix_agent_package_installed is succeeded - when: - - zabbix_repo == "other" - not zabbix_agent_install_agent_only become: true tags: - - init - - zabbix-agent + - install - name: "RedHat | Enable the service" - service: + ansible.builtin.service: name: "{{ zabbix_agent_service }}" enabled: true use: service become: true tags: - - zabbix-agent - - init - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Suse.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Suse.yml deleted file mode 100644 index 82dc3ce7d..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Suse.yml +++ /dev/null @@ -1,55 +0,0 @@ ---- -# Tasks specific for OpenSuse Systems - -- name: "Include Zabbix gpg ids" - include_vars: zabbix.yml - -- name: "Install zypper repo dependency" - community.general.zypper: - name: - - python-xml - - "{{ suse[ansible_distribution][zabbix_agent_distribution_major_version]['python_libxml2_package'] }}" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - become: true - register: zabbix_agent_package_dependency - until: zabbix_agent_package_dependency is succeeded - -- name: "Suse | Install basic repo file" - community.general.zypper_repository: - repo: "{{ suse[ansible_distribution][zabbix_agent_distribution_major_version]['url'] }}" - name: "{{ suse[ansible_distribution][zabbix_agent_distribution_major_version]['name'] }}" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - when: - - zabbix_repo == "zabbix" - become: true - tags: - - zabbix-agent - - init - -- name: "Only install the Zabbix Agent" - set_fact: - zabbix_agent_packages: - - "{{ zabbix_agent_package }}" - when: - - zabbix_agent_install_agent_only - -- name: "Suse | Install zabbix-agent" - community.general.zypper: - name: "{{ zabbix_agent_packages }}" - state: "{{ zabbix_agent_package_state }}" - disable_gpg_check: true - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_agent_package_installed - until: zabbix_agent_package_installed is succeeded - become: true - tags: - - zabbix-agent - - init diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows.yml index 61e12361e..9b7501d9a 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows.yml @@ -1,36 +1,44 @@ --- - name: "Windows | Set default architecture" - set_fact: + ansible.builtin.set_fact: windows_arch: 32 + tags: + - always - name: "Windows | Override architecture if 64-bit" - set_fact: + ansible.builtin.set_fact: windows_arch: 64 when: - ansible_architecture == "64-bit" + tags: + - always - name: "Windows | Set path to zabbix.exe" - set_fact: + ansible.builtin.set_fact: zabbix_win_exe_path: '{{ zabbix_win_install_dir }}\bin\win{{ windows_arch }}\zabbix_agentd.exe' + tags: + - always -- name: "Windows | Set variables specific to Zabbix >= 4" - set_fact: +- name: "Windows | Set variables specific to Zabbix" + ansible.builtin.set_fact: zabbix_win_svc_name: Zabbix Agent zabbix_win_exe_path: '{{ zabbix_win_install_dir }}\bin\zabbix_agentd.exe' - zabbix_win_config_name: 'zabbix_agentd.conf' + zabbix_win_config_name: "zabbix_agentd.conf" zabbix2_win_svc_name: Zabbix Agent 2 zabbix2_win_exe_path: '{{ zabbix_win_install_dir }}\bin\zabbix_agent2.exe' - zabbix2_win_config_name: 'zabbix_agent2.conf' - when: - - zabbix_version_long is version('4.0.0', '>=') + zabbix2_win_config_name: "zabbix_agent2.conf" + tags: + - always - name: "Windows | Check if Zabbix agent is present" ansible.windows.win_stat: - path: '{{ item }}' + path: "{{ item }}" with_items: - "{{ zabbix_win_exe_path }}" - "{{ zabbix2_win_exe_path }}" register: agent_file_info + tags: + - always - name: "Windows | Get Installed Zabbix Agent Version" community.windows.win_file_version: @@ -39,9 +47,11 @@ when: - item.stat.exists | bool with_items: "{{ agent_file_info.results }}" + tags: + - always - name: "Windows | Set facts current zabbix agent installation" - set_fact: + ansible.builtin.set_fact: zabbix_agent_1_binary_exist: true zabbix_agent_1_version: zabbix_win_exe_info.results[0].win_file_version.product_version when: @@ -49,9 +59,11 @@ - zabbix_win_exe_info.results[0].item.stat.exists - zabbix_win_exe_info.results[0].item.stat.path == zabbix_win_exe_path - zabbix_win_exe_info.results[0].win_file_version.product_version + tags: + - always - name: "Windows | Set facts current zabbix agent installation (agent 2)" - set_fact: + ansible.builtin.set_fact: zabbix_agent_2_binary_exist: true zabbix_agent_2_version: zabbix_win_exe_info.results[1].win_file_version.product_version when: @@ -59,6 +71,8 @@ - zabbix_win_exe_info.results[1].item.stat.exists - zabbix_win_exe_info.results[1].item.stat.path == zabbix2_win_exe_path - zabbix_win_exe_info.results[1].win_file_version.product_version + tags: + - always - name: "Windows | Check Zabbix service" ansible.windows.win_service: @@ -66,25 +80,31 @@ register: zabbix_service_info when: item.item.stat.exists with_items: "{{ zabbix_win_exe_info.results }}" + tags: + - always - name: "Windows | Set facts about current zabbix agent service state" - set_fact: + ansible.builtin.set_fact: zabbix_agent_1_service_exist: true when: - zabbix_service_info.results[0].exists is defined - zabbix_service_info.results[0].exists - zabbix_service_info.results[0].display_name == zabbix_win_svc_name + tags: + - always - name: "Windows | Set facts about current zabbix agent service state (agent 2)" - set_fact: + ansible.builtin.set_fact: zabbix_agent_2_service_exist: true when: - zabbix_service_info.results[1].exists is defined - zabbix_service_info.results[1].exists - zabbix_service_info.results[1].display_name == zabbix2_win_svc_name + tags: + - always - name: "Windows | Set fact about version change requirement" - set_fact: + ansible.builtin.set_fact: zabbix_agent_version_change: true when: > (zabbix_agent_1_binary_exist | default(false) and @@ -94,6 +114,8 @@ zabbix_win_exe_info.results[1].win_file_version.product_version is version(zabbix_version_long, '<>')) or (zabbix_agent_1_binary_exist | default(false) and zabbix_agent2) or (zabbix_agent_2_binary_exist | default(false) and not zabbix_agent2) + tags: + - always ################## # delete section # @@ -131,10 +153,11 @@ - name: "Windows | Removing Zabbix Directory" ansible.windows.win_file: - path: '{{ zabbix_win_install_dir }}' + path: "{{ zabbix_win_install_dir }}" state: absent - when: ((zabbix_agent_version_change | default(false) or zabbix_agent2) and zabbix_agent_1_binary_exist | default(false)) or - ((zabbix_agent_version_change | default(false) or not zabbix_agent2) and zabbix_agent_2_binary_exist | default(false)) + when: + ((zabbix_agent_version_change | default(false) or zabbix_agent2) and zabbix_agent_1_binary_exist | default(false)) or + ((zabbix_agent_version_change | default(false) or not zabbix_agent2) and zabbix_agent_2_binary_exist | default(false)) ################### # install section # @@ -146,6 +169,8 @@ state: directory with_items: - "{{ zabbix_win_install_dir }}" + tags: + - install - name: "Windows | Create directory structure, includes" ansible.windows.win_file: @@ -155,25 +180,33 @@ - "{{ zabbix_agent_win_include }}" when: - ('.conf' not in zabbix_agent_win_include) + tags: + - install - name: "Windows | Set installation settings (agent 2)" - set_fact: + ansible.builtin.set_fact: zabbix_win_package: "{{ zabbix2_win_package }}" zabbix_win_download_link: "{{ zabbix2_win_download_link }}" zabbix_win_exe_path: "{{ zabbix2_win_exe_path }}" zabbix_win_config_name: "{{ zabbix2_win_config_name }}" zabbix_win_svc_name: "{{ zabbix2_win_svc_name }}" when: zabbix_agent2 | bool + tags: + - install - name: "Windows | Check if agent file is already downloaded" ansible.windows.win_stat: path: '{{ zabbix_win_install_dir }}\{{ zabbix_win_package }}' register: file_info + tags: + - install - name: "Windows | Check if agent binaries in place" ansible.windows.win_stat: path: "{{ zabbix_win_exe_path }}" register: zabbix_windows_binaries + tags: + - install - name: "Windows | Download Zabbix Agent Zip file" ansible.windows.win_get_url: @@ -192,12 +225,16 @@ register: zabbix_agent_win_download_zip until: zabbix_agent_win_download_zip is succeeded throttle: "{{ zabbix_download_throttle | default(5) | int }}" + tags: + - install - name: "Windows | Unzip file" community.windows.win_unzip: src: '{{ zabbix_win_install_dir }}\{{ zabbix_win_package }}' dest: "{{ zabbix_win_install_dir }}" creates: "{{ zabbix_win_exe_path }}" + tags: + - install - name: "Windows | Cleanup downloaded Zabbix Agent Zip file" ansible.windows.win_file: @@ -205,6 +242,8 @@ state: absent when: - zabbix_agent_win_download_zip.changed + tags: + - install - name: "Windows | Copy binary files to expected location" ansible.windows.win_copy: @@ -217,6 +256,8 @@ when: - zabbix_win_install_dir_bin is defined - not (zabbix_agent2 | bool) + tags: + - install - name: "Windows | Copy binary files to expected location (zabbix-agent2)" ansible.windows.win_copy: @@ -228,39 +269,49 @@ when: - zabbix_win_install_dir_bin is defined - zabbix_agent2 | bool + tags: + - install - set_fact: zabbix_win_exe_path: "{{ zabbix_win_install_dir_bin }}\\zabbix_agentd.exe" when: - zabbix_win_install_dir_bin is defined - not (zabbix_agent2 | bool) + tags: + - install - set_fact: zabbix_win_exe_path: "{{ zabbix_win_install_dir_bin }}\\zabbix_agent2.exe" when: - zabbix_win_install_dir_bin is defined - zabbix_agent2 | bool + tags: + - install - name: "Create directory for PSK file if not exist." - win_file: + ansible.windows.win_file: path: "{{ zabbix_agent_tlspskfile | win_dirname }}" state: directory when: - zabbix_agent_tlspskfile is defined - zabbix_agent_tlspskfile - not (zabbix_agent2 | bool) + tags: + - config - name: "Create directory for PSK file if not exist (zabbix-agent2)" - win_file: + ansible.windows.win_file: path: "{{ zabbix_agent2_tlspskfile | win_dirname }}" state: directory when: - zabbix_agent2_tlspskfile is defined - zabbix_agent2_tlspskfile - zabbix_agent2 | bool + tags: + - config - name: "Place TLS PSK File" - win_copy: + ansible.windows.win_copy: dest: "{{ zabbix_agent_tlspskfile }}" content: "{{ zabbix_agent_tlspsk_secret }}" when: @@ -270,9 +321,11 @@ - not (zabbix_agent2 | bool) notify: - restart win zabbix agent + tags: + - config - name: "Place TLS PSK File (zabbix-agent2)" - win_copy: + ansible.windows.win_copy: dest: "{{ zabbix_agent2_tlspskfile }}" content: "{{ zabbix_agent2_tlspsk_secret }}" when: @@ -282,25 +335,18 @@ - zabbix_agent2 | bool notify: - restart win zabbix agent + tags: + - config - name: "Windows | Check if windows service exist" ansible.windows.win_service: name: "{{ zabbix_win_svc_name }}" register: zabbix_windows_service + tags: + - service - name: "Windows | Register Service" ansible.windows.win_command: '"{{ zabbix_win_exe_path }}" --config "{{ zabbix_win_install_dir_conf }}\{{ zabbix_win_config_name }}" --install' when: not zabbix_windows_service.exists - -- name: "Windows | Set service startup mode to auto, ensure it is started and set auto-recovery" - ansible.windows.win_service: - name: "{{ zabbix_win_svc_name }}" - start_mode: auto - failure_actions: - - type: restart - delay_ms: 5000 - - type: restart - delay_ms: 10000 - - type: restart - delay_ms: 20000 - failure_reset_period_sec: 86400 + tags: + - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows_conf.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows_conf.yml index f6c5c331e..72dee230f 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows_conf.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/Windows_conf.yml @@ -1,17 +1,20 @@ --- - - name: "Set default ip address for zabbix_agent_ip" - set_fact: + ansible.builtin.set_fact: zabbix_agent_ip: "{{ hostvars[inventory_hostname]['ansible_ip_addresses'] | ansible.utils.ipv4 | first }}" when: - zabbix_agent_ip is not defined - "'ansible_ip_addresses' in hostvars[inventory_hostname]" + tags: + - config - name: "Windows | Configure zabbix-agent" ansible.windows.win_template: src: "{{ zabbix_win_config_name }}.j2" dest: "{{ zabbix_win_install_dir_conf }}\\{{ zabbix_win_config_name }}" notify: restart win zabbix agent + tags: + - config - name: "Windows | Set service startup mode to auto, ensure it is started and set auto-recovery" ansible.windows.win_service: @@ -19,19 +22,23 @@ start_mode: auto state: started failure_actions: - - type: restart - delay_ms: 5000 - - type: restart - delay_ms: 10000 - - type: restart - delay_ms: 20000 + - type: restart + delay_ms: 5000 + - type: restart + delay_ms: 10000 + - type: restart + delay_ms: 20000 failure_reset_period_sec: 86400 + tags: + - config - name: "Windows | Check firewall service" ansible.windows.win_service_info: name: MpsSvc register: firewall_info when: zabbix_win_firewall_management + tags: + - config - name: "Windows | Firewall rule" community.windows.win_firewall_rule: @@ -45,3 +52,5 @@ when: - zabbix_win_firewall_management - firewall_info.services[0].state == 'started' or firewall_info.services[0].start_mode == 'auto' + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/api.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/api.yml index 13f734edc..4de342645 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/api.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/api.yml @@ -3,14 +3,11 @@ community.zabbix.zabbix_group: host_group: "{{ zabbix_host_groups }}" state: "{{ zabbix_agent_hostgroups_state }}" - validate_certs: "{{ zabbix_api_validate_certs|default(omit) }}" - timeout: "{{ zabbix_api_timeout }}" when: - zabbix_api_create_hostgroup | bool register: zabbix_api_hostgroup_created until: zabbix_api_hostgroup_created is succeeded delegate_to: "{{ zabbix_api_server_host }}" - become: false tags: - api @@ -32,8 +29,6 @@ tls_subject: "{{ zabbix_agent_tls_subject | default(omit) }}" tls_accept: "{{ zabbix_agent_tls_config[zabbix_agent_tlsaccept if zabbix_agent_tlsaccept else 'unencrypted'] }}" tls_connect: "{{ zabbix_agent_tls_config[zabbix_agent_tlsconnect if zabbix_agent_tlsconnect else 'unencrypted'] }}" - validate_certs: "{{ zabbix_api_validate_certs | default(omit) }}" - timeout: "{{ zabbix_api_timeout }}" description: "{{ zabbix_agent_description | default(omit) }}" inventory_zabbix: "{{ zabbix_agent_inventory_zabbix | default({}) }}" ipmi_authtype: "{{ zabbix_agent_ipmi_authtype | default(omit) }}" @@ -46,7 +41,6 @@ register: zabbix_api_host_created until: zabbix_api_host_created is succeeded delegate_to: "{{ zabbix_api_server_host }}" - become: false changed_when: false tags: - api @@ -69,8 +63,6 @@ tls_subject: "{{ zabbix_agent2_tls_subject | default(omit) }}" tls_accept: "{{ zabbix_agent_tls_config[zabbix_agent2_tlsaccept if zabbix_agent2_tlsaccept else 'unencrypted'] }}" tls_connect: "{{ zabbix_agent_tls_config[zabbix_agent2_tlsconnect if zabbix_agent2_tlsconnect else 'unencrypted'] }}" - validate_certs: "{{ zabbix_api_validate_certs | default(omit) }}" - timeout: "{{ zabbix_api_timeout }}" description: "{{ zabbix_agent_description | default(omit) }}" inventory_zabbix: "{{ zabbix_agent_inventory_zabbix | default({}) }}" ipmi_authtype: "{{ zabbix_agent_ipmi_authtype | default(omit) }}" @@ -83,7 +75,6 @@ register: zabbix_api_host_created until: zabbix_api_host_created is succeeded delegate_to: "{{ zabbix_api_server_host }}" - become: false changed_when: false tags: - api @@ -94,8 +85,6 @@ macro_name: "{{ item.macro_key }}" macro_value: "{{ item.macro_value }}" macro_type: "{{ item.macro_type|default('text') }}" - validate_certs: "{{ zabbix_api_validate_certs | default(omit) }}" - timeout: "{{ zabbix_api_timeout }}" with_items: "{{ zabbix_agent_macros | default([]) }}" when: - zabbix_agent_macros is defined @@ -103,6 +92,5 @@ register: zabbix_api_hostmarcro_created until: zabbix_api_hostmarcro_created is succeeded delegate_to: "{{ zabbix_api_server_host }}" - become: false tags: - api diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/firewall.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/firewall.yml deleted file mode 100644 index 24ba96cb0..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/firewall.yml +++ /dev/null @@ -1,55 +0,0 @@ ---- - -- name: "Firewall | Configure IPTables (zabbix_agent_listenport)" - iptables: - action: "{{ zabbix_agent_firewall_action }}" - destination_port: "{{ zabbix_agent_listenport | string }}" - source: "{{ zabbix_agent_firewall_source | default(omit) }}" - protocol: tcp - chain: "{{ zabbix_agent_firewall_chain }}" - jump: ACCEPT - become: true - when: - - zabbix_agent_firewall_enable | bool - -- name: "Firewall | Configure IPTables (zabbix_agent_jmx_listenport)" - iptables: - action: "{{ zabbix_agent_firewall_action }}" - destination_port: "{{ zabbix_agent_listenport | string }}" - source: "{{ zabbix_agent_firewall_source | default(omit) }}" - protocol: tcp - chain: "{{ zabbix_agent_firewall_chain }}" - jump: ACCEPT - become: true - when: - - zabbix_agent_firewall_enable | bool - - zabbix_agent_jmx_listenport | bool - -- name: "Firewall | Configure firewalld (zabbix_agent_listenport)" - ansible.posix.firewalld: - rich_rule: 'rule family="ipv4" source address="{{ zabbix_agent_firewalld_source }}" port protocol="tcp" port="{{ zabbix_agent_listenport }}" accept' - zone: "{{ zabbix_agent_firewalld_zone }}" - permanent: true - immediate: true - state: enabled - become: true - when: - - zabbix_agent_firewalld_enable | bool - notify: - - firewalld-reload - tags: zabbix_agent_firewalld_enable - -- name: "Firewall | Configure firewalld (zabbix_agent_jmx_listenport)" - ansible.posix.firewalld: - rich_rule: 'rule family="ipv4" source address="{{ zabbix_agent_firewalld_source }}" port protocol="tcp" port="{{ zabbix_agent_jmx_listenport }}" accept' - zone: "{{ zabbix_agent_firewalld_zone }}" - permanent: true - immediate: true - state: enabled - become: true - when: - - zabbix_agent_firewalld_enable | bool - - zabbix_agent_jmx_listenport | bool - notify: - - firewalld-reload - tags: zabbix_agent_firewalld_enable diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/macOS.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/macOS.yml index 0904c39f1..7bcdd6fe3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/macOS.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/macOS.yml @@ -1,7 +1,7 @@ --- # Tasks specific for macOS - name: "macOS | Check installed package version" - shell: | + ansible.builtin.shell: | set -o pipefail pkgutil --pkg-info 'com.zabbix.pkg.ZabbixAgent' | grep 'version:' | cut -d ' ' -f 2 register: pkgutil_version @@ -10,15 +10,13 @@ failed_when: pkgutil_version.rc == 2 - name: "macOS | Download the Zabbix package" - get_url: + ansible.builtin.get_url: url: "{{ zabbix_mac_download_link }}" dest: "/tmp/{{ zabbix_mac_package }}" mode: 0644 when: pkgutil_version.stdout != zabbix_version_long - name: "macOS | Install the Zabbix package" - command: installer -pkg "/tmp/{{ zabbix_mac_package }}" -target / + ansible.builtin.command: installer -pkg "/tmp/{{ zabbix_mac_package }}" -target / become: true when: pkgutil_version.stdout != zabbix_version_long - tags: - - zabbix-agent diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/main.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/main.yml index 5ce427ce4..f5f87d18f 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/main.yml @@ -1,90 +1,52 @@ --- # tasks file for zabbix_agent - -- name: "Set variables specific for Zabbix Agent 2" - set_fact: - zabbix_agent_service: zabbix-agent2 - zabbix_agent_package: zabbix-agent2 - when: - - zabbix_agent2 is defined - - zabbix_agent2 +- name: "Include OS-specific variables" + ansible.builtin.include_vars: "{{ ansible_os_family }}.yml" tags: - always -- name: "Fix facts for linuxmint - distribution release" - set_fact: - zabbix_agent_distribution_release: xenial - when: - - ansible_os_family == "Linuxmint" - - ansible_distribution_release == "sonya" or ansible_distribution_release == "serena" +- name: Determine Latest Supported Zabbix Version + ansible.builtin.set_fact: + zabbix_agent_version: "{{ zabbix_valid_agent_versions[ansible_distribution_major_version][0] | default(6.4) }}" + when: zabbix_agent_version is not defined or zabbix_agent_version is none tags: - always -- name: "Fix facts for linuxmint - family" - set_fact: - zabbix_agent_os_family: Debian - when: - - ansible_os_family == "Linuxmint" +- name: Set More Variables + ansible.builtin.set_fact: + zabbix_valid_version: "{{ zabbix_agent_version|float in zabbix_valid_agent_versions[ansible_distribution_major_version] }}" tags: - always -- name: "Fix facts for XCP-ng - family" - set_fact: - zabbix_agent_os_family: RedHat - when: - - ansible_os_family == "XCP-ng" - -- name: "Include OS-specific variables" - include_vars: "{{ zabbix_agent_os_family }}.yml" +- name: Stopping Install of Invalid Version + ansible.builtin.fail: + msg: Zabbix version {{ zabbix_agent_version }} is not supported on {{ ansible_distribution }} {{ ansible_distribution_major_version }} + when: not zabbix_valid_version tags: - always -- name: Determine Latest Supported Zabbix Version - set_fact: - zabbix_agent_version: "{{ zabbix_valid_agent_versions[ansible_distribution_major_version][0] | default(6.0) }}" - when: zabbix_agent_version is not defined +- name: Setting Zabbix API Server Port + ansible.builtin.set_fact: + zabbix_api_server_port: "{{ '443' if zabbix_api_use_ssl|bool else '80' }}" + when: zabbix_api_server_port is undefined -- name: "Reset zabbix_agent_version for Ubuntu 22.04 to 6.0" - # README https://support.zabbix.com/browse/ZBXNEXT-7624 - set_fact: - zabbix_version: 6.0 - zabbix_agent_version: 6.0 - when: - - ansible_distribution_release is defined - - ansible_distribution_release == "jammy" - - ( zabbix_agent_version is version ('6.0','lt') or - zabbix_version is version ('6.0','lt') ) - -- name: "Install the correct repository" - include_tasks: "{{ zabbix_agent_os_family if (zabbix_agent_os_family not in ['Sangoma']) else 'RedHat' }}.yml" +- name: "Set variables specific for Zabbix Agent 2" + ansible.builtin.set_fact: + zabbix_agent_service: zabbix-agent2 + zabbix_agent_package: zabbix-agent2 when: - - not (zabbix_agent_docker | bool) + - zabbix_agent2 is defined + - zabbix_agent2 tags: - always -- name: "Set the 'ansible_python_interpreter' to the one we use for running this playbook." - set_fact: - ansible_python_interpreter: "{{ ansible_playbook_python }}" - delegate_to: localhost - delegate_facts: true - when: - - (zabbix_install_pip_packages | bool) or (zabbix_api_create_hostgroup | bool) or (zabbix_api_create_hosts | bool) - -- name: "Install local python-netaddr package" - pip: - name: netaddr - state: present - register: zabbix_python_netaddr_package_installed - until: zabbix_python_netaddr_package_installed is succeeded - delegate_to: localhost - run_once: true - become: "{{ zabbix_agent_become_on_localhost }}" +- name: "Install the correct repository" + ansible.builtin.include_tasks: "{{ ansible_os_family }}.yml" when: - - zabbix_install_pip_packages | bool - - ansible_all_ipv4_addresses is defined or (zabbix_agent_ip is not defined and total_private_ip_addresses is defined) + - not (zabbix_agent_docker | bool) - name: "Encrypt with TLS PSK auto management" - include_tasks: tlspsk_auto.yml + ansible.builtin.include_tasks: tlspsk_auto.yml when: - not zabbix_agent2 - zabbix_agent_tlspsk_auto | bool @@ -92,7 +54,7 @@ - (zabbix_agent_tlspsk_secret is undefined) or (zabbix_agent_tlspsk_secret | length == '0') - name: "Encrypt with TLS PSK auto management" - include_tasks: tlspsk_auto_agent2.yml + ansible.builtin.include_tasks: tlspsk_auto_agent2.yml when: - zabbix_agent2 | bool - zabbix_agent2_tlspsk_auto | bool @@ -100,44 +62,33 @@ - (zabbix_agent2_tlspsk_secret is undefined) or (zabbix_agent2_tlspsk_secret | length == '0') - name: "Configure Agent" - include_tasks: Windows_conf.yml + ansible.builtin.include_tasks: Windows_conf.yml when: - - zabbix_agent_os_family == "Windows" - tags: - - always + - ansible_os_family == "Windows" - name: "Configure Agent" - include_tasks: Darwin.yml + ansible.builtin.include_tasks: Linux.yml when: - - zabbix_agent_os_family == "Darwin" - tags: - - always - -- name: "Configure Agent" - include_tasks: Linux.yml - when: - - (zabbix_agent_os_family != "Windows" and zabbix_agent_os_family != "Darwin") or (zabbix_agent_docker | bool) - tags: - - always + - (ansible_os_family != "Windows" and ansible_os_family != "Darwin") or (zabbix_agent_docker | bool) - name: "Run the API calls to Zabbix Server" vars: gather_facts: false ansible_user: "{{ zabbix_api_login_user }}" + ansible_httpapi_use_ssl: "{{ zabbix_api_use_ssl }}" ansible_network_os: community.zabbix.zabbix ansible_connection: httpapi # Can't think of a way to make http_login_* vars be undefined -( - http_login_user: "{{ zabbix_api_http_user | default(zabbix_http_user | default(-42)) }}" - http_login_password: "{{ zabbix_api_http_password | default(zabbix_http_password | default(-42)) }}" - include_tasks: api.yml + http_login_user: "{{ zabbix_api_http_user | default(-42) }}" + http_login_password: "{{ zabbix_api_http_password | default(-42) }}" + ansible.builtin.include_tasks: api.yml when: - (zabbix_api_create_hostgroup | bool) or (zabbix_api_create_hosts | bool) tags: - api - name: "Including userparameters" - include_tasks: "userparameter.yml" + ansible.builtin.include_tasks: "userparameter.yml" when: zabbix_agent_userparameters|length > 0 tags: - - zabbix-agent - - userparameter + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/remove.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/remove.yml index 57968146c..181329a32 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/remove.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/remove.yml @@ -1,9 +1,9 @@ --- - name: Pull service facts - service_facts: + ansible.builtin.service_facts: -- name: "Remove | Make sure the \"old\" zabbix-agent service stopped" - service: +- name: 'Remove | Make sure the "old" zabbix-agent service stopped' + ansible.builtin.service: name: "zabbix-agent" state: stopped enabled: false @@ -13,13 +13,13 @@ ansible_facts.services["zabbix-agent"] is defined - name: "Remove | Package removal" - package: + ansible.builtin.package: name: "zabbix-agent" state: absent become: true - name: "Remove | Remove the agent-include-dir" - file: + ansible.builtin.file: path: "{{ zabbix_agent_include }}" state: absent become: true diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/selinux.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/selinux.yml index b7ec69e7b..2b11d1a47 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/selinux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/selinux.yml @@ -1,7 +1,6 @@ --- - - name: "SELinux | Debian | Install policycoreutils-python" - apt: + ansible.builtin.apt: pkg: policycoreutils-python-utils state: present update_cache: true @@ -15,10 +14,12 @@ until: zabbix_agent_package_installed is succeeded become: true when: - - zabbix_agent_os_family == "Debian" + - ansible_os_family == "Debian" + tags: + - install - name: "SELinux | RedHat | Install policycoreutils-python" - package: + ansible.builtin.package: name: policycoreutils-python state: installed environment: @@ -27,15 +28,14 @@ register: zabbix_agent_policycoreutils_installed until: zabbix_agent_policycoreutils_installed is succeeded when: - - zabbix_agent_os_family == "RedHat" + - ansible_os_family == "RedHat" - (zabbix_agent_distribution_major_version == "6" or zabbix_agent_distribution_major_version == "7") become: true tags: - - init - - zabbix-agent + - install - name: "SELinux | RedHat | Install python3-policycoreutils on RHEL8" - package: + ansible.builtin.package: name: python3-policycoreutils state: installed environment: @@ -44,59 +44,67 @@ register: zabbix_agent_policycoreutils_installed until: zabbix_agent_policycoreutils_installed is succeeded when: - - zabbix_agent_os_family == "RedHat" + - ansible_os_family == "RedHat" - ansible_distribution_major_version == "8" become: true tags: - - init - - zabbix-agent + - install - name: "SELinux | RedHat | Install selinux-policy-targeted" - package: + ansible.builtin.package: name: selinux-policy-targeted state: installed register: zabbix_agent_selinuxpolicytargeted_installed until: zabbix_agent_selinuxpolicytargeted_installed is succeeded when: - - zabbix_agent_os_family == "RedHat" + - ansible_os_family == "RedHat" become: true tags: - - init - - zabbix-agent + - install # straight to getenforce binary , workaround for missing python_selinux library - name: "SELinux | Get getenforce binary" - stat: + ansible.builtin.stat: path: /usr/sbin/getenforce register: getenforce_bin become: true + tags: + - always - name: "SELinux | Collect getenforce output" - command: /usr/sbin/getenforce + ansible.builtin.command: /usr/sbin/getenforce register: sestatus - when: 'getenforce_bin.stat.exists' + when: "getenforce_bin.stat.exists" changed_when: false become: true check_mode: false + tags: + - always - name: "SELinux | Set zabbix_selinux to true if getenforce returns Enforcing or Permissive" - set_fact: + ansible.builtin.set_fact: zabbix_selinux: "{{ true }}" when: - 'getenforce_bin.stat.exists and ("Enforcing" in sestatus.stdout or "Permissive" in sestatus.stdout)' + tags: + - always - name: "SELinux | Allow zabbix_agent to start (SELinux)" community.general.selinux_permissive: name: zabbix_agent_t permissive: true become: true + tags: + - config - name: "SELinux | Allow zabbix to run sudo commands (SELinux)" ansible.posix.seboolean: name: zabbix_run_sudo persistent: true state: true + become: true when: - ansible_selinux.status == "enabled" - selinux_allow_zabbix_run_sudo|bool - tags: selinux + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto.yml index aaa733872..ad7d49aa3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto.yml @@ -1,12 +1,14 @@ --- -- include_tasks: tlspsk_auto_linux.yml - when: (zabbix_agent_os_family != "Windows") or (zabbix_agent_docker | bool) +- ansible.builtin.include_tasks: tlspsk_auto_linux.yml + when: (ansible_os_family != "Windows") or (zabbix_agent_docker | bool) -- include_tasks: tlspsk_auto_windows.yml - when: zabbix_agent_os_family == "Windows" +- ansible.builtin.include_tasks: tlspsk_auto_windows.yml + when: ansible_os_family == "Windows" - name: AutoPSK | Default tlsaccept and tlsconnect to enforce PSK - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlsaccept: psk zabbix_agent_tlsconnect: psk when: zabbix_api_create_hosts + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2.yml index 77eafc878..6e5f8dc4d 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2.yml @@ -1,12 +1,14 @@ --- - include_tasks: tlspsk_auto_agent2_linux.yml - when: (zabbix_agent_os_family != "Windows") or (zabbix_agent_docker | bool) + when: (ansible_os_family != "Windows") or (zabbix_agent_docker | bool) - include_tasks: tlspsk_auto_agent2_windows.yml - when: zabbix_agent_os_family == "Windows" + when: ansible_os_family == "Windows" - name: AutoPSK | Default tlsaccept and tlsconnect to enforce PSK - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlsaccept: psk zabbix_agent2_tlsconnect: psk when: zabbix_api_create_hosts + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_common.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_common.yml index 4a7b897ae..3f6e0d2cd 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_common.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_common.yml @@ -1,38 +1,45 @@ --- -# Process PSK Secret +# Process PSK Secret - name: AutoPSK | Save existing TLS PSK secret - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspsk_read: "{{ zabbix_agent2_tlspsk_base64['content'] | b64decode | trim }}" when: zabbix_agent2_tlspskcheck.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Use existing TLS PSK secret - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspsk_secret: "{{ zabbix_agent2_tlspsk_read }}" - when: - - zabbix_agent2_tlspskcheck.stat.exists + when: + - zabbix_agent2_tlspskcheck.stat.exists - zabbix_agent2_tlspsk_read|length >= 32 no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Generate new TLS PSK secret - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspsk_secret: "{{ lookup('password', '/dev/null chars=hexdigits length=64') }}" when: - not zabbix_agent2_tlspskcheck.stat.exists - (zabbix_agent2_tlspsk_read is not defined) or (zabbix_agent2_tlspsk_read|length < 32) no_log: "{{ ansible_verbosity < 3 }}" - + tags: + - config # Process PSK Identity - name: AutoPSK | Use existing TLS PSK identity - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspskidentity: "{{ zabbix_agent2_tlspskidentity_base64['content'] | b64decode | trim }}" - when: + when: - zabbix_agent2_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Generate new TLS PSK identity - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspskidentity: >- {{ zabbix_agent_visible_hostname @@ -42,3 +49,5 @@ }} when: not zabbix_agent2_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_linux.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_linux.yml index 721f1cb86..aaff36128 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_linux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_linux.yml @@ -1,42 +1,52 @@ --- - name: AutoPSK | Set default path variables (Linux) - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspskfile: "/etc/zabbix/tls_psk_auto.secret" zabbix_agent2_tlspskidentity_file: "/etc/zabbix/tls_psk_auto.identity" + tags: + - config - name: AutoPSK | Check for existing TLS PSK file (Linux) - stat: + ansible.builtin.stat: path: "{{ zabbix_agent2_tlspskfile }}" register: zabbix_agent2_tlspskcheck become: true + tags: + - config - name: AutoPSK | Check for existing TLS PSK identity (Linux) - stat: + ansible.builtin.stat: path: "{{ zabbix_agent2_tlspskidentity_file }}" register: zabbix_agent2_tlspskidentity_check become: true + tags: + - config - name: AutoPSK | read existing TLS PSK file (Linux) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent2_tlspskfile }}" register: zabbix_agent2_tlspsk_base64 become: true - when: + when: - zabbix_agent2_tlspskcheck.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Read existing TLS PSK identity file (Linux) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent2_tlspskidentity_file }}" register: zabbix_agent2_tlspskidentity_base64 become: true when: zabbix_agent2_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - include_tasks: tlspsk_auto_agent2_common.yml - name: AutoPSK | Template TLS PSK identity in file (Linux) - copy: + ansible.builtin.copy: dest: "{{ zabbix_agent2_tlspskidentity_file }}" content: "{{ zabbix_agent2_tlspskidentity }}" owner: zabbix @@ -49,9 +59,11 @@ notify: - restart zabbix-agent - restart mac zabbix agent - + tags: + - config + - name: AutoPSK | Template TLS PSK secret in file (Linux) - copy: + ansible.builtin.copy: dest: "{{ zabbix_agent2_tlspskfile }}" content: "{{ zabbix_agent2_tlspsk_secret }}" owner: zabbix @@ -64,3 +76,5 @@ notify: - restart zabbix-agent - restart mac zabbix agent + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_windows.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_windows.yml index 770d60776..3e1529e6b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_windows.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_agent2_windows.yml @@ -1,38 +1,48 @@ --- - name: AutoPSK | Set default path variables for Windows - set_fact: + ansible.builtin.set_fact: zabbix_agent2_tlspskfile: "{{ zabbix_win_install_dir }}\\tls_psk_auto.secret.txt" zabbix_agent2_tlspskidentity_file: "{{ zabbix_win_install_dir }}\\tls_psk_auto.identity.txt" + tags: + - config - name: AutoPSK | Check for existing TLS PSK file (Windows) ansible.windows.win_stat: path: "{{ zabbix_agent2_tlspskfile }}" register: zabbix_agent2_tlspskcheck + tags: + - config - name: AutoPSK | Check for existing TLS PSK identity (Windows) ansible.windows.win_stat: path: "{{ zabbix_agent2_tlspskidentity_file }}" register: zabbix_agent2_tlspskidentity_check + tags: + - config - name: AutoPSK | read existing TLS PSK file (Windows) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent2_tlspskfile }}" register: zabbix_agent2_tlspsk_base64 - when: + when: - zabbix_agent2_tlspskcheck.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Read existing TLS PSK identity file (Windows) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent2_tlspskidentity_file }}" register: zabbix_agent2_tlspskidentity_base64 when: zabbix_agent2_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config -- include_tasks: tlspsk_auto_agent2_common.yml +- ansible.builtin.include_tasks: tlspsk_auto_agent2_common.yml - name: Windows | AutoPSK | Template TLS PSK identity in file (Windows) - win_copy: + ansible.windows.win_copy: dest: "{{ zabbix_agent2_tlspskidentity_file }}" content: "{{ zabbix_agent2_tlspskidentity }}" when: @@ -40,9 +50,11 @@ - zabbix_agent2_tlspskidentity is defined notify: - restart win zabbix agent - + tags: + - config + - name: AutoPSK | Template TLS PSK secret in file (Windows) - win_copy: + ansible.windows.win_copy: dest: "{{ zabbix_agent2_tlspskfile }}" content: "{{ zabbix_agent2_tlspsk_secret }}" when: @@ -50,3 +62,5 @@ - zabbix_agent2_tlspsk_secret is defined notify: - restart win zabbix agent + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_common.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_common.yml index 4b02fafb6..05ef24d0e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_common.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_common.yml @@ -1,37 +1,44 @@ --- # Process PSK Secret - name: AutoPSK | Save existing TLS PSK secret - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspsk_read: "{{ zabbix_agent_tlspsk_base64['content'] | b64decode | trim }}" when: zabbix_agent_tlspskcheck.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Use existing TLS PSK secret - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspsk_secret: "{{ zabbix_agent_tlspsk_read }}" when: - zabbix_agent_tlspskcheck.stat.exists - zabbix_agent_tlspsk_read|length >= 32 no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Generate new TLS PSK secret - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspsk_secret: "{{ lookup('password', '/dev/null chars=hexdigits length=64') }}" when: - (not zabbix_agent_tlspskcheck.stat.exists) or (zabbix_agent_tlspsk_read|length < 32) no_log: "{{ ansible_verbosity < 3 }}" - + tags: + - config # Process PSK Identity - name: AutoPSK | Use existing TLS PSK identity - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspskidentity: "{{ zabbix_agent_tlspskidentity_base64['content'] | b64decode | trim }}" when: - zabbix_agent_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Generate new TLS PSK identity - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspskidentity: >- {{ zabbix_agent_visible_hostname @@ -41,3 +48,5 @@ }} when: not zabbix_agent_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_linux.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_linux.yml index 1dbea4082..8cc711fcb 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_linux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_linux.yml @@ -1,42 +1,52 @@ --- - name: AutoPSK | Set default path variables (Linux) - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspskfile: "/etc/zabbix/tls_psk_auto.secret" zabbix_agent_tlspskidentity_file: "/etc/zabbix/tls_psk_auto.identity" + tags: + - config - name: AutoPSK | Check for existing TLS PSK file (Linux) - stat: + ansible.builtin.stat: path: "{{ zabbix_agent_tlspskfile }}" register: zabbix_agent_tlspskcheck become: true + tags: + - config - name: AutoPSK | Check for existing TLS PSK identity (Linux) - stat: + ansible.builtin.stat: path: "{{ zabbix_agent_tlspskidentity_file }}" register: zabbix_agent_tlspskidentity_check become: true + tags: + - config - name: AutoPSK | read existing TLS PSK file (Linux) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent_tlspskfile }}" register: zabbix_agent_tlspsk_base64 become: true - when: + when: - zabbix_agent_tlspskcheck.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Read existing TLS PSK identity file (Linux) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent_tlspskidentity_file }}" register: zabbix_agent_tlspskidentity_base64 become: true when: zabbix_agent_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - include_tasks: tlspsk_auto_common.yml - name: AutoPSK | Template TLS PSK identity in file (Linux) - copy: + ansible.builtin.copy: dest: "{{ zabbix_agent_tlspskidentity_file }}" content: "{{ zabbix_agent_tlspskidentity }}" owner: zabbix @@ -49,9 +59,11 @@ notify: - restart zabbix-agent - restart mac zabbix agent - + tags: + - config + - name: AutoPSK | Template TLS PSK secret in file (Linux) - copy: + ansible.builtin.copy: dest: "{{ zabbix_agent_tlspskfile }}" content: "{{ zabbix_agent_tlspsk_secret }}" owner: zabbix @@ -64,3 +76,5 @@ notify: - restart zabbix-agent - restart mac zabbix agent + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_windows.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_windows.yml index 146cfd457..b9289ac49 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_windows.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/tlspsk_auto_windows.yml @@ -1,38 +1,48 @@ --- - name: AutoPSK | Set default path variables for Windows - set_fact: + ansible.builtin.set_fact: zabbix_agent_tlspskfile: "{{ zabbix_win_install_dir }}\\tls_psk_auto.secret.txt" zabbix_agent_tlspskidentity_file: "{{ zabbix_win_install_dir }}\\tls_psk_auto.identity.txt" + tags: + - config - name: AutoPSK | Check for existing TLS PSK file (Windows) ansible.windows.win_stat: path: "{{ zabbix_agent_tlspskfile }}" register: zabbix_agent_tlspskcheck + tags: + - config - name: AutoPSK | Check for existing TLS PSK identity (Windows) ansible.windows.win_stat: path: "{{ zabbix_agent_tlspskidentity_file }}" register: zabbix_agent_tlspskidentity_check + tags: + - config - name: AutoPSK | read existing TLS PSK file (Windows) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent_tlspskfile }}" register: zabbix_agent_tlspsk_base64 - when: + when: - zabbix_agent_tlspskcheck.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - name: AutoPSK | Read existing TLS PSK identity file (Windows) - slurp: + ansible.builtin.slurp: src: "{{ zabbix_agent_tlspskidentity_file }}" register: zabbix_agent_tlspskidentity_base64 when: zabbix_agent_tlspskidentity_check.stat.exists no_log: "{{ ansible_verbosity < 3 }}" + tags: + - config - include_tasks: tlspsk_auto_common.yml - name: AutoPSK | Template TLS PSK identity in file (Windows) - win_copy: + ansible.windows.win_copy: dest: "{{ zabbix_agent_tlspskidentity_file }}" content: "{{ zabbix_agent_tlspskidentity }}" when: @@ -40,14 +50,18 @@ - zabbix_agent_tlspskidentity is defined notify: - restart win zabbix agent - + tags: + - config + - name: AutoPSK | Template TLS PSK secret in file (Windows) - win_copy: + ansible.windows.win_copy: dest: "{{ zabbix_agent_tlspskfile }}" content: "{{ zabbix_agent_tlspsk_secret }}" when: - zabbix_agent_tlspskfile is defined - zabbix_agent_tlspsk_secret is defined - - zabbix_agent_os_family == "Windows" + - ansible_os_family == "Windows" notify: - restart win zabbix agent + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/userparameter.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/userparameter.yml index 9a86b536a..a80be1736 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/userparameter.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/tasks/userparameter.yml @@ -1,85 +1,87 @@ --- - block: - - name: "Windows | Installing user-defined userparameters" - ansible.windows.win_template: - src: "{{ zabbix_agent_userparameters_templates_src }}/{{ item.name }}.j2" - dest: '{{ zabbix_agent_win_include }}\{{ item.name }}.conf' - notify: - - restart win zabbix agent - with_items: "{{ zabbix_agent_userparameters }}" - - - name: "Windows | Installing user-defined scripts" - ansible.windows.win_copy: - src: "{{ zabbix_agent_userparameters_scripts_src }}/{{ item.scripts_dir }}" - dest: '{{ zabbix_win_install_dir }}\scripts\' - notify: - - restart win zabbix agent - with_items: "{{ zabbix_agent_userparameters }}" - when: item.scripts_dir is defined - - when: zabbix_agent_os_family == "Windows" + - name: "Windows | Installing user-defined userparameters" + ansible.windows.win_template: + src: "{{ zabbix_agent_userparameters_templates_src }}/{{ item.name }}.j2" + dest: '{{ zabbix_agent_win_include }}\{{ item.name }}.conf' + notify: + - restart win zabbix agent + with_items: "{{ zabbix_agent_userparameters }}" + - name: "Windows | Installing user-defined scripts" + ansible.windows.win_copy: + src: "{{ zabbix_agent_userparameters_scripts_src }}/{{ item.scripts_dir }}" + dest: '{{ zabbix_win_install_dir }}\scripts\' + notify: + - restart win zabbix agent + with_items: "{{ zabbix_agent_userparameters }}" + when: item.scripts_dir is defined + when: ansible_os_family == "Windows" + tags: + - config - block: - - name: "Installing user-defined userparameters" - template: - src: "{{ zabbix_agent_userparameters_templates_src }}/{{ item.name }}.j2" - dest: "{{ zabbix_agent_include }}/userparameter_{{ item.name }}.conf" - owner: zabbix - group: zabbix - mode: 0644 - notify: - - restart zabbix-agent - - restart mac zabbix agent - become: true - with_items: "{{ zabbix_agent_userparameters }}" - - - name: "Installing user-defined scripts" - copy: - src: "{{ zabbix_agent_userparameters_scripts_src }}/{{ item.scripts_dir }}" - dest: "/etc/zabbix/scripts/" - owner: zabbix - group: zabbix - mode: 0755 - notify: - - restart zabbix-agent - - restart mac zabbix agent - become: true - with_items: "{{ zabbix_agent_userparameters }}" - when: item.scripts_dir is defined + - name: "Installing user-defined userparameters" + ansible.builtin.template: + src: "{{ zabbix_agent_userparameters_templates_src }}/{{ item.name }}.j2" + dest: "{{ zabbix_agent_include }}/userparameter_{{ item.name }}.conf" + owner: zabbix + group: zabbix + mode: 0644 + notify: + - restart zabbix-agent + - restart mac zabbix agent + become: true + with_items: "{{ zabbix_agent_userparameters }}" + - name: "Installing user-defined scripts" + ansible.builtin.copy: + src: "{{ zabbix_agent_userparameters_scripts_src }}/{{ item.scripts_dir }}" + dest: "/etc/zabbix/scripts/" + owner: zabbix + group: zabbix + mode: 0755 + notify: + - restart zabbix-agent + - restart mac zabbix agent + become: true + with_items: "{{ zabbix_agent_userparameters }}" + when: item.scripts_dir is defined when: - - zabbix_agent_os_family != "Windows" + - ansible_os_family != "Windows" - not zabbix_agent2 + tags: + - config - block: - - name: "Installing user-defined userparameters" - template: - src: "{{ zabbix_agent_userparameters_templates_src }}/{{ item.name }}.j2" - dest: "{{ zabbix_agent2_include }}/userparameter_{{ item.name }}.conf" - owner: zabbix - group: zabbix - mode: 0644 - notify: - - restart zabbix-agent - - restart mac zabbix agent - become: true - with_items: "{{ zabbix_agent_userparameters }}" - - - name: "Installing user-defined scripts" - copy: - src: "{{ zabbix_agent_userparameters_scripts_src }}/{{ item.scripts_dir }}" - dest: "/etc/zabbix/scripts/" - owner: zabbix - group: zabbix - mode: 0755 - notify: - - restart zabbix-agent - - restart mac zabbix agent - become: true - with_items: "{{ zabbix_agent_userparameters }}" - when: item.scripts_dir is defined + - name: "Installing user-defined userparameters" + ansible.builtin.template: + src: "{{ zabbix_agent_userparameters_templates_src }}/{{ item.name }}.j2" + dest: "{{ zabbix_agent2_include }}/userparameter_{{ item.name }}.conf" + owner: zabbix + group: zabbix + mode: 0644 + notify: + - restart zabbix-agent + - restart mac zabbix agent + become: true + with_items: "{{ zabbix_agent_userparameters }}" + - name: "Installing user-defined scripts" + ansible.builtin.copy: + src: "{{ zabbix_agent_userparameters_scripts_src }}/{{ item.scripts_dir }}" + dest: "/etc/zabbix/scripts/" + owner: zabbix + group: zabbix + mode: 0755 + notify: + - restart zabbix-agent + - restart mac zabbix agent + become: true + with_items: "{{ zabbix_agent_userparameters }}" + when: item.scripts_dir is defined when: - - zabbix_agent_os_family != "Windows" + - ansible_os_family != "Windows" - zabbix_agent2 + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agent2.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agent2.conf.j2 index 39829abc3..ea60d032e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agent2.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agent2.conf.j2 @@ -4,13 +4,13 @@ # This configuration file is "minimalized", which means all the original comments # are removed. The full documentation for your Zabbix Agent 2 can be found here: -# https://www.zabbix.com/documentation/{{ zabbix_version }}/en/manual/appendix/config/zabbix_agent2{{ "_win" if zabbix_agent_os_family == "Windows" else "" }} +# https://www.zabbix.com/documentation/{{ zabbix_agent_version }}/en/manual/appendix/config/zabbix_agent2{{ "_win" if ansible_os_family == "Windows" else "" }} -{% if zabbix_agent_os_family != "Windows" %} +{% if ansible_os_family != "Windows" %} PidFile={{ zabbix_agent2_pidfile }} {% endif %} LogType={{ zabbix_agent2_logtype }} -{% if zabbix_agent_os_family == "Windows" %} +{% if ansible_os_family == "Windows" %} LogFile={{ zabbix_agent2_win_logfile }} {% else %} LogFile={{ zabbix_agent2_logfile }} @@ -79,13 +79,18 @@ Alias={{ item }} {% endif %} {% endif %} Timeout={{ zabbix_agent2_timeout }} -{% if zabbix_agent_os_family == "Windows" %} +{% if ansible_os_family == "Windows" %} Include={{ zabbix_agent_win_include }} {% else %} Include={{ zabbix_agent2_include }}/{{ zabbix_agent2_include_pattern }} {% endif %} +{% if zabbix_agent2_additional_include is defined and zabbix_agent2_additional_include is iterable and zabbix_agent2_additional_include is not string %} +{% for include in zabbix_agent2_additional_include %} +Include={{ include }} +{% endfor %} +{% endif %} UnsafeUserParameters={{ zabbix_agent2_unsafeuserparameters }} -{% if zabbix_agent_os_family != "Windows" %} +{% if ansible_os_family != "Windows" %} ControlSocket={{ zabbix_agent2_controlsocket }} {% endif %} {% if zabbix_agent2_tlsconnect is defined and zabbix_agent2_tlsconnect %} @@ -128,7 +133,7 @@ Plugins.{{ my_name }}.{{ param }}={{ value }} {% endfor %} {% endfor %} {% endif %} -{% if zabbix_version is version('6.0', '>=') %} +{% if zabbix_agent_version is version('6.0', '>=') %} {% if zabbix_agent2_listenbacklog is defined and zabbix_agent2_listenbacklog %} ListenBacklog={{ zabbix_agent2_listenbacklog }} {% endif %} diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agentd.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agentd.conf.j2 index 5e5d31d9b..24af45bc3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agentd.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/templates/zabbix_agentd.conf.j2 @@ -4,15 +4,15 @@ # This configuration file is "minimalized", which means all the original comments # are removed. The full documentation for your Zabbix Agent can be found here: -# https://www.zabbix.com/documentation/{{ zabbix_version }}/en/manual/appendix/config/zabbix_agentd{{ "_win" if zabbix_agent_os_family == "Windows" else "" }} +# https://www.zabbix.com/documentation/{{ zabbix_agent_version }}/en/manual/appendix/config/zabbix_agentd{{ "_win" if ansible_os_family == "Windows" else "" }} -{% if zabbix_agent_os_family != "Windows" %} +{% if ansible_os_family != "Windows" %} PidFile={{ zabbix_agent_pidfile }} {% endif %} {% if zabbix_agent_version is version('3.0', '>=') %} LogType={{ zabbix_agent_logtype }} {% endif %} -{% if zabbix_agent_os_family == "Windows" %} +{% if ansible_os_family == "Windows" %} LogFile={{ zabbix_agent_win_logfile }} {% else %} LogFile={{ zabbix_agent_logfile }} @@ -66,7 +66,7 @@ RefreshActiveChecks={{ zabbix_agent_refreshactivechecks }} BufferSend={{ zabbix_agent_buffersend }} BufferSize={{ zabbix_agent_buffersize }} MaxLinesPerSecond={{ zabbix_agent_maxlinespersecond }} -{% if zabbix_version is version_compare('6.2', '>=') %} +{% if zabbix_agent_version is version_compare('6.2', '>=') %} HeartbeatFrequency={{ zabbix_agent_heartbeatfrequency }} {% endif %} {% if zabbix_agent_zabbix_alias is defined and zabbix_agent_zabbix_alias %} @@ -79,20 +79,25 @@ Alias={{ item }} {% endif %} {% endif %} Timeout={{ zabbix_agent_timeout }} -{% if zabbix_agent_os_family != "Windows" %} +{% if ansible_os_family != "Windows" %} AllowRoot={{ zabbix_agent_allowroot }} {% endif %} {% if zabbix_agent_runas_user is defined and zabbix_agent_runas_user %} User={{ zabbix_agent_runas_user }} {% endif %} -{% if zabbix_agent_os_family == "Windows" %} +{% if ansible_os_family == "Windows" %} Include={{ zabbix_agent_win_include }} {% else %} Include={{ zabbix_agent_include }}/{{ zabbix_agent_include_pattern }} {% endif %} +{% if zabbix_agent_additional_include is defined and zabbix_agent_additional_include is iterable and zabbix_agent_additional_include is not string %} +{% for include in zabbix_agent_additional_include %} +Include={{ include }} +{% endfor %} +{% endif %} UnsafeUserParameters={{ zabbix_agent_unsafeuserparameters }} -{% if zabbix_version is version_compare('2.2', '>=') %} -{% if zabbix_agent_os_family != "Windows" %} +{% if zabbix_agent_version is version_compare('2.2', '>=') %} +{% if ansible_os_family != "Windows" %} LoadModulePath={{ zabbix_agent_loadmodulepath }} {% endif %} {% endif %} @@ -105,7 +110,7 @@ LoadModule={{ module }} {% endfor %} {% endif %} {% endif %} -{% if zabbix_version is version_compare('3.0', '>=') %} +{% if zabbix_agent_version is version_compare('3.0', '>=') %} {% if zabbix_agent_tlsconnect is defined and zabbix_agent_tlsconnect %} TLSConnect={{ zabbix_agent_tlsconnect }} {% endif %} @@ -137,7 +142,7 @@ TLSPSKIdentity={{ zabbix_agent_tlspskidentity }} TLSPSKFile={{ zabbix_agent_tlspskfile }} {% endif %} {% endif %} -{% if zabbix_version is version('6.0', '>=') %} +{% if zabbix_agent_version is version('6.0', '>=') %} {% if zabbix_agent_listenbacklog is defined and zabbix_agent_listenbacklog %} ListenBacklog={{ zabbix_agent_listenbacklog }} {% endif %} diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Darwin.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Darwin.yml deleted file mode 100644 index 164b02460..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Darwin.yml +++ /dev/null @@ -1,6 +0,0 @@ ---- -# vars file for zabbix_agent (Debian) - -zabbix_agent: zabbix-agent -zabbix_agent_service: com.zabbix.zabbix_agentd -zabbix_agent_conf: zabbix_agentd.conf diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Debian.yml index 3100ca957..4a65dfbeb 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Debian.yml @@ -8,31 +8,41 @@ zabbix_agent2_conf: zabbix_agent2.conf zabbix_valid_agent_versions: # Debian + "12": + - 6.4 + - 6.2 + - 6.0 + "11": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 + "10": + - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 + "9": + - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 # Ubuntu "22": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 + "20": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 + "18": + - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 + +debian_keyring_path: /etc/apt/keyrings/ +zabbix_gpg_key: "{{ debian_keyring_path }}/zabbix-official-repo.asc" +_zabbix_repo_deb_url: "http://repo.zabbix.com/zabbix/{{ zabbix_agent_version }}" diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/RedHat.yml index b9f2378dd..50f0b01ec 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/RedHat.yml @@ -9,16 +9,13 @@ zabbix_agent2_conf: zabbix_agent2.conf zabbix_valid_agent_versions: "9": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "8": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "7": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Sangoma.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Sangoma.yml deleted file mode 100644 index 5bcc846ab..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Sangoma.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -# vars file for zabbix_agent (Sangola) - -zabbix_agent: zabbix-agent -zabbix_agent_service: zabbix-agent -zabbix_agent_conf: zabbix_agentd.conf -zabbix_agent2_conf: zabbix_agent2.conf diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Suse.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Suse.yml deleted file mode 100644 index abecd9c23..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Suse.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -# vars file for zabbix_agent (Suse) - -zabbix_agent: zabbix-agentd -zabbix_agent_service: zabbix_agentd -zabbix_agent_conf: zabbix_agentd.conf -zabbix_agent2_conf: zabbix-agent2.conf diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Windows.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Windows.yml index 8add26238..4dd64ba02 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Windows.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/Windows.yml @@ -1,2 +1,7 @@ --- # vars file for zabbix_agent (Windows) +zabbix_valid_agent_versions: + "10": + - 6.4 + - 6.2 + - 6.0 diff --git a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/zabbix.yml b/ansible_collections/community/zabbix/roles/zabbix_agent/vars/zabbix.yml deleted file mode 100644 index c78d3a76e..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_agent/vars/zabbix.yml +++ /dev/null @@ -1,285 +0,0 @@ ---- -sign_keys: - "64": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "62": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "60": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - jammy: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - "54": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - jammy: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "52": - # bullseye: not available upstream - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - jammy: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "50": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - jammy: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "44": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "42": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "40": - bullseye: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "34": - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "32": - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - sonya: - sign_key: 79EA5ED4 - serena: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "30": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "24": - jessie: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - "22": - squeeze: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - lucid: - sign_key: 79EA5ED4 - -suse: - "openSUSE Leap": - "42": - name: server:monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_Leap_{{ ansible_distribution_version }}/ - python_libxml2_package: python-libxml2 - "openSUSE": - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_{{ ansible_distribution_version }} - python_libxml2_package: python-libxml2 - "SLES": - "11": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_11_SP3/ - python_libxml2_package: python-libxml2 - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_12_SP5/ - python_libxml2_package: python-libxml2 - "15": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_15_SP3/ - python_libxml2_package: python3-libxml2-python - "SLES_SAP": # SAP specific version of SLES - "11": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_11_SP3/ - python_libxml2_package: python-libxml2 - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_12_SP5/ - python_libxml2_package: python-libxml2 - "15": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_15_SP3/ - python_libxml2_package: python3-libxml2-python diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/README.md b/ansible_collections/community/zabbix/roles/zabbix_javagateway/README.md index 70427d97c..1761c7f8b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/README.md +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/README.md @@ -29,29 +29,22 @@ This role will work on the following operating systems: * Ubuntu So, you'll need one of those operating systems.. :-) -Please send Pull Requests or suggestions when you want to use this role for other Operating systems. ## Zabbix Versions See the following list of supported Operating systems with the Zabbix releases. -| Zabbix | 6.4 | 6.2 | 6.0 (LTS) | 5.2 | 5.0 | 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----------|-----|-----|-----|-----------|-----------| -| Red Hat Fam 8 | V | V | V | V | V | V | | | -| Red Hat Fam 7 | | | | V | V | V | V | V | -| Red Hat Fam 6 | | | | V | V | | | V | -| Red Hat Fam 5 | | | | V | V | | | V | -| Fedora | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | | | | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | V | V | V | V | V | -| Debian 10 buster | V | V | V | V | V | V | | | -| Debian 9 stretch | | | | V | V | V | V | | -| Debian 8 jessie | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | V | V | -| macOS 10.15 | | | | | | V | V | | -| macOS 10.14 | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Red Hat Fam 7 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | V | V | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | V | V | V | # Role Variables @@ -61,17 +54,14 @@ The following is an overview of all available configuration default for this rol ### Overall Zabbix -* `zabbix_javagateway_version`: This is the version of zabbix. Default: 5.2. Can be overridden to 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo +The `zabbix_javagateway_version` is optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_javagateway_version: 6.0`. * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. +* `zabbix_javagateway_disable_repo`: A list of repos to disable during install. Default `epel`. * `zabbix_javagateway_package_state`: Default: `present`. Can be overridden to `latest` to update packages when needed. * `zabbix_javagateway_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_agent_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### Java Gatewaty @@ -106,6 +96,17 @@ or when using the zabbix-proxy: zabbix_proxy_javagateway: 192.168.1.2 ``` +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Example Playbook Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/defaults/main.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/defaults/main.yml index a34046616..4356f61a4 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/defaults/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/defaults/main.yml @@ -1,17 +1,14 @@ --- # defaults file for zabbix_javagateway -zabbix_javagateway_version: 6.4 -zabbix_version: "{{ zabbix_javagateway_version }}" +#zabbix_javagateway_version:6.4 zabbix_javagateway_package_state: present -zabbix_selinux: false -zabbix_repo: zabbix zabbix_repo_yum_schema: https zabbix_java_gateway_conf_mode: "0644" zabbix_repo_yum_gpgcheck: 0 -zabbix_repo_yum_disabled: "*" -zabbix_repo_yum_enabled: [] +zabbix_javagateway_disable_repo: + - epel zabbix_repo_yum: - name: zabbix description: Zabbix Official Repository - $basearch @@ -28,6 +25,8 @@ zabbix_repo_yum: gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX state: present +zabbix_repo_deb_component: main + zabbix_javagateway_pidfile: /run/zabbix/zabbix_java_gateway.pid zabbix_javagateway_listenip: 0.0.0.0 zabbix_javagateway_listenport: 10052 diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/handlers/main.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/handlers/main.yml index c7034aa7d..9b6ed50c1 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/handlers/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/handlers/main.yml @@ -2,14 +2,14 @@ # handlers file for zabbix-javagateway - name: zabbix-java-gateway restarted - service: + ansible.builtin.service: name: zabbix-java-gateway state: restarted enabled: true become: true - name: "clean repo files from proxy creds" - shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true + ansible.builtin.shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true become: true when: - ansible_os_family == 'RedHat' diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/Debian.yml index d025e6ca8..4c4cff06d 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/Debian.yml @@ -1,80 +1,80 @@ --- - -- name: "Include Zabbix gpg ids" - include_vars: zabbix.yml - -- name: "Set some variables" - set_fact: +- name: "Debian | Set some variables" + ansible.builtin.set_fact: zabbix_short_version: "{{ zabbix_javagateway_version | regex_replace('\\.', '') }}" + tags: + - always -- name: "Debian | Install gpg key" - apt_key: - id: "{{ sign_keys[zabbix_short_version][ansible_distribution_release]['sign_key'] }}" - url: http://repo.zabbix.com/zabbix-official-repo.key - become: true - -- name: "Debian | Installing repository Debian" - apt_repository: - repo: "deb http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}/debian/ {{ ansible_distribution_release }} main" +- name: "Debian | Installing lsb-release" + ansible.builtin.apt: + pkg: lsb-release + update_cache: true + cache_valid_time: 3600 + force: true state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" become: true - when: - - ansible_distribution == "Debian" - - zabbix_repo == "zabbix" + tags: + - install -- name: "Debian | Installing repository Debian" - apt_repository: - repo: "deb-src http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}/debian/ {{ ansible_distribution_release }} main" - state: present - become: true - when: - - ansible_distribution == "Debian" - - ansible_machine == "aarch64" - - zabbix_repo == "zabbix" +- name: "Debian | Update ansible_lsb fact" + ansible.builtin.setup: + gather_subset: + - lsb -- name: "Debian | Installing repository Ubuntu" - apt_repository: - repo: "deb http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}/ubuntu-arm64/ {{ ansible_distribution_release }} main" - state: present - become: true +- name: "Debian | Repo URL" + ansible.builtin.set_fact: + zabbix_repo_deb_url: "{{ _zabbix_repo_deb_url }}/{{ ansible_lsb.id.lower() }}{{ '-arm64' if ansible_machine == 'aarch64' and ansible_lsb.id == 'debian' else ''}}" when: - - ansible_distribution == "Ubuntu" - - ansible_machine == "aarch64" - - zabbix_repo == "zabbix" - + - zabbix_repo_deb_url is undefined + tags: + - always -- name: "Debian | Installing repository Ubuntu" - apt_repository: - repo: "deb http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}/ubuntu/ {{ ansible_distribution_release }} main" - state: present +# In releases older than Debian 12 and Ubuntu 22.04, /etc/apt/keyrings does not exist by default. +# It SHOULD be created with permissions 0755 if it is needed and does not already exist. +# See: https://wiki.debian.org/DebianRepository/UseThirdParty +- name: "Debian | Create /etc/apt/keyrings/ on older versions" + ansible.builtin.file: + path: /etc/apt/keyrings/ + state: directory + mode: "0755" become: true when: - - ansible_distribution == "Ubuntu" - - ansible_machine != "aarch64" - - zabbix_repo == "zabbix" + - (ansible_distribution == "Ubuntu" and ansible_distribution_major_version < "22") or + (ansible_distribution == "Debian" and ansible_distribution_major_version < "12") -- name: "Debian | Installing repository Ubuntu" - apt_repository: - repo: "deb-src http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}/ubuntu-arm64/ {{ ansible_distribution_release }} main" - state: present +- name: "Debian | Download gpg key" + ansible.builtin.get_url: + url: http://repo.zabbix.com/zabbix-official-repo.key + dest: "{{ zabbix_gpg_key }}" + mode: "0644" + force: true become: true - when: - - ansible_distribution == "Ubuntu" - - ansible_machine == "aarch64" - - zabbix_repo == "zabbix" - + tags: + - install -- name: "Debian | Installing repository Ubuntu" - apt_repository: - repo: "deb-src http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}/ubuntu/ {{ ansible_distribution_release }} main" - state: present +- name: "Debian | Installing repository {{ ansible_distribution }}" + ansible.builtin.copy: + dest: /etc/apt/sources.list.d/zabbix.sources + owner: root + group: root + mode: 0644 + content: | + Types: deb deb-src + Enabled: yes + URIs: {{ zabbix_repo_deb_url }} + Suites: {{ ansible_distribution_release }} + Components: {{ zabbix_repo_deb_component }} + Architectures: {{ 'amd64' if ansible_machine != 'aarch64' else 'arm64'}} + Signed-By: {{ zabbix_gpg_key }} become: true - when: - - ansible_distribution == "Ubuntu" - - zabbix_repo == "zabbix" + tags: + - install - name: "Debian | Installing zabbix-java-gateway" - apt: + ansible.builtin.apt: pkg: zabbix-java-gateway state: "{{ zabbix_javagateway_package_state }}" update_cache: true @@ -86,12 +86,17 @@ register: zabbix_java_gateway_install until: zabbix_java_gateway_install is succeeded become: true + tags: + - install -- name: "Make sure Zabbix Java Gateway is not yet running" - systemd: +- name: "Debian | Make sure Zabbix Java Gateway is not yet running" + ansible.builtin.systemd: name: zabbix-java-gateway state: stopped enabled: true daemon_reload: true + become: true when: - zabbix_java_gateway_install.changed + tags: + - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/RedHat.yml index 877628381..96d9d3928 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/RedHat.yml @@ -2,33 +2,34 @@ # Tasks specific for RedHat systems - name: "RedHat | Install basic repo file" - yum_repository: + ansible.builtin.yum_repository: name: "{{ item.name }}" description: "{{ item.description }}" baseurl: "{{ item.baseurl }}" gpgcheck: "{{ item.gpgcheck }}" gpgkey: "{{ item.gpgkey }}" mode: "{{ item.mode | default('0644') }}" - priority: "{{ item.priority | default('98') }}" + priority: "{{ item.priority | default('99') }}" state: "{{ item.state | default('present') }}" proxy: "{{ zabbix_http_proxy | default(omit) }}" with_items: "{{ zabbix_repo_yum }}" register: yum_repo_installed become: true - when: - zabbix_repo == "zabbix" notify: - "clean repo files from proxy creds" + tags: + - install - name: "RedHat | Installing zabbix-java-gateway" - package: + ansible.builtin.package: pkg: zabbix-java-gateway state: "{{ zabbix_javagateway_package_state }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_agent_disable_repo | default(omit) }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" register: zabbix_java_gateway_install until: zabbix_java_gateway_install is succeeded become: true + tags: + - install diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/main.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/main.yml index b95322426..6b56d43d3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/tasks/main.yml @@ -1,46 +1,53 @@ --- -# tasks file for zabbix_proxy +# tasks file for zabbix_javagateway -- name: "Install the correct repository" - include_tasks: "RedHat.yml" - when: - - ansible_os_family == "RedHat" +- name: Include OS-specific variables + ansible.builtin.include_vars: "{{ ansible_os_family }}.yml" + tags: + - always -- name: "Install the correct repository" - include_tasks: "Debian.yml" - when: - - ansible_os_family == "Debian" +- name: Determine Latest Supported Zabbix Version + ansible.builtin.set_fact: + zabbix_javagateway_version: "{{ zabbix_valid_javagateway_versions[ansible_distribution_major_version][0] | default(6.4) }}" + when: zabbix_javagateway_version is not defined + tags: + - always -- name: "Place systemd unit file" - copy: - src: systemd.service - dest: /etc/systemd/system/zabbix-java-gateway.service - mode: '0644' - register: systemd_state - when: - - zabbix_version is version('5.4', '<') +- name: Set More Variables + ansible.builtin.set_fact: + zabbix_valid_version: "{{ zabbix_javagateway_version|float in zabbix_valid_javagateway_versions[ansible_distribution_major_version] }}" + tags: + - always -- name: "Reload systemd" - shell: systemctl daemon-reload - when: - - zabbix_version is version('5.4', '<') - - systemd_state.changed +- name: Stopping Install of Invalid Version + ansible.builtin.fail: + msg: Zabbix version {{ zabbix_javagateway_version }} is not supported on {{ ansible_distribution }} {{ ansible_distribution_major_version }} + when: not zabbix_valid_version tags: - - skip_ansible_lint + - always + +- name: "Install the correct repository" + ansible.builtin.include_tasks: "{{ ansible_os_family }}.yml" - name: "Configure zabbix-proxy" - template: + ansible.builtin.template: src: zabbix_java_gateway.conf.j2 dest: /etc/zabbix/zabbix_java_gateway.conf owner: zabbix group: zabbix mode: "{{ zabbix_java_gateway_conf_mode }}" + become: true notify: - zabbix-java-gateway restarted + tags: + - config - name: "Make sure Zabbix Java Gateway is running" - systemd: + ansible.builtin.systemd: name: zabbix-java-gateway state: started enabled: true daemon_reload: true + become: true + tags: + - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/templates/zabbix_java_gateway.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_javagateway/templates/zabbix_java_gateway.conf.j2 index 9b197600d..7c697cd3b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/templates/zabbix_java_gateway.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/templates/zabbix_java_gateway.conf.j2 @@ -4,7 +4,7 @@ # This configuration file is "minimalized", which means all the original comments # are removed. The full documentation for your Zabbix Java Gateway can be found here: -# https://www.zabbix.com/documentation/{{ zabbix_version }}/en/manual/concepts/java +# https://www.zabbix.com/documentation/{{ zabbix_javagateway_version }}/en/manual/concepts/java LISTEN_IP={{ zabbix_javagateway_listenip }} LISTEN_PORT={{ zabbix_javagateway_listenport }} diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/Debian.yml index 1eecc3170..2253f5b7b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/Debian.yml @@ -1,6 +1,30 @@ ---- -apache_user: www-data -apache_group: www-data -apache_log: apache2 +zabbix_valid_javagateway_versions: + # Debian + "12": + - 6.4 + - 6.0 + "11": + - 6.4 + - 6.2 + - 6.0 + "10": + - 6.4 + - 6.2 + - 6.0 + # Ubuntu + "22": + - 6.4 + - 6.2 + - 6.0 + "20": + - 6.4 + - 6.2 + - 6.0 + "18": + - 6.4 + - 6.2 + - 6.0 -mysql_create_dir: '' +debian_keyring_path: /etc/apt/keyrings/ +zabbix_gpg_key: "{{ debian_keyring_path }}/zabbix-official-repo.asc" +_zabbix_repo_deb_url: "http://repo.zabbix.com/zabbix/{{ zabbix_javagateway_version }}" diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/RedHat.yml index 8c1997706..62af028ff 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/RedHat.yml @@ -1,6 +1,14 @@ --- -apache_user: apache -apache_group: apache -apache_log: httpd - -mysql_create_dir: create/ +zabbix_valid_javagateway_versions: + "9": + - 6.4 + - 6.2 + - 6.0 + "8": + - 6.4 + - 6.2 + - 6.0 + "7": + - 6.4 + - 6.2 + - 6.0 diff --git a/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/zabbix.yml b/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/zabbix.yml deleted file mode 100644 index bd960deba..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_javagateway/vars/zabbix.yml +++ /dev/null @@ -1,258 +0,0 @@ ---- -sign_keys: - "64": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - jammy: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - "62": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - jammy: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - "60": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - jammy: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - "54": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "52": - # bullseye: not available upstream - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "50": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "44": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "42": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "40": - bullseye: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "34": - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "32": - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - sonya: - sign_key: 79EA5ED4 - serena: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "30": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "24": - jessie: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - "22": - squeeze: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - lucid: - sign_key: 79EA5ED4 - -suse: - "openSUSE Leap": - "42": - name: server:monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_Leap_{{ ansible_distribution_version }}/ - "openSUSE": - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_{{ ansible_distribution_version }} - "SLES": - "11": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_11_SP3/ - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_12_SP3/ diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/README.md b/ansible_collections/community/zabbix/roles/zabbix_proxy/README.md index 6682f6c18..baec42155 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/README.md +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/README.md @@ -77,24 +77,17 @@ ansible-galaxy collection install community.postgresql See the following list of supported Operating systems with the Zabbix releases. -| Zabbix | 6.4 | 6.2 | 6.0 | 5.4 | 5.2 | 5.0 (LTS)| 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----|-----|-----|-----------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | V | V | V | V | V | V | V | V | V | -| Red Hat Fam 6 | | | | | V | V | | | V | -| Red Hat Fam 5 | | | | | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | | | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | | V | V | V | V | V | -| Debian 10 buster | V | | V | V | V | V | V | | | -| Debian 9 stretch | V | | V | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Red Hat Fam 7 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | V | V | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | V | V | V | # Role Variables @@ -102,104 +95,49 @@ See the following list of supported Operating systems with the Zabbix releases. The following is an overview of all available configuration default for this role. -### Overall Zabbix - -* `zabbix_proxy_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2, 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. -* `zabbix_proxy_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo -* `zabbix_repo_yum`: A list with Yum repository configuration. -* `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. - -### SElinux - -* `zabbix_selinux`: Default: `False`. Enables an SELinux policy so that the Proxy will run. - ### Zabbix Proxy +* `zabbix_proxy_version`: Optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_proxy_version: 6.0`. +* `zabbix_proxy_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) * `zabbix_proxy_ip`: The IP address of the host. When not provided, it will be determined via the `ansible_default_ipv4` fact. * `zabbix_proxy_server`: The ip or dns name for the zabbix-server machine. -* `zabbix_proxy_serverport`: The port on which the zabbix-server is running. Default: 10051 -* `*zabbix_proxy_package_state`: Default: `present`. Can be overridden to `latest` to update packages * `zabbix_proxy_install_database_client`: Default: `True`. False does not install database client. -* `zabbix_proxy_become_on_localhost`: Default: `True`. Set to `False` if you don't need to elevate privileges on localhost to install packages locally with pip. * `zabbix_proxy_manage_service`: Default: `True`. When you run multiple Zabbix proxies in a High Available cluster setup (e.g. pacemaker), you don't want Ansible to manage the zabbix-proxy service, because Pacemaker is in control of zabbix-proxy service. -* `zabbix_install_pip_packages`: Default: `True`. Set to `False` if you don't want to install the required pip packages. Useful when you control your environment completely. -* `zabbix_proxy_startpreprocessors`: Number of pre-forked instances of preprocessing workers. The preprocessing manager process is automatically started when a preprocessor worker is started.This parameter is supported since Zabbix 4.2.0. -* `zabbix_proxy_username`: Default: `zabbix`. The name of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_proxy_logtype`: Specifies where log messages are written to: system, file, console. -* `zabbix_proxy_logfile`: Name of log file. -* `zabbix_proxy_userid`: The UID of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_proxy_groupname`: Default: `zabbix`. The name of the group of the user on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_proxy_groupid`: The GID of the group on the host. Will only be used when `zabbix_repo: epel` is used. * `zabbix_proxy_include_mode`: Default: `0755`. The "mode" for the directory configured with `zabbix_proxy_include`. * `zabbix_proxy_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. -* `zabbix_proxy_statsallowedip`: Default: `127.0.0.1`. Allowed IP foe remote gathering of the ZabbixPorixy internal metrics. -* `zabbix_proxy_vaulttoken`: Vault authentication token that should have been generated exclusively for Zabbix server with read only permission -* `zabbix_proxy_vaulturl`: Vault server HTTP[S] URL. System-wide CA certificates directory will be used if SSLCALocation is not specified. -* `zabbix_proxy_vaultdbpath`: Vault path from where credentials for database will be retrieved by keys 'password' and 'username'. -* `zabbix_proxy_listenbacklog`: The maximum number of pending connections in the queue. ### Database specific * `zabbix_proxy_dbhost_run_install`: Default: `True`. When set to `True`, sql files will be executed on the host running the database. * `zabbix_proxy_database`: Default: `mysql`. The type of database used. Can be: `mysql`, `pgsql` or `sqlite3` -* `zabbix_proxy_database_long`: Default: `mysql`. The type of database used, but long name. Can be: `mysql`, `postgresql` or `sqlite3` -* `zabbix_proxy_dbhost`: The hostname on which the database is running. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbhost`: Default: localhost. The hostname on which the database is running. Will be ignored when `sqlite3` is used as database. * `zabbix_proxy_real_dbhost`: The hostname of the dbhost that is running behind a loadbalancer/VIP (loadbalancers doesn't accept ssh connections) Will be ignored when `sqlite3` is used as database. -* `zabbix_proxy_dbname`: The database name which is used by the Zabbix Proxy. -* `zabbix_proxy_dbuser`: The database username which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. -* `zabbix_proxy_dbpassword`: The database user password which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbname`: Default: zabbix_proxy. The database name which is used by the Zabbix Proxy. +* `zabbix_proxy_dbuser`: Default: zabbix_proxy. The database username which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbpassword`: Default: zabbix_proxy. The database user password which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. +* `zabbix_proxy_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. * `zabbix_proxy_dbport`: The database port which is used by the Zabbix Proxy. Will be ignored when `sqlite3` is used as database. -* `zabbix_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. +* `zabbix_proxy_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. * `zabbix_proxy_install_database_client`: Default: `True`. False does not install database client. Default true -* `zabbix_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. +* `zabbix_proxy_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. * `zabbix_proxy_dbencoding`: Default: `utf8`. The encoding for the MySQL database. * `zabbix_proxy_dbcollation`: Default: `utf8_bin`. The collation for the MySQL database.zabbix_proxy_ -* `zabbix_server_allowunsupporteddbversions`: Allow proxy to work with unsupported database versions. -* `zabbix_proxy_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. -### TLS Specific configuration - -These variables are specific for Zabbix 3.0 and higher: - -* `zabbix_proxy_tlsconnect`: How the agent should connect to server or proxy. Used for active checks. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_proxy_tlsaccept`: What incoming connections to accept. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_proxy_tlscafile`: Full pathname of a file containing the top-level CA(s) certificates for peer certificate verification. -* `zabbix_proxy_tlscrlfile`: Full pathname of a file containing revoked certificates. -* `zabbix_proxy_tlsservercertissuer`: Allowed server certificate issuer. -* `zabbix_proxy_tlsservercertsubject`: Allowed server certificate subject. -* `zabbix_proxy_tlscertfile`: Full pathname of a file containing the agent certificate or certificate chain. -* `zabbix_proxy_tlskeyfile`: Full pathname of a file containing the agent private key. -* `zabbix_proxy_dbtlsconnect`: Setting this option enforces to use TLS connection to database: - -`required` - connect using TLS -`verify_ca` - connect using TLS and verify certificate -`verify_full` - connect using TLS, verify certificate and verify that database identity specified by DBHost matches its certificate - -On `MySQL` starting from 5.7.11 and `PostgreSQL` the following values are supported: `required`, `verify`, `verify_full`. On MariaDB starting from version 10.2.6 `required` and `verify_full` values are supported. -By default not set to any option and the behaviour depends on database configuration. -This parameter is supported since Zabbix 5.0.0. - -* `zabbix_proxy_dbtlscafile`: Full pathname of a file containing the top-level CA(s) certificates for database certificate verification. This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlscertfile`: Full pathname of file containing Zabbix Proxy certificate for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlskeyfile`: Full pathname of file containing the private key for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlscipher`: The list of encryption ciphers that Zabbix Proxy permits for TLS protocols up through TLSv1.2. Supported only for MySQL.This parameter is supported since Zabbix 5.0.0. -* `zabbix_proxy_dbtlscipher13`: The list of encryption ciphersuites that Zabbix Proxy permits for TLSv1.3 protocol. Supported only for MySQL, starting from version 8.0.16. This parameter is supported since Zabbix 5.0.0. - -## proxy + +### Yum/APT +* `zabbix_repo_yum`: A list with Yum repository configuration. +* `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) +* `zabbix_repo_yum_gpgcheck`: Default: `0`. Should yum perform a GPG check on the repository +* `zabbix_proxy_disable_repo`: A list of repos to disable during install. Default `epel`. +* `zabbix_proxy_apt_priority`: APT priority for the zabbix repository +* `*zabbix_proxy_package_state`: Default: `present`. Can be overridden to `latest` to update packages +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_proxy_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. +### SElinux + +* `zabbix_proxy_selinux`: Default: `False`. Enables an SELinux policy so that the Proxy will run. + +## Proxy When the target host does not have access to the internet, but you do have a proxy available then the following properties needs to be set to download the packages via the proxy: @@ -210,9 +148,9 @@ When the target host does not have access to the internet, but you do have a pro With Zabbix Proxy you can make use of 2 different databases: -* `mysql` -* `postgresql` -* `SQLite3` +* MySQL +* PostgreSQL +* SQLite3 In the following paragraphs we dive into both setups. @@ -232,12 +170,12 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: mysql -zabbix_proxy_database_long: mysql zabbix_proxy_dbport: 3306 zabbix_proxy_dbpassword: <SOME_SECRET_STRING> ``` Please generate a value for the `zabbix_proxy_dbpassword` property (Maybe use `ansible-vault` for this). The zabbix-proxy role will create an database and username (With the provided value for the password) in `MySQL`. + 3. Execute the role by running the Ansible playbook that calls this role. At the end of this run, the Zabbix Proxy with `MySQL` will be running. #### Separate Setup @@ -249,7 +187,6 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: mysql -zabbix_proxy_database_long: mysql zabbix_proxy_dbport: 3306 zabbix_proxy_dbhost: mysql-host zabbix_proxy_dbhost_run_install: false @@ -283,7 +220,6 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: pgsql -zabbix_proxy_database_long: postgresql zabbix_proxy_dbport: 5432 zabbix_proxy_dbpassword: <SOME_SECRET_STRING> ``` @@ -300,7 +236,6 @@ We need to have the following dependencies met: ```yaml zabbix_proxy_database: pgsql -zabbix_proxy_database_long: postgresql zabbix_proxy_dbport: 5432 zabbix_proxy_dbhost: pgsql-host zabbix_proxy_dbhost_run_install: false @@ -326,7 +261,6 @@ The following properties needs to be set when using `SQLite3` as the database: ```yaml zabbix_proxy_database: sqlite3 -zabbix_proxy_database_long: sqlite3 zabbix_proxy_dbname: /path/to/sqlite3.db ``` @@ -336,20 +270,140 @@ NOTE: When using `zabbix_proxy_dbname: zabbix_proxy` (Which is default with this These variables need to be overridden when you want to make use of the Zabbix API for automatically creating and or updating proxies, i.e. when `zabbix_api_create_proxy` is set to `True`. -* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth. -* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth. * `zabbix_api_server_host`: The IP or hostname/FQDN of Zabbix server. Example: zabbix.example.com -* `zabbix_api_server_port`: TCP port to use to connect to Zabbix server. Example: 8080 -* `zabbix_api_use_ssl`: yes (Default) if we need to connect to Zabbix server over HTTPS -* `zabbix_api_validate_certs` : yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used +* `zabbix_api_use_ssl`: Is SSL required to connect to the Zabbix API server? Default: `false` +* `zabbix_api_server_port`: 80 if `zabbix_api_use_ssl` is `false` and 443 if `true` (Default) TCP port to use to connect to Zabbix server. Example: 8080 * `zabbix_api_login_user`: Username of user which has API access. * `zabbix_api_login_pass`: Password for the user which has API access. +* `zabbix_api_http_user`: The http user to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_http_password`: The http password to access zabbix url with Basic Auth (if your Zabbix is behind a proxy with HTTP Basic Auth). +* `zabbix_api_validate_certs`: yes (Default) if we need to validate tls certificates of the API. Use `no` in case self-signed certificates are used. +* `zabbix_api_timeout`: timeout for API calls (default to 30 seconds) * `ansible_zabbix_url_path`: URL path if Zabbix WebUI running on non-default (zabbix) path, e.g. if http://<FQDN>/zabbixeu then set to `zabbixeu` * `zabbix_api_create_proxy`: When you want to enable the Zabbix API to create/delete the proxy. This has to be set to `True` if you want to make use of `zabbix_proxy_state`. Default: `False` * `zabbix_proxy_name`: name of the Zabbix proxy as it is seen by Zabbix server * `zabbix_proxy_state`: present (Default) if the proxy needs to be created or absent if you want to delete it. This only works when `zabbix_api_create_proxy` is set to `True`. * `zabbix_proxy_status`: active (Default) if the proxy needs to be active or passive. -* `zabbix_api_timeout`: timeout for API calls (default to 30 seconds) + +## Configuration Variables + +The following table lists all variables that are exposed to modify the configuration of the zabbix_proxy.conf file. Specific details of each variable can be found in the Zabbix documentation. + +**NOTE**: Only variables with a default value appear in the defaults file, all others must be added. + +| Zabbix Name | Variable Name | Default Value |Notes | +|-----------|------------------|--------|--------| +| AllowRoot | zabbix_proxy_allowroot |0| | +| AllowUnsupportedDBVersions | zabbix_proxy_allowunsupporteddbversions |0| | +| CacheSize | zabbix_proxy_cachesize | 8M| | +| ConfigFrequency | zabbix_proxy_configfrequency |3600| | +| DataSenderFrequency | zabbix_proxy_datasenderfrequency |1| | +| DBHost | zabbix_proxy_dbhost | localhost| | +| DBName | zabbix_proxy_dbname | zabbix_proxy| | +| DBPassword | zabbix_proxy_dbpassword | zabbix_proxy| | +| DBSchema | zabbix_proxy_dbschema || | +| DBSocket | zabbix_proxy_dbsocket || | +| DBTLSCAFile | zabbix_proxy_dbtlscafile || | +| DBTLSCertFile | zabbix_proxy_dbtlscertfile || | +| DBTLSCipher | zabbix_proxy_dbtlscipher || | +| DBTLSCipher13 | zabbix_proxy_dbtlscipher13 || | +| DBTLSConnect | zabbix_proxy_dbtlsconnect || | +| DBTLSKeyFile | zabbix_proxy_dbtlskeyfile || | +| DBUser | zabbix_proxy_dbuser | zabbix_proxy| | +| DebugLevel | zabbix_proxy_debuglevel |3| | +| EnableRemoteCommands | zabbix_proxy_enableremotecommands |0| | +| ExternalScripts | zabbix_proxy_externalscripts | /usr/lib/zabbix/externalscripts| | +| Fping6Location | zabbix_proxy_fping6location | OS Specific Value | | +| FpingLocation | zabbix_proxy_fpinglocation | OS Specific Value | | +| HeartbeatFrequency | zabbix_proxy_heartbeatfrequency |60| Version 6.2 or Lower| +| HistoryCacheSize | zabbix_proxy_historycachesize | 8M| | +| HistoryIndexCacheSize | zabbix_proxy_historyindexcachesize | 4M| | +| Hostname | zabbix_proxy_hostname | "{{ inventory_hostname }}"| | +| HostnameItem | zabbix_proxy_hostnameitem || | +| HousekeepingFrequency | zabbix_proxy_housekeepingfrequency |1| | +| Include | zabbix_proxy_include | /etc/zabbix/zabbix_proxy.conf.d| | +| JavaGateway | zabbix_proxy_javagateway || | +| JavaGatewayPort | zabbix_proxy_javagatewayport |10052| | +| ListenBacklog | zabbix_proxy_listenbacklog || | +| ListenIP | zabbix_proxy_listenip || | +| ListenPort | zabbix_proxy_listenport |10051| | +| LoadModule | zabbix_proxy_loadmodule || | +| LoadModulePath | zabbix_proxy_loadmodulepath | /usr/lib/zabbix/modules| | +| LogFile | zabbix_proxy_logfile | /var/log/zabbix/zabbix_proxy.log| | +| LogFileSize | zabbix_proxy_logfilesize |10| | +| LogRemoteCommands | zabbix_proxy_logremotecommands || | +| LogSlowQueries | zabbix_proxy_logslowqueries || | +| LogType | zabbix_proxy_logtype | file| | +| PidFile | zabbix_proxy_pidfile | /var/run/zabbix/zabbix_proxy.pid| | +| ProxyLocalBuffer | zabbix_proxy_proxylocalbuffer |0| | +| ProxyMode | zabbix_proxy_proxymode || | +| ProxyOfflineBuffer | zabbix_proxy_proxyofflinebuffer |1| | +| Server | zabbix_proxy_server | 192.168.1.1| | +| SNMPTrapperFile | zabbix_proxy_snmptrapperfile | /tmp/zabbix_traps.tmp| | +| SocketDir | zabbix_proxy_socketdir | /var/run/zabbix| | +| SourceIP | zabbix_proxy_sourceip || | +| SSHKeyLocation | zabbix_proxy_sshkeylocation || | +| SSLCALocation | zabbix_proxy_sslcalocation || | +| SSLCertLocation | zabbix_proxy_sslcertlocation || | +| SSLKeyLocation | zabbix_proxy_sslkeylocation || | +| StartDBSyncers | zabbix_proxy_startdbsyncers |4| | +| StartDiscoverers | zabbix_proxy_startdiscoverers |1| | +| StartHTTPPollers | zabbix_proxy_starthttppollers |1| | +| StartIPMIPollers | zabbix_proxy_startipmipollers |0| | +| StartJavaPollers | zabbix_proxy_startjavapollers || | +| StartODBCPollers | zabbix_proxy_startodbcpollers |1| | +| StartPingers | zabbix_proxy_startpingers |1| | +| StartPollers | zabbix_proxy_startpollers |5| | +| StartPollersUnreachable | zabbix_proxy_startpollersunreachable |1| | +| StartPreprocessors | zabbix_proxy_startpreprocessors |3| | +| StartSNMPTrapper | zabbix_proxy_startsnmptrapper || | +| StartTrappers | zabbix_proxy_starttrappers |5| | +| StartVMwareCollectors | zabbix_proxy_startvmwarecollectors || | +| StatsAllowedIP | zabbix_proxy_statsallowedip | "127.0.0.1"| | +| Timeout | zabbix_proxy_timeout |3| | +| TLSAccept | zabbix_proxy_tlsaccept || | +| TLSCAFile | zabbix_proxy_tlscafile || | +| TLSCertFile | zabbix_proxy_tlscertfile || | +| TLSCipherAll | zabbix_proxy_tlscipherall || | +| TLSCipherAll13 | zabbix_proxy_tlscipherall13 || | +| TLSCipherCert | zabbix_proxy_tlsciphercert || | +| TLSCipherCert13 | zabbix_proxy_tlsciphercert13 || | +| TLSCipherPSK | zabbix_proxy_tlscipherpsk || | +| TLSCipherPSK13 | zabbix_proxy_tlscipherpsk13 || | +| TLSConnect | zabbix_proxy_tlsconnect || | +| TLSCRLFile | zabbix_proxy_tlscrlfile || | +| TLSKeyFile | zabbix_proxy_tlskeyfile || | +| TLSPSKFile | zabbix_proxy_tlspskfile || | +| TLSPSKIdentity | zabbix_proxy_tlspskidentity || | +| TLSServerCertIssuer | zabbix_proxy_tlsservercertissuer || | +| TLSServerCertSubject | zabbix_proxy_tlsservercertsubject || | +| TmpDir | zabbix_proxy_tmpdir | /tmp| | +| TrapperTimeout | zabbix_proxy_trappertimeout |300| | +| UnavailableDelay | zabbix_proxy_unavailabledelay || | +| UnreachableDelay | zabbix_proxy_unreachabledelay || | +| UnreachablePeriod | zabbix_proxy_unreachableperiod |45| | +| User | zabbix_proxy_user || | +| Vault | zabbix_proxy_vault || Version 6.2 or Greater | +| VaultDBPath | zabbix_proxy_vaultdbpath || | +| VaultTLSCertFile | zabbix_proxy_vaulttlscertfile || Version 6.2 or Greater | +| VaultTLSKeyFile | zabbix_proxy_vaulttlskeyfile || Version 6.2 or Greater | +| VaultToken | zabbix_proxy_vaulttoken || | +| VaultURL | zabbix_proxy_vaulturl |https://127.0.0.1:8200| | +| VMwareCacheSize | zabbix_proxy_vmwarecachesize | 8M| | +| VMwareFrequency | zabbix_proxy_vmwarefrequency |60| | +| VMwarePerfFrequency | zabbix_proxy_vmwareperffrequency | | | +| VMwareTimeout | zabbix_proxy_vmwaretimeout | | | + +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. # Example Playbook @@ -361,7 +415,6 @@ Including an example of how to use your role (for instance, with variables passe - role: community.zabbix.zabbix_proxy zabbix_proxy_server: 192.168.1.1 zabbix_proxy_database: mysql - zabbix_proxy_database_long: mysql ``` # Molecule @@ -385,3 +438,4 @@ See LICENCE to see the full text. Please send suggestion or pull requests to make this role better. Also let us know if you encounter any issues installing or using this role. Github: https://github.com/ansible-collections/community.zabbix + diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/defaults/main.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/defaults/main.yml index 82a70cb09..f46c9c64e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/defaults/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/defaults/main.yml @@ -1,32 +1,53 @@ --- # defaults file for zabbix_proxy +# zabbix_proxy_version: 6.4 +zabbix_os_user: zabbix +zabbix_proxy_selinux: false +zabbix_proxy_interface: + useip: "{{ zabbix_useuip }}" + ip: "{{ zabbix_proxy_ip }}" + dns: "{{ ansible_fqdn }}" + port: "{{ zabbix_proxy_listenport }}" +zabbix_useuip: 1 -# zabbix_proxy_version: 6.0 -zabbix_proxy_version_minor: "*" -zabbix_version: "{{ zabbix_proxy_version }}" -zabbix_selinux: false - -# These variables are optional. They specify the version of Zabbix proxy package. +# Database +zabbix_proxy_database: mysql +zabbix_proxy_database_creation: true +zabbix_proxy_database_sqlload: true +zabbix_proxy_dbhost_run_install: true +zabbix_proxy_dbcollation: utf8_bin +zabbix_proxy_dbencoding: utf8 +zabbix_proxy_dbhost: localhost +zabbix_proxy_dbname: zabbix_proxy +zabbix_proxy_dbpassword: zabbix_proxy +zabbix_proxy_dbpassword_hash_method: md5 +zabbix_proxy_dbuser: zabbix_proxy +zabbix_proxy_install_database_client: true -# zabbix_proxy_rhel_version: 4.4.4 -# zabbix_proxy_debian_version: 1:4.4.4-1+stretch -# zabbix_proxy_ubuntu_version: 1:4.4.4-1+xenial +# Misc. +zabbix_proxy_cat_cmd: cat +zabbix_proxy_conf_mode: "0644" +zabbix_proxy_config: /etc/zabbix/zabbix_proxy.conf +zabbix_proxy_include_mode: "0755" +zabbix_proxy_manage_service: true +zabbix_proxy_privileged_host: localhost +zabbix_proxy_server: 192.168.1.1 +zabbix_proxy_tls_config: + no_encryption: "no_encryption" + psk: "PSK" + cert: "certificate" +zabbix_proxy_version_minor: "*" -zabbix_repo: zabbix -zabbix_proxy_apt_priority: -zabbix_proxy_package_state: present -zabbix_proxy_install_recommends: true -zabbix_proxy_install_database_client: true -zabbix_install_pip_packages: true +# Yum/APT Variables zabbix_repo_yum_schema: https -zabbix_proxy_conf_mode: "0644" zabbix_repo_yum_gpgcheck: 0 -zabbix_repo_yum_disabled: "*" -zabbix_repo_yum_enabled: [] +zabbix_repo_deb_component: main +zabbix_proxy_disable_repo: + - epel zabbix_repo_yum: - name: zabbix description: Zabbix Official Repository - $basearch - baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/" + baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_proxy_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/" gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" mode: "0644" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX @@ -38,159 +59,71 @@ zabbix_repo_yum: gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX state: present +zabbix_proxy_apt_priority: +zabbix_proxy_package_state: present -# User (EPEL specific) -zabbix_proxy_username: zabbix -zabbix_proxy_groupname: zabbix - -zabbix_server_host: 192.168.1.1 # Will be deprecated in 2.0.0 -zabbix_proxy_server: "{{ zabbix_server_host }}" -zabbix_server_port: 10051 # Will be deprecated in 2.0.0 -zabbix_proxy_serverport: "{{ zabbix_server_port }}" -zabbix_database_creation: true -zabbix_database_sqlload: true -zabbix_proxy_dbtlsconnect: -zabbix_proxy_dbtlscafile: -zabbix_proxy_dbtlscertfile: -zabbix_proxy_dbtlskeyfile: -zabbix_proxy_dbtlscipher: -zabbix_proxy_dbtlscipher13: +# Proxy Configuration Variables (Only ones with role provided defaults) +zabbix_proxy_allowroot: 0 zabbix_proxy_allowunsupporteddbversions: 0 - -# Some role specific vars -zabbix_proxy_database: mysql -zabbix_proxy_database_long: mysql -# zabbix_proxy_database: pgsql -# zabbix_proxy_database_long: postgresql -# zabbix_proxy_database: sqlite3 -# zabbix_proxy_database_long: sqlite3 - -# zabbix-proxy specific vars -zabbix_proxy_mode: 0 +zabbix_proxy_cachesize: 8M +zabbix_proxy_configfrequency: 3600 +zabbix_proxy_datasenderfrequency: 1 +zabbix_proxy_dbport: 5432 +zabbix_proxy_debuglevel: 3 +zabbix_proxy_enableremotecommands: 0 +zabbix_proxy_externalscripts: /usr/lib/zabbix/externalscripts +zabbix_proxy_heartbeatfrequency: 60 +zabbix_proxy_historycachesize: 8M +zabbix_proxy_historyindexcachesize: 4M zabbix_proxy_hostname: "{{ inventory_hostname }}" +zabbix_proxy_housekeepingfrequency: 1 +zabbix_proxy_include: /etc/zabbix/zabbix_proxy.conf.d +zabbix_proxy_javagatewayport: 10052 +zabbix_proxy_libdir: /usr/lib/zabbix zabbix_proxy_listenport: 10051 -zabbix_proxy_sourceip: -zabbix_proxy_logtype: file +zabbix_proxy_loadmodulepath: "{{ zabbix_proxy_libdir }}/modules" zabbix_proxy_logfile: /var/log/zabbix/zabbix_proxy.log zabbix_proxy_logfilesize: 10 -zabbix_proxy_enableremotecommands: 0 -zabbix_proxy_debuglevel: 3 +zabbix_proxy_logtype: file zabbix_proxy_pidfile: /var/run/zabbix/zabbix_proxy.pid +zabbix_proxy_proxylocalbuffer: 0 +zabbix_proxy_proxyofflinebuffer: 1 +zabbix_proxy_snmptrapperfile: /tmp/zabbix_traps.tmp zabbix_proxy_socketdir: /var/run/zabbix -zabbix_proxy_dbencoding: utf8 -zabbix_proxy_dbcollation: utf8_bin -zabbix_proxy_dbhost: localhost -zabbix_proxy_dbname: zabbix_proxy -zabbix_proxy_dbschema: -zabbix_proxy_dbuser: zabbix_proxy -zabbix_proxy_dbpassword: zabbix_proxy -zabbix_proxy_dbsocket: -zabbix_proxy_dbport: 5432 -zabbix_proxy_dbpassword_hash_method: md5 +zabbix_proxy_startdbsyncers: 4 +zabbix_proxy_startdiscoverers: 1 +zabbix_proxy_starthttppollers: 1 +zabbix_proxy_startipmipollers: 0 zabbix_proxy_startodbcpollers: 1 -zabbix_proxy_dbhost_run_install: true -zabbix_proxy_privileged_host: localhost -zabbix_proxy_localbuffer: 0 # Will be deprecated in 2.0.0 -zabbix_proxy_proxylocalbuffer: "{{ zabbix_proxy_localbuffer }}" -zabbix_proxy_offlinebuffer: 1 # Will be deprecated in 2.0.0 -zabbix_proxy_proxyofflinebuffer: "{{ zabbix_proxy_offlinebuffer }}" -zabbix_proxy_heartbeatfrequency: 60 -zabbix_proxy_configfrequency: 3600 -zabbix_proxy_datasenderfrequency: 1 +zabbix_proxy_startpingers: 1 zabbix_proxy_startpollers: 5 -zabbix_proxy_startipmipollers: 0 zabbix_proxy_startpollersunreachable: 1 -zabbix_proxy_starttrappers: 5 -zabbix_proxy_startpingers: 1 -zabbix_proxy_startdiscoverers: 1 -zabbix_proxy_starthttppollers: 1 zabbix_proxy_startpreprocessors: 3 -zabbix_proxy_javagateway: -zabbix_proxy_javagatewayport: 10052 -zabbix_proxy_startjavapollers: 5 -zabbix_proxy_startvmwarecollector: 0 -zabbix_proxy_vmwarefrequency: 60 -zabbix_proxy_vmwarecachesize: 8 -zabbix_proxy_snmptrapperfile: /tmp/zabbix_traps.tmp -zabbix_proxy_snmptrapper: 0 -zabbix_proxy_listenip: -zabbix_proxy_housekeepingfrequency: 1 -zabbix_proxy_cachesize: 8 -zabbix_proxy_startdbsyncers: 4 -zabbix_proxy_historycachesize: 8 -zabbix_proxy_historyindexcachesize: 4 -zabbix_proxy_historytextcachesize: 16 +zabbix_proxy_starttrappers: 5 +zabbix_proxy_statsallowedip: "127.0.0.1" zabbix_proxy_timeout: 3 +zabbix_proxy_tmpdir: /tmp zabbix_proxy_trappertimeout: 300 zabbix_proxy_unreachableperiod: 45 -zabbix_proxy_unavaliabledelay: 60 -zabbix_proxy_unreachabedelay: 15 -zabbix_proxy_externalscripts: /usr/lib/zabbix/externalscripts -zabbix_proxy_fpinglocation: /usr/sbin/fping -zabbix_proxy_fping6location: /usr/sbin/fping6 -zabbix_proxy_sshkeylocation: -zabbix_proxy_loglowqueries: 0 -zabbix_proxy_tmpdir: /tmp -zabbix_proxy_allowroot: 0 -zabbix_proxy_include: /etc/zabbix/zabbix_proxy.conf.d -zabbix_proxy_include_mode: "0755" -zabbix_proxy_libdir: /usr/lib/zabbix -zabbix_proxy_loadmodulepath: "{{ zabbix_proxy_libdir }}/modules" -zabbix_proxy_manage_service: true -zabbix_proxy_statsallowedip: "127.0.0.1" -zabbix_proxy_vaulttoken: zabbix_proxy_vaulturl: https://127.0.0.1:8200 -zabbix_proxy_vaultdbpath: -zabbix_proxy_listenbacklog: - -# TLS settings -zabbix_proxy_tlsconnect: -zabbix_proxy_tlsaccept: -zabbix_proxy_tlscafile: -zabbix_proxy_tlscrlfile: -zabbix_proxy_tlsservercertissuer: -zabbix_proxy_tlsservercertsubject: -zabbix_proxy_tls_subject: "{{ zabbix_proxy_tlsservercertsubject }}" # FIXME this is not correct and should be removed with 2.0.0, here only to prevent regression -zabbix_proxy_tlscertfile: -zabbix_proxy_tlskeyfile: -zabbix_proxy_tlspskidentity: - -zabbix_proxy_tls_config: - no_encryption: "no_encryption" - psk: "PSK" - cert: "certificate" +zabbix_proxy_vmwarecachesize: 8M +zabbix_proxy_vmwarefrequency: 60 # Zabbix API stuff -zabbix_validate_certs: true # Will be deprecated in 2.0.0 -zabbix_api_validate_certs: "{{ zabbix_validate_certs }}" -zabbix_url: http://localhost # Will be deprecated in 2.0.0 -zabbix_api_server_url: "{{ zabbix_url }}" -zabbix_api_server_host: "{{ zabbix_api_server_url | urlsplit('hostname') }}" -zabbix_api_port_from_url: "{{ zabbix_api_server_port | default(zabbix_api_server_url | urlsplit('port')) }}" -zabbix_api_scheme_from_url: "{{ zabbix_api_server_url | urlsplit('scheme') }}" -zabbix_api_port_from_shema: "{{ (zabbix_api_scheme_from_url == 'https') | ternary(443, 80) }}" -# zabbix_http_user: admin # Will be deprecated in 2.0.0 -# zabbix_http_password: admin # Will be deprecated in 2.0.0 -# zabbix_api_http_user: admin -# zabbix_api_http_password: admin -zabbix_api_user: Admin # Will be deprecated in 2.0.0 -zabbix_api_pass: !unsafe zabbix # Will be deprecated in 2.0.0 -zabbix_api_login_user: "{{ zabbix_api_user }}" -zabbix_api_login_pass: "{{ zabbix_api_pass }}" +zabbix_api_server_host: localhost +zabbix_api_use_ssl: false +# zabbix_api_server_port: 80 +zabbix_api_login_user: Admin +zabbix_api_login_pass: !unsafe zabbix +zabbix_api_validate_certs: false ansible_httpapi_pass: "{{ zabbix_api_login_pass }}" -ansible_httpapi_port: "{{ (zabbix_api_port_from_url == '') | ternary(zabbix_api_port_from_shema, zabbix_api_port_from_url) }}" -ansible_httpapi_use_ssl: "{{ zabbix_api_use_ssl | default((zabbix_api_scheme_from_url == 'https') | ternary(true, false)) }}" +ansible_httpapi_port: "{{ zabbix_api_server_port }}" ansible_httpapi_validate_certs: "{{ zabbix_api_validate_certs }}" -zabbix_api_create_proxy: false zabbix_api_timeout: 30 -zabbix_create_proxy: present # or absent # Will be deprecated in 2.0.0 -zabbix_proxy_state: "{{ zabbix_create_proxy }}" +zabbix_api_create_proxy: false +zabbix_proxy_state: present zabbix_proxy_status: active # or passive -zabbix_useuip: 1 -zabbix_proxy_become_on_localhost: true -zabbix_proxy_interface: - useip: "{{ zabbix_useuip }}" - ip: "{{ zabbix_proxy_ip }}" - dns: "{{ ansible_fqdn }}" - port: "{{ zabbix_proxy_listenport }}" +# TLS setttings +zabbix_proxy_tlsaccept: +zabbix_proxy_tlsconnect: diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/handlers/main.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/handlers/main.yml index 8f42133be..9d5b88ee3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/handlers/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/handlers/main.yml @@ -2,27 +2,16 @@ # handlers file for zabbix-proxy - name: restart zabbix-proxy - service: + ansible.builtin.service: name: zabbix-proxy state: restarted enabled: true become: true when: - zabbix_proxy_manage_service | bool - - zabbix_repo != 'epel' - -- name: restart zabbix-proxy - service: - name: zabbix-proxy-mysql{{ zabbix_proxy_database_long }} - state: restarted - enabled: true - become: true - when: - - zabbix_proxy_manage_service | bool - - zabbix_repo == 'epel' - name: "clean repo files from proxy creds" - shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true + ansible.builtin.shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true become: true when: - ansible_os_family == 'RedHat' diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/Debian.yml index fae6b5b96..8e27e7d27 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/Debian.yml @@ -1,76 +1,48 @@ --- -- name: "Include Zabbix gpg ids" - include_vars: zabbix.yml - -- name: "Set some variables" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - zabbix_proxy_apt_repository: - - "http://repo.zabbix.com/zabbix/{{ zabbix_version }}/{{ ansible_distribution.lower() }}/" - - "{{ ansible_distribution_release }}" - - "main" - zabbix_underscore_version: "{{ zabbix_version | regex_replace('\\.', '_') }}" - zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" - when: - - ansible_machine != "aarch64" - -- name: "Set some variables" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - zabbix_proxy_apt_repository: - - "http://repo.zabbix.com/zabbix/{{ zabbix_version }}/{{ ansible_distribution.lower() }}-arm64/" - - "{{ ansible_distribution_release }}" - - "main" - zabbix_underscore_version: "{{ zabbix_version | regex_replace('\\.', '_') }}" +- name: "Debian | Set short version name" + ansible.builtin.set_fact: + zabbix_short_version: "{{ zabbix_proxy_version | regex_replace('\\.', '') }}" zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" - when: - - ansible_machine == "aarch64" - -- name: "Debian | Set some facts" - set_fact: - apache_log: apache2 - datafiles_path: "/usr/share/zabbix-proxy-{{ zabbix_proxy_database }}" - when: - - zabbix_version is version_compare('3.0', '<') + zabbix_underscore_version: "{{ zabbix_proxy_version | regex_replace('\\.', '_') }}" tags: - - zabbix-proxy - - init - - config + - always -- name: "Debian | Set some facts for Zabbix >= 3.0 && < 5.4" - set_fact: - apache_log: apache2 - datafiles_path: /usr/share/doc/zabbix-proxy-{{ zabbix_proxy_database }} - when: - - zabbix_version is version('3.0', '>=') - - zabbix_version is version('5.4', '<') +- name: "Debian | Installing lsb-release" + ansible.builtin.apt: + pkg: lsb-release + update_cache: true + cache_valid_time: 3600 + force: true + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + become: true tags: - - zabbix-proxy - - init - - config + - install -- name: "Debian | Set some facts for Zabbix == 5.4" - set_fact: - datafiles_path: /usr/share/doc/zabbix-sql-scripts/{{ zabbix_proxy_database_long }} +- name: "Debian | Update ansible_lsb fact" + ansible.builtin.setup: + gather_subset: + - lsb + +- name: "Debian | Repo URL" + ansible.builtin.set_fact: + zabbix_repo_deb_url: "{{ _zabbix_repo_deb_url }}/{{ ansible_lsb.id.lower() }}{{ '-arm64' if ansible_machine == 'aarch64' and ansible_lsb.id == 'debian' else ''}}" when: - - zabbix_version is version('5.4', '==') + - zabbix_repo_deb_url is undefined tags: - - zabbix-proxy - - init - - config + - always -- name: "Debian | Set some facts for Zabbix >= 6.0" - set_fact: - datafiles_path: /usr/share/zabbix-sql-scripts/{{ zabbix_proxy_database_long }} - when: - - zabbix_version is version('6.0', '>=') +- name: "Debian | Set some facts for Zabbix" + ansible.builtin.set_fact: + datafiles_path: /usr/share/doc/zabbix-sql-scripts/{{ zabbix_proxy_db_long }} tags: - - zabbix-proxy - - init + - install - config - name: "Debian | Installing gnupg" - apt: + ansible.builtin.apt: pkg: gnupg update_cache: true cache_valid_time: 3600 @@ -82,108 +54,97 @@ register: gnupg_installed until: gnupg_installed is succeeded become: true + tags: + - install + +# In releases older than Debian 12 and Ubuntu 22.04, /etc/apt/keyrings does not exist by default. +# It SHOULD be created with permissions 0755 if it is needed and does not already exist. +# See: https://wiki.debian.org/DebianRepository/UseThirdParty +- name: "Debian | Create /etc/apt/keyrings/ on older versions" + ansible.builtin.file: + path: /etc/apt/keyrings/ + state: directory + mode: "0755" + become: true + when: + - (ansible_distribution == "Ubuntu" and ansible_distribution_major_version < "22") or + (ansible_distribution == "Debian" and ansible_distribution_major_version < "12") -- name: "Debian | Install gpg key" - apt_key: - id: "{{ sign_keys[zabbix_short_version][ansible_distribution_release]['sign_key'] }}" +- name: "Debian | Download gpg key" + ansible.builtin.get_url: url: http://repo.zabbix.com/zabbix-official-repo.key + dest: "{{ zabbix_gpg_key }}" + mode: "0644" + force: true register: are_zabbix_proxy_dependency_packages_installed until: are_zabbix_proxy_dependency_packages_installed is succeeded - when: - - zabbix_repo == "zabbix" become: true tags: - - zabbix-proxy - - init + - install - name: "Debian | Installing repository {{ ansible_distribution }}" - apt_repository: - repo: "{{ item }} {{ zabbix_proxy_apt_repository | join(' ') }}" - state: present - when: zabbix_repo == "zabbix" + ansible.builtin.copy: + dest: /etc/apt/sources.list.d/zabbix.sources + owner: root + group: root + mode: 0644 + content: | + Types: deb deb-src + Enabled: yes + URIs: {{ zabbix_repo_deb_url }} + Suites: {{ ansible_distribution_release }} + Components: {{ zabbix_repo_deb_component }} + Architectures: {{ 'amd64' if ansible_machine != 'aarch64' else 'arm64'}} + Signed-By: {{ zabbix_gpg_key }} become: true - with_items: - - deb-src - - deb tags: - - zabbix-proxy - - init - + - install + - name: "Debian | Create /etc/apt/preferences.d/" - file: + ansible.builtin.file: path: /etc/apt/preferences.d/ state: directory - mode: '0755' + mode: "0755" when: - zabbix_proxy_apt_priority | int become: true - + tags: + - install + - name: "Debian | Configuring the weight for APT" - copy: + ansible.builtin.copy: dest: "/etc/apt/preferences.d/zabbix-proxy-{{ zabbix_proxy_database }}" content: | Package: zabbix-proxy-{{ zabbix_proxy_database }} Pin: origin repo.zabbix.com Pin-Priority: {{ zabbix_proxy_apt_priority }} owner: root - mode: '0644' + mode: "0644" when: - zabbix_proxy_apt_priority | int become: true - -- name: Check if warn parameter can be used for shell module - set_fact: - produce_warn: False - when: ansible_version.full is version("2.14", "<") - -- name: apt-get clean - shell: apt-get clean; apt-get update - args: - warn: "{{ produce_warn | default(omit) }}" - changed_when: false - become: true tags: - - skip_ansible_lint - -# On certain 18.04 images, such as docker or lxc, dpkg is configured not to -# install files into paths /usr/share/doc/* -# Since this is where Zabbix installs its database schemas, we need to allow -# files to be installed to /usr/share/doc/zabbix* -- name: Check for the dpkg exclude line - command: grep -F 'path-exclude=/usr/share/doc/*' /etc/dpkg/dpkg.cfg.d/excludes - register: dpkg_exclude_line - failed_when: false - changed_when: false - check_mode: false - -- name: Allow Zabbix dpkg installs to /usr/share/doc/zabbix* - lineinfile: - path: /etc/dpkg/dpkg.cfg.d/excludes - line: 'path-include=/usr/share/doc/zabbix*' - become: true - when: - - dpkg_exclude_line.rc == 0 + - install - name: "Debian | Installing zabbix-proxy-{{ zabbix_proxy_database }}" - apt: - pkg: zabbix-proxy-{{ zabbix_proxy_database }} - state: "{{ zabbix_proxy_package_state }}" + ansible.builtin.apt: + pkg: "zabbix-proxy-{{ zabbix_proxy_database }}" update_cache: true cache_valid_time: 0 - install_recommends: "{{ zabbix_proxy_install_recommends }}" + force: true + state: "{{ zabbix_proxy_package_state }}" default_release: "{{ ansible_distribution_release }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_package_installed - until: zabbix_proxy_package_installed is succeeded + register: is_zabbix_proxy_package_installed + until: is_zabbix_proxy_package_installed is succeeded become: true tags: - - zabbix-proxy - - init + - install - name: "Debian | Installing zabbix-sql-scripts" - apt: + ansible.builtin.apt: pkg: zabbix-sql-scripts state: "{{ zabbix_proxy_package_state }}" update_cache: true @@ -195,14 +156,13 @@ register: zabbix_proxy_package_sql_installed until: zabbix_proxy_package_sql_installed is succeeded when: - - zabbix_version is version('5.4', '>=') + - zabbix_proxy_version is version('6.0', '>=') become: true tags: - - zabbix-proxy - - init + - install - name: "Debian | Install Ansible module dependencies" - apt: + ansible.builtin.apt: name: "{{ zabbix_python_prefix }}-psycopg2" state: present environment: @@ -212,16 +172,14 @@ until: zabbix_proxy_dependencies_installed is succeeded become: true when: - - zabbix_database_creation + - zabbix_proxy_database_creation tags: - - zabbix-proxy - - init + - install + - dependencies - name: "Debian | Install Mysql Client package" - apt: - name: - - default-mysql-client - - "{{ zabbix_python_prefix }}-mysqldb" + ansible.builtin.apt: + name: "{{ mysql_client_pkgs[ansible_distribution_major_version] }}" state: present environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" @@ -232,35 +190,13 @@ when: - zabbix_proxy_database == 'mysql' - zabbix_proxy_install_database_client - - ansible_distribution_release != "buster" tags: - - zabbix-proxy - - init - - database - -- name: "Debian 10 | Install Mysql Client package" - apt: - name: - - mariadb-client - - "{{ zabbix_python_prefix }}-mysqldb" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_dependencies_installed - until: zabbix_proxy_dependencies_installed is succeeded - become: true - when: - - zabbix_proxy_database == 'mysql' - - zabbix_proxy_install_database_client - - ansible_distribution_release == "buster" - tags: - - zabbix-proxy - - init + - install + - dependencies - database - name: "Debian | Install PostgreSQL Client package" - apt: + ansible.builtin.apt: name: postgresql-client state: present environment: @@ -270,16 +206,16 @@ until: are_zabbix_proxy_dependency_packages_installed is succeeded become: true when: - - zabbix_database_creation or zabbix_database_sqlload + - zabbix_proxy_database_creation or zabbix_proxy_database_sqlload - zabbix_proxy_database == 'pgsql' - zabbix_proxy_install_database_client tags: - - zabbix-proxy - - init + - install + - dependencies - database - name: "Debian | Install sqlite3" - apt: + ansible.builtin.apt: name: sqlite3 state: present environment: @@ -291,4 +227,6 @@ when: - zabbix_proxy_database == 'sqlite3' tags: - - zabbix-proxy + - install + - dependencies + - database diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/RedHat.yml index 34a40396e..f35b3c7b3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/RedHat.yml @@ -1,323 +1,147 @@ --- # Tasks specific for RedHat systems -- name: "Set short version name" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - -- name: "RedHat | Use EPEL package name" - set_fact: - zabbix_proxy_package: "zabbix{{ zabbix_version | regex_replace('\\.', '') }}-proxy" - when: - - zabbix_repo == "epel" +- name: "RedHat | Set short version name" + ansible.builtin.set_fact: + zabbix_short_version: "{{ zabbix_proxy_version | regex_replace('\\.', '') }}" tags: - - zabbix-proxy - - init - -- name: "RedHat | Define package with version" - set_fact: - zabbix_proxy_package: "zabbix{{ zabbix_short_version }}-proxy-{{ zabbix_proxy_database }}" - cacheable: true - when: - - zabbix_proxy_rhel_version is defined - - zabbix_repo != "epel" + - always - name: "RedHat | Define package without version" - set_fact: + ansible.builtin.set_fact: zabbix_proxy_package: "zabbix-proxy-{{ zabbix_proxy_database }}" cacheable: true - when: - - zabbix_proxy_rhel_version is not defined - - zabbix_repo != "epel" - -- name: "RedHat | Set some facts Zabbix < 3.0" - set_fact: - apache_log: httpd - datafiles_path: "/usr/share/doc/zabbix-proxy-{{ zabbix_proxy_database }}-{{ zabbix_version }}*/create" - when: - - zabbix_version is version('3.0', '<') - tags: - - zabbix-proxy - -- name: "RedHat | Set facts for Zabbix >= 3.0 && < 5.4" - set_fact: - apache_log: httpd - datafiles_path: "/usr/share/doc/zabbix-proxy-{{ zabbix_proxy_database }}-{{ zabbix_version }}*" - when: - - zabbix_version is version('3.0', '>=') - - zabbix_version is version('5.4', '<') tags: - - zabbix-proxy + - always -- name: "RedHat | Set facts for Zabbix == 5.4" - set_fact: - datafiles_path: "/usr/share/doc/zabbix-sql-scripts/{{ zabbix_proxy_database_long }}" - when: - - zabbix_version is version('5.4', '==') +- name: "RedHat | Set facts for Zabbix" + ansible.builtin.set_fact: + datafiles_path: "/usr/share/doc/zabbix-sql-scripts/{{ zabbix_proxy_db_long }}" tags: - - zabbix-server - -- name: "RedHat | Set facts for Zabbix >= 6.0" - set_fact: - datafiles_path: "/usr/share/zabbix-sql-scripts/{{ zabbix_proxy_database_long }}" - when: - - zabbix_version is version('6.0', '>=') - tags: - - zabbix-server - -- name: "RedHat | Set facts for Zabbix >= 3.0 and RedHat 8" - set_fact: - apache_log: httpd - datafiles_path: "/usr/share/doc/zabbix-proxy-{{ zabbix_proxy_database }}" - when: - - zabbix_version is version('3.0', '>=') - - zabbix_version is version('5.4', '<') - - ansible_distribution_major_version == '8' - tags: - - zabbix-proxy - -- name: "RedHat | Set some facts EPEL" - set_fact: - datafiles_path: "/usr/share/zabbix-{{ zabbix_proxy_database_long }}" - when: - - zabbix_repo == "epel" - tags: - - zabbix-server - -- name: "RedHat | Create 'zabbix' group (EPEL)" - group: - name: "{{ zabbix_proxy_groupname | default('zabbix') }}" - gid: "{{ zabbix_proxy_groupid | default(omit) }}" - state: present - become: true - when: - - zabbix_repo == "epel" + - always -- name: "RedHat | Create 'zabbix' user (EPEL)" - user: - name: "{{ zabbix_proxy_username | default('zabbix') }}" - comment: Zabbix Monitoring System - uid: "{{ zabbix_proxy_userid | default(omit) }}" - group: zabbix - become: true - when: - - zabbix_repo == "epel" - -- name: "Make sure old file is absent" - file: +- name: "RedHat | Make sure old file is absent" + ansible.builtin.file: path: /etc/yum.repos.d/zabbix-supported.repo state: absent become: true + tags: + - install - name: "RedHat | Install basic repo file" - yum_repository: + ansible.builtin.yum_repository: name: "{{ item.name }}" description: "{{ item.description }}" baseurl: "{{ item.baseurl }}" gpgcheck: "{{ item.gpgcheck }}" gpgkey: "{{ item.gpgkey }}" mode: "{{ item.mode | default('0644') }}" - priority: "{{ item.priority | default('98') }}" + priority: "{{ item.priority | default('99') }}" state: "{{ item.state | default('present') }}" proxy: "{{ zabbix_http_proxy | default(omit) }}" with_items: "{{ zabbix_repo_yum }}" register: yum_repo_installed become: true - when: - - zabbix_repo == "zabbix" notify: - "clean repo files from proxy creds" tags: - - zabbix-agent - -- name: "RedHat | Installing zabbix-proxy-{{ zabbix_proxy_database }}" - package: - pkg: "{{ zabbix_proxy_package }}-{{ zabbix_proxy_version }}.{{ zabbix_proxy_version_minor }}" - state: "{{ zabbix_proxy_package_state }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - become: true - when: - zabbix_repo != "other" - register: is_zabbix_proxy_package_installed - until: is_zabbix_proxy_package_installed is succeeded - -- name: "RedHat | Installing zabbix-proxy-{{ zabbix_proxy_database }} (When zabbix_repo == other)" - package: - pkg: "{{ zabbix_proxy_package }}-{{ zabbix_proxy_version }}.{{ zabbix_proxy_version_minor }}" - state: "{{ zabbix_proxy_package_state }}" - become: true - when: - zabbix_repo == "other" - register: is_zabbix_proxy_package_installed - until: is_zabbix_proxy_package_installed is succeeded - -- name: "RedHat | Installing zabbix-sql-scripts" - package: - pkg: "zabbix-sql-scripts-{{ zabbix_proxy_version }}.{{ zabbix_proxy_version_minor }}" - state: "{{ zabbix_proxy_package_state }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_sql_package_installed - until: zabbix_proxy_sql_package_installed is succeeded - when: - - zabbix_version is version('5.4', '>=') - - zabbix_repo != "other" - become: true - tags: - - zabbix-server - -- name: "RedHat | Installing zabbix-sql-scripts (When zabbix_repo == other)" - package: - pkg: "zabbix-sql-scripts-{{ zabbix_proxy_version }}.{{ zabbix_proxy_version_minor }}" - state: "{{ zabbix_proxy_package_state }}" - register: zabbix_proxy_sql_package_installed - until: zabbix_proxy_sql_package_installed is succeeded - when: - - zabbix_version is version('5.4', '>=') - - zabbix_repo == "other" - become: true - tags: - - zabbix-server - -- name: "RedHat | Install Ansible PostgreSQL module dependencies" - yum: - name: python-psycopg2 + - install + +- name: Install packages for Zabbix Repository + block: + - name: "RedHat | Installing zabbix-proxy-{{ zabbix_proxy_database }}" + ansible.builtin.yum: + pkg: "{{ zabbix_proxy_package }}-{{ zabbix_proxy_version }}.{{ zabbix_proxy_version_minor }}" + state: "{{ zabbix_proxy_package_state }}" + disablerepo: "{{ zabbix_proxy_disable_repo | default(omit) }}" + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + become: true + register: is_zabbix_proxy_package_installed + until: is_zabbix_proxy_package_installed is succeeded + + - name: "RedHat | Installing zabbix-sql-scripts" + ansible.builtin.yum: + pkg: "zabbix-sql-scripts-{{ zabbix_proxy_version }}.{{ zabbix_proxy_version_minor }}" + state: "{{ zabbix_proxy_package_state }}" + disablerepo: "{{ zabbix_proxy_disable_repo | default(omit) }}" + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_proxy_sql_package_installed + until: zabbix_proxy_sql_package_installed is succeeded + become: true + tags: + - install + +- name: "RedHat | Install Ansible PostgreSQL Client package" + ansible.builtin.yum: + name: "{{ pgsql_depenencies[ansible_distribution_major_version] }}" state: present environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" become: true - register: are_zabbix_proxy_dependency_packages_installed - until: are_zabbix_proxy_dependency_packages_installed is succeeded + register: are_zabbix_proxy_pgsql_packages_installed + until: are_zabbix_proxy_pgsql_packages_installed is succeeded when: - - zabbix_database_creation or zabbix_database_sqlload + - zabbix_proxy_database_creation or zabbix_proxy_database_sqlload - zabbix_proxy_database == 'pgsql' - - ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6" - tags: - - zabbix-proxy - - init - -- name: "RedHat | Install Ansible module dependencies on RHEL9 or RHEL8" - yum: - name: python3-psycopg2 - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_dependencies_installed - until: zabbix_proxy_dependencies_installed is succeeded - become: true - when: - - zabbix_database_creation - - zabbix_proxy_database == 'pgsql' - - ansible_distribution_major_version|int >= 8 - tags: - - zabbix-server - -- name: "RedHat | Install Mysql Client package RHEL7" - yum: - name: - - mariadb - - MySQL-python - state: installed - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - become: true - register: are_zabbix_proxy_dependency_packages_installed - until: are_zabbix_proxy_dependency_packages_installed is succeeded - when: - - zabbix_database_creation or zabbix_database_sqlload - - zabbix_proxy_database == 'mysql' - - ansible_distribution_major_version == '7' - tags: - - zabbix-proxy - - init - -- name: "RedHat | Install Mysql Client packages RHEL9 or RHEL8" - yum: - name: - - mysql - - python3-PyMySQL - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_dependencies_installed - until: zabbix_proxy_dependencies_installed is succeeded - become: true - when: - - zabbix_proxy_database == 'mysql' - - ansible_distribution_major_version|int >= 8 tags: - - zabbix-proxy - - init - -- name: "RedHat | Install Mysql Client package RHEL5 - 6" - yum: - name: - - mysql - - MySQL-python - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - become: true - register: are_zabbix_proxy_dependency_packages_installed - until: are_zabbix_proxy_dependency_packages_installed is succeeded - when: - - zabbix_database_creation or zabbix_database_sqlload - - zabbix_proxy_database == 'mysql' - - ansible_distribution_major_version == "6" or ansible_distribution_major_version == "5" - - zabbix_proxy_install_database_client - tags: - - zabbix-proxy - - init + - install - database - -- name: "RedHat | Install PostgreSQL client package" - yum: - name: postgresql - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - become: true - register: are_zabbix_proxy_dependency_packages_installed - until: are_zabbix_proxy_dependency_packages_installed is succeeded - when: - - zabbix_database_creation or zabbix_database_sqlload - - zabbix_proxy_database == 'pgsql' + - dependencies + +- name: "RedHat | Install Mysql Client Package" + block: + - name: "RedHat | Add Mysql Repo (Centos 7 Only)" + ansible.builtin.yum_repository: + name: mariadb + description: MariaDB 10.8 CentOS repository list + file: mariadb + baseurl: "https://mirror.rackspace.com/mariadb/yum/10.11/centos{{ ansible_distribution_major_version }}-amd64" + gpgcheck: no + when: ansible_distribution_major_version == '7' + + - name: "RedHat | Install Mysql Client package" + ansible.builtin.yum: + name: "{{ mysql_client_pkgs[ansible_distribution_major_version] }}" + state: installed + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + become: true + register: are_zabbix_proxy_mysql_packages_installed + until: are_zabbix_proxy_mysql_packages_installed is succeeded + when: + - zabbix_proxy_database_creation or zabbix_proxy_database_sqlload - zabbix_proxy_install_database_client + - zabbix_proxy_database == 'mysql' tags: - - zabbix-proxy - - init + - install - database + - dependencies - name: "RedHat | Install sqlite3" - yum: + ansible.builtin.yum: name: - sqlite state: present environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_dependencies_installed - until: zabbix_proxy_dependencies_installed is succeeded + register: zabbix_proxy_sqlite_packages_installed + until: zabbix_proxy_sqlite_packages_installed is succeeded become: true when: - zabbix_proxy_database == 'sqlite3' tags: - - zabbix-proxy + - install + - database + - dependencies - name: "Configure SELinux when enabled" - include_tasks: selinux.yml + ansible.builtin.include_tasks: selinux.yml when: - - zabbix_selinux | bool + - zabbix_proxy_selinux | bool diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/main.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/main.yml index bd39b5b8a..f564635b1 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/main.yml @@ -1,71 +1,114 @@ --- # tasks file for zabbix_proxy - name: "Include OS-specific variables" - include_vars: "{{ ansible_os_family }}.yml" + ansible.builtin.include_vars: "{{ ansible_os_family }}.yml" + tags: + - always - name: Determine Latest Supported Zabbix Version - set_fact: - zabbix_proxy_version: "{{ zabbix_valid_proxy_versions[ansible_distribution_major_version][0] | default(6.0) }}" - when: zabbix_proxy_version is not defined + ansible.builtin.set_fact: + zabbix_proxy_version: "{{ zabbix_valid_proxy_versions[ansible_distribution_major_version][0] | default(6.4) }}" + when: zabbix_proxy_version is not defined or zabbix_proxy_version is none + tags: + - always -- name: "Replace Sangoma with RedHat task" - set_fact: - ansible_os_family: "RedHat" - when: - - ansible_os_family == 'Sangoma' +- name: Set More Variables + ansible.builtin.set_fact: + zabbix_proxy_db_long: "{{ 'postgresql' if zabbix_proxy_database == 'pgsql' else zabbix_proxy_database }}" + zabbix_valid_version: "{{ zabbix_proxy_version|float in zabbix_valid_proxy_versions[ansible_distribution_major_version] }}" + zabbix_short_version: "{{ zabbix_proxy_version | regex_replace('\\.', '') }}" + zabbix_proxy_fpinglocation: "{{ zabbix_proxy_fpinglocation if zabbix_proxy_fpinglocation is defined else _zabbix_proxy_fpinglocation}}" + zabbix_proxy_fping6location: "{{ zabbix_proxy_fping6location if zabbix_proxy_fping6location is defined else _zabbix_proxy_fping6location}}" + tags: + - always + +- name: Stopping Install of Invalid Version + ansible.builtin.fail: + msg: Zabbix version {{ zabbix_proxy_version }} is not supported on {{ ansible_distribution }} {{ ansible_distribution_major_version }} + when: not zabbix_valid_version + tags: + - always + +- name: Setting Zabbix API Server Port + ansible.builtin.set_fact: + zabbix_api_server_port: "{{ '443' if zabbix_api_use_ssl|bool else '80' }}" + when: zabbix_api_server_port is undefined + +- name: Set Path to SQL File + ansible.builtin.set_fact: + datafile_path: "{{ db_file_path[zabbix_short_version] }}" + tags: + - install + - config - name: "Set default ip address for zabbix_proxy_ip" - set_fact: + ansible.builtin.set_fact: zabbix_proxy_ip: "{{ hostvars[inventory_hostname]['ansible_default_ipv4'].address }}" when: - zabbix_proxy_ip is not defined - "'ansible_default_ipv4' in hostvars[inventory_hostname]" + tags: + - install + - config + - api -- name: "Set OS dependent variables" - include_vars: "{{ item }}" - with_first_found: - - "../vars/{{ ansible_distribution }}.yml" - - "../vars/main.yml" +- name: "Complete OS Specific Tasks" + ansible.builtin.include_tasks: "{{ ansible_os_family }}.yml" -- name: "Install the correct repository" - include_tasks: "{{ ansible_os_family }}.yml" +- name: "Get the file for database schema" + ansible.builtin.shell: ls -1 {{ db_file_path[zabbix_short_version] }} + changed_when: false + become: true + when: + - zabbix_proxy_database_sqlload + register: ls_output_schema + tags: + - database -- name: "Installing the {{ zabbix_proxy_database_long }} database" - include_tasks: "{{ zabbix_proxy_database_long }}.yml" +- name: "Installing the database" + ansible.builtin.include_tasks: "{{ zabbix_proxy_db_long }}.yml" - name: "Create include dir zabbix-proxy" - file: + ansible.builtin.file: path: "{{ zabbix_proxy_include }}" - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" mode: "{{ zabbix_proxy_include_mode }}" state: directory become: true + tags: + - install + - config - name: "Create module dir zabbix-proxy" - file: + ansible.builtin.file: path: "{{ zabbix_proxy_loadmodulepath }}" - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" state: directory mode: "0755" become: true + tags: + - install + - config - name: "Create directory for PSK file if not exist." - file: + ansible.builtin.file: path: "{{ zabbix_proxy_tlspskfile | dirname }}" mode: 0755 state: directory become: true when: - zabbix_proxy_tlspskfile is defined + tags: + - config - name: "Place TLS PSK File" - copy: + ansible.builtin.copy: dest: "{{ zabbix_proxy_tlspskfile }}" content: "{{ zabbix_proxy_tlspsk_secret }}" - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" mode: 0400 become: true when: @@ -73,34 +116,20 @@ - zabbix_proxy_tlspsk_secret is defined notify: - restart zabbix-proxy - -- name: "Allow zabbix-proxy to open connections (SELinux)" - ansible.posix.seboolean: - name: zabbix_can_network - persistent: true - state: true - become: true - when: ansible_selinux.status == "enabled" - tags: selinux - -- name: "Allow zabbix-proxy to connect to zabbix_proxy_preprocessing.sock (SELinux)" - ansible.posix.seboolean: - name: daemons_enable_cluster_mode - persistent: true - state: true - become: true - when: ansible_selinux.status == "enabled" - tags: selinux + tags: + - config - name: "Configure zabbix-proxy" - template: + ansible.builtin.template: src: zabbix_proxy.conf.j2 - dest: /etc/zabbix/zabbix_proxy.conf - owner: zabbix - group: zabbix + dest: "{{ zabbix_proxy_config }}" + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" mode: "{{ zabbix_proxy_conf_mode }}" notify: restart zabbix-proxy become: true + tags: + - config - name: Ensure proxy definition is up-to-date (added/updated/removed) vars: @@ -108,9 +137,9 @@ ansible_user: "{{ zabbix_api_login_user }}" ansible_network_os: community.zabbix.zabbix ansible_connection: httpapi - # Can't think of a way to make http_login_* vars be undefined -( - http_login_user: "{{ zabbix_api_http_user | default(zabbix_http_user | default(-42)) }}" - http_login_password: "{{ zabbix_api_http_password | default(zabbix_http_password | default(-42)) }}" + ansible_httpapi_use_ssl: "{{ zabbix_api_use_ssl }}" + http_login_user: "{{ zabbix_api_http_user | default(-42) }}" + http_login_password: "{{ zabbix_api_http_password | default(-42) }}" community.zabbix.zabbix_proxy: state: "{{ zabbix_proxy_state }}" status: "{{ zabbix_proxy_status }}" @@ -125,14 +154,15 @@ when: - zabbix_api_create_proxy | bool delegate_to: "{{ zabbix_api_server_host }}" - become: false tags: - api - name: "zabbix-proxy started" - service: + ansible.builtin.service: name: zabbix-proxy state: started enabled: true become: true when: zabbix_proxy_manage_service | bool + tags: + - service diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/mysql.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/mysql.yml index 6d699ea83..dde847a53 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/mysql.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/mysql.yml @@ -1,21 +1,35 @@ --- # task file for mysql -- name: "Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" - set_fact: +- name: "MySQL | Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ zabbix_proxy_dbhost if (zabbix_proxy_dbhost != 'localhost') else inventory_hostname }}" when: - zabbix_proxy_dbhost_run_install + tags: + - database -- name: "Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" - set_fact: +- name: "MySQL | Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ inventory_hostname }}" when: - not zabbix_proxy_dbhost_run_install + tags: + - database -- name: "Override delegated_dbhost with real dbhost when dbhost is behind loadbalancer" - set_fact: +- name: "MySQL | Override delegated_dbhost with real dbhost when dbhost is behind loadbalancer" + ansible.builtin.set_fact: delegated_dbhost: "{{ zabbix_proxy_real_dbhost }}" when: zabbix_proxy_real_dbhost | default(false) + tags: + - database + +- name: PyMySQL + ansible.builtin.pip: + name: PyMySQL + register: installation_dependencies + until: installation_dependencies is succeeded + tags: + - database - name: "MySQL | Create database" community.mysql.mysql_db: @@ -28,11 +42,10 @@ login_port: "{{ zabbix_proxy_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_proxy_mysql_login_unix_socket | default(omit) }}" state: present - when: zabbix_database_creation + when: zabbix_proxy_database_creation register: zabbix_database_created delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-proxy - database - skip_ansible_lint @@ -47,31 +60,22 @@ password: "{{ zabbix_proxy_dbpassword }}" priv: "{{ zabbix_proxy_dbname }}.*:ALL" host: "{{ zabbix_proxy_privileged_host }}" + plugin: "{{ 'mysql_native_password' if (ansible_os_family == 'RedHat' and ansible_distribution_major_version == '7') else omit }}" state: present - when: zabbix_database_creation + when: zabbix_proxy_database_creation delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-proxy - database -- name: "Get the file for schema.sql" - shell: ls -1 {{ datafiles_path }}/{{ 'schema' if zabbix_version is version('6.0', '<') else 'proxy' }}.sq* - changed_when: false - when: - - zabbix_database_sqlload - - zabbix_repo != "epel" - register: ls_output_create - tags: - - zabbix-proxy - - database - -- name: "Check if we have done files" - stat: +- name: "MySQL | Check if we have done files" + ansible.builtin.stat: path: /etc/zabbix/schema.done register: done_file + become: true when: - - zabbix_database_sqlload - - zabbix_repo != "epel" + - zabbix_proxy_database_sqlload + tags: + - database - name: "MySQL | Get version_comment" community.mysql.mysql_variables: @@ -84,7 +88,6 @@ delegate_to: "{{ delegated_dbhost }}" register: install_mysql_version tags: - - zabbix-proxy - database - name: "MySQL | Get current value for innodb_default_row_format" @@ -100,7 +103,6 @@ when: - install_mysql_version.msg is version('5.6', '>=') tags: - - zabbix-proxy - database - name: "MySQL | Set innodb_default_row_format to dynamic" @@ -113,15 +115,12 @@ login_port: "{{ zabbix_proxy_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_proxy_mysql_login_unix_socket | default(omit) }}" when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_proxy_database_sqlload | bool - not done_file.stat.exists - install_mysql_version.msg is version('5.6', '>=') - mysql_innodb_default_row_format.msg != 'dynamic' delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-proxy - database - name: "MySQL | Create database and import file" @@ -135,42 +134,39 @@ encoding: "{{ zabbix_proxy_dbencoding }}" collation: "{{ zabbix_proxy_dbcollation }}" state: import - target: "{{ ls_output_create.stdout }}" + target: "{{ ls_output_schema.stdout }}" when: - - zabbix_database_sqlload - - zabbix_repo != "epel" + - zabbix_proxy_database_sqlload - not done_file.stat.exists delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-proxy - database - name: "MySQL | Revert innodb_default_row_format to previous value" community.mysql.mysql_variables: variable: innodb_default_row_format - value: '{{ mysql_innodb_default_row_format.msg }}' + value: "{{ mysql_innodb_default_row_format.msg }}" login_host: "{{ zabbix_proxy_mysql_login_host | default(omit) }}" login_user: "{{ zabbix_proxy_mysql_login_user | default(omit) }}" login_password: "{{ zabbix_proxy_mysql_login_password | default(omit) }}" login_port: "{{ zabbix_proxy_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_proxy_mysql_login_unix_socket | default(omit) }}" when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_proxy_database_sqlload | bool - not done_file.stat.exists - mysql_innodb_default_row_format.msg != 'dynamic' delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-proxy - database -- name: "Create done file" - file: +- name: "MySQL | Create done file" + ansible.builtin.file: path: /etc/zabbix/schema.done state: touch - mode: '0644' + mode: "0644" + become: true when: - - zabbix_database_sqlload - - zabbix_repo != "epel" + - zabbix_proxy_database_sqlload - not done_file.stat.exists + tags: + - database diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/postgresql.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/postgresql.yml index f32618d94..e71af9aba 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/postgresql.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/postgresql.yml @@ -1,17 +1,21 @@ --- # task file for postgresql -- name: "Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" - set_fact: +- name: "PostgreSQL | Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ zabbix_proxy_dbhost if (zabbix_proxy_dbhost != 'localhost') else inventory_hostname }}" when: - zabbix_proxy_dbhost_run_install + tags: + - database -- name: "Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" - set_fact: +- name: "PostgreSQL | Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ inventory_hostname }}" when: - not zabbix_proxy_dbhost_run_install + tags: + - database - name: "PostgreSQL | Delegated" block: @@ -20,8 +24,9 @@ name: "{{ zabbix_proxy_dbname }}" port: "{{ zabbix_proxy_dbport }}" state: present + - name: "PostgreSQL | Delegated | Create database user" - postgresql_user: + community.postgresql.postgresql_user: db: "{{ zabbix_proxy_dbname }}" name: "{{ zabbix_proxy_dbuser }}" password: "{{ ('md5' + (zabbix_proxy_dbpassword + zabbix_proxy_dbuser)|hash('md5')) if zabbix_proxy_dbpassword_hash_method == 'md5' else zabbix_proxy_dbpassword }}" @@ -33,10 +38,9 @@ become_user: postgres delegate_to: "{{ delegated_dbhost }}" when: - - zabbix_database_creation + - zabbix_proxy_database_creation - zabbix_proxy_pgsql_login_host is not defined tags: - - zabbix-proxy - database - name: "PostgreSQL | Remote" @@ -51,7 +55,7 @@ port: "{{ zabbix_proxy_dbport }}" state: present - name: "PostgreSQL | Remote | Create database user" - postgresql_user: + community.postgresql.postgresql_user: login_host: "{{ zabbix_proxy_pgsql_login_host | default(omit) }}" login_user: "{{ zabbix_proxy_pgsql_login_user | default(omit) }}" login_password: "{{ zabbix_proxy_pgsql_login_password | default(omit) }}" @@ -63,30 +67,30 @@ state: present encrypted: true when: - - zabbix_database_creation + - zabbix_proxy_database_creation - zabbix_proxy_pgsql_login_host is defined tags: - - zabbix-proxy + - database + +- name: "PostgreSQL | Handle Compressed Schema File" + ansible.builtin.set_fact: + zabbix_proxy_cat_cmd: zcat + when: "'.gz' in ls_output_schema.stdout" + tags: - database - name: "PostgreSQL | Importing schema file" - shell: | + ansible.builtin.shell: | set -euxo pipefail - FILE={{ 'schema.sql' if zabbix_version is version('6.0', '<') else 'proxy.sql' }} - cd {{ datafiles_path }} - if [ -f ${FILE}.gz ] - then zcat ${FILE}.gz > /tmp/schema.sql - else - cp ${FILE} /tmp/schema.sql - fi - cat /tmp/schema.sql | psql -h '{{ zabbix_proxy_dbhost }}' -U '{{ zabbix_proxy_dbuser }}' \ - -d '{{ zabbix_proxy_dbname }}' + {{ zabbix_proxy_cat_cmd }} {{ ls_output_schema.stdout }} | psql -h '{{ zabbix_proxy_dbhost }}' -U '{{ zabbix_proxy_dbuser }}' -d '{{ zabbix_proxy_dbname }}' touch /etc/zabbix/schema.done - rm -f /tmp/schema.sql args: creates: /etc/zabbix/schema.done executable: /bin/bash environment: - PGPASSWORD: '{{ zabbix_proxy_dbpassword }}' + PGPASSWORD: "{{ zabbix_proxy_dbpassword }}" + become: true when: - - zabbix_database_creation + - zabbix_proxy_database_creation + tags: + - database diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/selinux.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/selinux.yml index 02fb4ebaf..0dca77c52 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/selinux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/selinux.yml @@ -1,11 +1,7 @@ --- - - name: "SELinux | RedHat | Install related SELinux package to fix issues" - yum: - name: - - policycoreutils-python - - libsemanage-python - - checkpolicy + ansible.builtin.yum: + name: "{{ selinux_pkgs[ansible_distribution_major_version] }}" state: present environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" @@ -13,38 +9,32 @@ register: zabbix_proxy_dependencies_installed until: zabbix_proxy_dependencies_installed is succeeded become: true - when: - - ansible_os_family == "RedHat" - - ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6" - tags: - - zabbix-proxy - -- name: "SELinux | RedHat | Install related SELinux package to fix issues on RHEL8" - yum: - name: - - policycoreutils - - checkpolicy - - python3-libsemanage - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_proxy_dependencies_installed - until: zabbix_proxy_dependencies_installed is succeeded - become: true - when: - - ansible_os_family == "RedHat" - - ansible_distribution_major_version|int >= 8 tags: - zabbix-proxy - name: "SELinux | RedHat | Add SEmodule to fix SELinux issue: zabbix_proxy_alerter.sock" - script: + ansible.builtin.script: cmd: files/install_semodule.bsx args: creates: /etc/selinux/targeted/active/modules/400/zabbix_proxy_add/cil become: true - when: - - ansible_os_family == "RedHat" tags: - zabbix-proxy + +- name: "Allow zabbix-proxy to open connections (SELinux)" + ansible.posix.seboolean: + name: zabbix_can_network + persistent: true + state: true + become: true + when: ansible_selinux.status == "enabled" + tags: selinux + +- name: "Allow zabbix-proxy to connect to zabbix_proxy_preprocessing.sock (SELinux)" + ansible.posix.seboolean: + name: daemons_enable_cluster_mode + persistent: true + state: true + become: true + when: ansible_selinux.status == "enabled" + tags: selinux diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/sqlite3.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/sqlite3.yml index 03fbf6fb3..3d74b73e7 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/sqlite3.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/tasks/sqlite3.yml @@ -2,49 +2,54 @@ # task file for sqlite3 - name: "Sqlite3 | Default Database Path" - set_fact: + ansible.builtin.set_fact: zabbix_proxy_dbname: /var/lib/zabbix/zabbix_proxy.db when: - zabbix_proxy_dbname == "zabbix_proxy" + tags: + - database - name: "Sqlite3 | Create database" - file: + ansible.builtin.file: name: "{{ zabbix_proxy_dbname | dirname }}" mode: 0744 - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" seuser: system_u serole: object_r setype: zabbix_var_lib_t state: directory become: true when: - - zabbix_database_creation + - zabbix_proxy_database_creation + tags: + - database + +- name: "Sqlite3 | Handle Compressed Schema File" + ansible.builtin.set_fact: + zabbix_proxy_cat_cmd: zcat + when: "'.gz' in ls_output_schema.stdout" + tags: + - database - name: "Sqlite3 | Importing schema file" become: true - become_user: zabbix - shell: | - set -o pipefail - FILE={{ 'schema.sql' if zabbix_version is version('6.0', '<') else 'proxy.sql' }} - cd {{ datafiles_path }} - if [ -f ${FILE}.gz ] - then zcat ${FILE}.gz > /tmp/schema.sql - else - cp ${FILE} /tmp/schema.sql - fi - cat /tmp/schema.sql | sqlite3 {{ zabbix_proxy_dbname }} - rm -f /tmp/schema.sql + become_user: "{{ zabbix_os_user }}" + ansible.builtin.shell: | + set -euxo pipefail + {{ zabbix_proxy_cat_cmd }} {{ ls_output_schema.stdout }} | sqlite3 {{ zabbix_proxy_dbname }} args: creates: "{{ zabbix_proxy_dbname }}" executable: /bin/bash environment: - PGPASSWORD: '{{ zabbix_proxy_dbpassword }}' + PGPASSWORD: "{{ zabbix_proxy_dbpassword }}" when: - - zabbix_database_creation + - zabbix_proxy_database_creation + tags: + - database -- name: "Fix zabbix db file permission (SELinux)" - file: +- name: "Sqlite3 | Fix zabbix db file permission (SELinux)" + ansible.builtin.file: path: "{{ zabbix_proxy_dbname }}" state: file seuser: system_u @@ -53,5 +58,6 @@ become: true when: - ansible_selinux.status == "enabled" - - zabbix_database_creation - tags: selinux + - zabbix_proxy_database_creation + tags: + - database diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/templates/zabbix_proxy.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_proxy/templates/zabbix_proxy.conf.j2 index b61842d12..60ae3f0a5 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/templates/zabbix_proxy.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/templates/zabbix_proxy.conf.j2 @@ -4,197 +4,116 @@ # This configuration file is "minimalized", which means all the original comments # are removed. The full documentation for your Zabbix Proxy can be found here: -# https://www.zabbix.com/documentation/{{ zabbix_version }}/en/manual/appendix/config/zabbix_proxy +# https://www.zabbix.com/documentation/{{ zabbix_proxy_version }}/en/manual/appendix/config/zabbix_proxy -ProxyMode={{ zabbix_proxy_mode }} -Server={{ zabbix_proxy_server }} -{% if zabbix_version is version('6.0', '<') %} -ServerPort={{ zabbix_proxy_serverport }} -{% endif %} -{% if zabbix_proxy_hostname is defined and zabbix_proxy_hostname %} -Hostname={{ zabbix_proxy_hostname }} -{% endif %} -{% if zabbix_proxy_hostnameitem is defined and zabbix_proxy_hostnameitem %} -HostnameItem={{ zabbix_proxy_hostnameitem }} -{% endif %} -ListenPort={{ zabbix_proxy_listenport }} -{% if zabbix_proxy_sourceip is defined and zabbix_proxy_sourceip %} -SourceIP={{ zabbix_proxy_sourceip }} -{% endif %} -{% if zabbix_version is version('6.0', '>=') %} -LogType={{ zabbix_proxy_logtype }} -{% endif %} -LogFile={{ zabbix_proxy_logfile }} -LogFileSize={{ zabbix_proxy_logfilesize }} -EnableRemoteCommands={{ zabbix_proxy_enableremotecommands }} -DebugLevel={{ zabbix_proxy_debuglevel }} -PidFile={{ zabbix_proxy_pidfile }} -{% if zabbix_version is version('3.2', '>') %} -SocketDir={{ zabbix_proxy_socketdir }} -{% endif %} -DBHost={{ zabbix_proxy_dbhost }} -DBName={{ zabbix_proxy_dbname }} -{% if zabbix_proxy_dbschema is defined and zabbix_proxy_dbschema %} -DBSchema={{ zabbix_proxy_dbschema }} -{% endif %} -DBUser={{ zabbix_proxy_dbuser }} -DBPassword={{ zabbix_proxy_dbpassword }} -DBPort={{ zabbix_proxy_dbport }} -{% if zabbix_version is version('6.0', '>=') %} -AllowUnsupportedDBVersions={{ zabbix_proxy_allowunsupporteddbversions }} -{% endif %} -ProxyLocalBuffer={{ zabbix_proxy_proxylocalbuffer }} -ProxyOfflineBuffer={{ zabbix_proxy_proxyofflinebuffer }} -{% if zabbix_version is version('6.4', '<') %} -HeartbeatFrequency={{ zabbix_proxy_heartbeatfrequency }} -{% endif %} -{% if zabbix_proxy_configfrequency is defined and zabbix_proxy_configfrequency is not none %} -{% if zabbix_version is version('6.4', '<') %} -ConfigFrequency={{ zabbix_proxy_configfrequency }} -{% else %} -ProxyConfigFrequency={{ zabbix_proxy_configfrequency }} -{% endif %} -{% else %} -{% if zabbix_version is version('6.2', '<') %} -ConfigFrequency=3600 -{% elif zabbix_version is version('6.4', '<') %} -ConfigFrequency=300 -{% else %} -ProxyConfigFrequency=10 -{% endif %} -{% endif %} -DataSenderFrequency={{ zabbix_proxy_datasenderfrequency }} -StartPollers={{ zabbix_proxy_startpollers }} -StartIPMIPollers={{ zabbix_proxy_startipmipollers }} -{% if zabbix_version is version('4.2', '>=') %} -StartPreprocessors={{ zabbix_proxy_startpreprocessors }} -{% endif %} -StartPollersUnreachable={{ zabbix_proxy_startpollersunreachable }} -StartTrappers={{ zabbix_proxy_starttrappers }} -StartPingers={{ zabbix_proxy_startpingers }} -StartDiscoverers={{ zabbix_proxy_startdiscoverers }} -StartHTTPPollers={{ zabbix_proxy_starthttppollers }} -{% if zabbix_proxy_javagateway is defined and zabbix_proxy_javagateway %} -JavaGateway={{ zabbix_proxy_javagateway }} -JavaGatewayPort={{ zabbix_proxy_javagatewayport }} -StartJavaPollers={{ zabbix_proxy_startjavapollers }} -{% endif %} -{% if zabbix_version is version_compare('2.4', '>=') %} -StartVMwareCollectors={{ zabbix_proxy_startvmwarecollector }} -VMwareFrequency={{ zabbix_proxy_vmwarefrequency }} -VMwareCacheSize={{ zabbix_proxy_vmwarecachesize -}}M -{% endif %} -SNMPTrapperFile={{ zabbix_proxy_snmptrapperfile }} -StartSNMPTrapper={{ zabbix_proxy_snmptrapper }} -{% if zabbix_proxy_listenip is defined and zabbix_proxy_listenip %} -ListenIP={{ zabbix_proxy_listenip }} -{% endif %} -HousekeepingFrequency={{ zabbix_proxy_housekeepingfrequency }} -CacheSize={{ zabbix_proxy_cachesize -}}M -StartDBSyncers={{ zabbix_proxy_startdbsyncers }} -HistoryCacheSize={{ zabbix_proxy_historycachesize -}}M -{% if zabbix_version is version_compare('3.2', '>=') %} -HistoryIndexCacheSize={{ zabbix_proxy_historyindexcachesize -}}M -{% endif %} -{% if zabbix_version is version_compare('2.4', '<') %} -HistoryTextCacheSize={{ zabbix_proxy_historytextcachesize -}}M -{% endif %} -Timeout={{ zabbix_proxy_timeout }} -TrapperTimeout={{ zabbix_proxy_trappertimeout }} -UnreachablePeriod={{ zabbix_proxy_unreachableperiod }} -UnavailableDelay={{ zabbix_proxy_unavaliabledelay }} -UnreachableDelay={{ zabbix_proxy_unreachabedelay }} -{% if zabbix_version is version_compare('6.2', '>=') %} -StartODBCPollers={{ zabbix_proxy_startodbcpollers }} -{% endif %} -ExternalScripts={{ zabbix_proxy_externalscripts }} -FpingLocation={{ zabbix_proxy_fpinglocation }} -Fping6Location={{ zabbix_proxy_fping6location }} -{% if zabbix_proxy_sshkeylocation is defined and zabbix_proxy_sshkeylocation %} -SSHKeyLocation={{ zabbix_proxy_sshkeylocation }} -{% endif %} -LogSlowQueries={{ zabbix_proxy_loglowqueries }} -TmpDir={{ zabbix_proxy_tmpdir }} -{% if zabbix_version is version_compare('2.4', '<') %} -AllowRoot={{ zabbix_proxy_allowroot }} -{% endif %} -Include={{ zabbix_proxy_include }} -{% if zabbix_version is version_compare('3.0', '<') %} -LoadModulePath={{ zabbix_proxy_loadmodulepath }} -{% endif %} -{% if zabbix_proxy_loadmodule is defined and zabbix_proxy_loadmodule %} -LoadModule={{ zabbix_proxy_loadmodule }} -{% endif %} -{% if zabbix_version is version_compare('4.0', '>=') %} -StatsAllowedIP={{ zabbix_proxy_statsallowedip }} -{% endif %} -{% if zabbix_version is version_compare('3.0', '>=') %} -{% if zabbix_proxy_tlsconnect is defined and zabbix_proxy_tlsconnect %} -TLSConnect={{ zabbix_proxy_tlsconnect }} -{% endif %} -{% if zabbix_proxy_tlsaccept is defined and zabbix_proxy_tlsaccept %} -TLSAccept={{ zabbix_proxy_tlsaccept }} -{% endif %} -{% if zabbix_proxy_tlscafile is defined and zabbix_proxy_tlscafile %} -TLSCAFile={{ zabbix_proxy_tlscafile }} -{% endif %} -{% if zabbix_proxy_tlscrlfile is defined and zabbix_proxy_tlscrlfile %} -TLSCRLFile={{ zabbix_proxy_tlscrlfile }} -{% endif %} -{% if zabbix_proxy_tlsservercertissuer is defined and zabbix_proxy_tlsservercertissuer %} -TLSServerCertIssuer={{ zabbix_proxy_tlsservercertissuer }} -{% endif %} -{% if zabbix_proxy_tlsservercertsubject is defined and zabbix_proxy_tlsservercertsubject %} -TLSServerCertSubject={{ zabbix_proxy_tlsservercertsubject }} -{% endif %} -{% if zabbix_proxy_tlscertfile is defined and zabbix_proxy_tlscertfile %} -TLSCertFile={{ zabbix_proxy_tlscertfile }} -{% endif %} -{% if zabbix_proxy_tlskeyfile is defined and zabbix_proxy_tlskeyfile %} -TLSKeyFile={{ zabbix_proxy_tlskeyfile }} -{% endif %} -{% if zabbix_proxy_tlspskidentity is defined and zabbix_proxy_tlspskidentity %} -TLSPSKIdentity={{ zabbix_proxy_tlspskidentity }} -{% endif %} -{% if zabbix_proxy_tlspskfile is defined and zabbix_proxy_tlspskfile %} -TLSPSKFile={{ zabbix_proxy_tlspskfile }} -{% endif %} -{% endif %} -{% if zabbix_proxy_dbtlsconnect is defined and zabbix_proxy_dbtlsconnect is not none %} -DBTLSConnect={{ zabbix_proxy_dbtlsconnect }} -{% endif %} -{% if zabbix_proxy_dbtlscafile is defined and zabbix_proxy_dbtlscafile is not none %} -DBTLSCAFile={{ zabbix_proxy_dbtlscafile }} -{% endif %} -{% if zabbix_proxy_dbtlscertfile is defined and zabbix_proxy_dbtlscertfile is not none %} -DBTLSCertFile={{ zabbix_proxy_dbtlscertfile }} -{% endif %} -{% if zabbix_proxy_dbtlskeyfile is defined and zabbix_proxy_dbtlskeyfile is not none %} -DBTLSKeyFile={{ zabbix_proxy_dbtlskeyfile }} -{% endif %} -{% if zabbix_proxy_dbtlscipher is defined and zabbix_proxy_dbtlscipher is not none %} -DBTLSCipher={{ zabbix_proxy_dbtlscipher }} -{% endif %} -{% if zabbix_proxy_dbtlscipher13 is defined and zabbix_proxy_dbtlscipher13 is not none %} -DBTLSCipher13={{ zabbix_proxy_dbtlscipher13 }} -{% endif %} -{% if zabbix_version is version('6.0', '>=') %} -{% if zabbix_proxy_vaulttoken is defined and zabbix_proxy_vaulttoken is not none %} -VaultToken={{ zabbix_proxy_vaulttoken }} -{% endif %} -{% if zabbix_proxy_vaulturl is defined and zabbix_proxy_vaulturl is not none %} -VaultURL={{ zabbix_proxy_vaulturl }} -{% endif %} -{% if zabbix_proxy_vaultdbpath is defined and zabbix_proxy_vaultdbpath is not none %} -VaultDBPath={{ zabbix_proxy_vaultdbpath }} -{% endif %} -{% if zabbix_proxy_vaulttlscertfile is defined and zabbix_proxy_vaulttlscertfile is not none %} -VaultTLSKeyFile={{ zabbix_proxy_vaulttlscertfile }} -{% endif %} -{% if zabbix_proxy_vaulttlskeyfile is defined and zabbix_proxy_vaulttlskeyfile is not none %} -VaultTLSCertFile={{ zabbix_proxy_vaulttlskeyfile }} -{% endif %} -{% if zabbix_proxy_listenbacklog is defined and zabbix_proxy_listenbacklog is not none %} -ListenBacklog={{ zabbix_proxy_listenbacklog }} -{% endif %} -{% endif %} +{{ (zabbix_proxy_allowroot is defined and zabbix_proxy_allowroot is not none) | ternary('','# ') }}AllowRoot={{ zabbix_proxy_allowroot | default('') }} +{% if zabbix_proxy_version is version('6.0', '>=') %} +{{ (zabbix_proxy_allowunsupporteddbversions is defined and zabbix_proxy_allowunsupporteddbversions is not none) | ternary('','# ') }}AllowUnsupportedDBVersions={{ zabbix_proxy_allowunsupporteddbversions | default('') }} +{% endif %} +{{ (zabbix_proxy_cachesize is defined and zabbix_proxy_cachesize is not none) | ternary('','# ') }}CacheSize={{ zabbix_proxy_cachesize | default('') }} +{{ (zabbix_proxy_configfrequency is defined and zabbix_proxy_configfrequency is not none) | ternary('','# ') }}ConfigFrequency={{ zabbix_proxy_configfrequency | default('') }} +{{ (zabbix_proxy_datasenderfrequency is defined and zabbix_proxy_datasenderfrequency is not none) | ternary('','# ') }}DataSenderFrequency={{ zabbix_proxy_datasenderfrequency | default('') }} +{{ (zabbix_proxy_dbhost is defined and zabbix_proxy_dbhost is not none) | ternary('','# ') }}DBHost={{ zabbix_proxy_dbhost | default('') }} +{{ (zabbix_proxy_dbname is defined and zabbix_proxy_dbname is not none) | ternary('','# ') }}DBName={{ zabbix_proxy_dbname | default('') }} +{{ (zabbix_proxy_dbpassword is defined and zabbix_proxy_dbpassword is not none) | ternary('','# ') }}DBPassword={{ zabbix_proxy_dbpassword | default('') }} +{{ (zabbix_proxy_dbschema is defined and zabbix_proxy_dbschema is not none) | ternary('','# ') }}DBSchema={{ zabbix_proxy_dbschema | default('') }} +{{ (zabbix_proxy_dbsocket is defined and zabbix_proxy_dbsocket is not none) | ternary('','# ') }}DBSocket={{ zabbix_proxy_dbsocket | default('') }} +{{ (zabbix_proxy_dbtlscafile is defined and zabbix_proxy_dbtlscafile is not none) | ternary('','# ') }}DBTLSCAFile={{ zabbix_proxy_dbtlscafile | default('') }} +{{ (zabbix_proxy_dbtlscertfile is defined and zabbix_proxy_dbtlscertfile is not none) | ternary('','# ') }}DBTLSCertFile={{ zabbix_proxy_dbtlscertfile | default('') }} +{{ (zabbix_proxy_dbtlscipher is defined and zabbix_proxy_dbtlscipher is not none) | ternary('','# ') }}DBTLSCipher={{ zabbix_proxy_dbtlscipher | default('') }} +{{ (zabbix_proxy_dbtlscipher13 is defined and zabbix_proxy_dbtlscipher13 is not none) | ternary('','# ') }}DBTLSCipher13={{ zabbix_proxy_dbtlscipher13 | default('') }} +{{ (zabbix_proxy_dbtlsconnect is defined and zabbix_proxy_dbtlsconnect is not none) | ternary('','# ') }}DBTLSConnect={{ zabbix_proxy_dbtlsconnect | default('') }} +{{ (zabbix_proxy_dbtlskeyfile is defined and zabbix_proxy_dbtlskeyfile is not none) | ternary('','# ') }}DBTLSKeyFile={{ zabbix_proxy_dbtlskeyfile | default('') }} +{{ (zabbix_proxy_dbuser is defined and zabbix_proxy_dbuser is not none) | ternary('','# ') }}DBUser={{ zabbix_proxy_dbuser | default('') }} +{{ (zabbix_proxy_debuglevel is defined and zabbix_proxy_debuglevel is not none) | ternary('','# ') }}DebugLevel={{ zabbix_proxy_debuglevel | default('') }} +{{ (zabbix_proxy_enableremotecommands is defined and zabbix_proxy_enableremotecommands is not none) | ternary('','# ') }}EnableRemoteCommands={{ zabbix_proxy_enableremotecommands | default('') }} +{{ (zabbix_proxy_externalscripts is defined and zabbix_proxy_externalscripts is not none) | ternary('','# ') }}ExternalScripts={{ zabbix_proxy_externalscripts | default('') }} +{{ (zabbix_proxy_fping6location is defined and zabbix_proxy_fping6location is not none) | ternary('','# ') }}Fping6Location={{ zabbix_proxy_fping6location | default('') }} +{{ (zabbix_proxy_fpinglocation is defined and zabbix_proxy_fpinglocation is not none) | ternary('','# ') }}FpingLocation={{ zabbix_proxy_fpinglocation | default('') }} +{% if zabbix_proxy_version is version('6.4', '<') %} +{{ (zabbix_proxy_heartbeatfrequency is defined and zabbix_proxy_heartbeatfrequency is not none) | ternary('','# ') }}HeartbeatFrequency={{ zabbix_proxy_heartbeatfrequency | default('') }} +{% endif %} +{{ (zabbix_proxy_historycachesize is defined and zabbix_proxy_historycachesize is not none) | ternary('','# ') }}HistoryCacheSize={{ zabbix_proxy_historycachesize | default('') }} +{{ (zabbix_proxy_historyindexcachesize is defined and zabbix_proxy_historyindexcachesize is not none) | ternary('','# ') }}HistoryIndexCacheSize={{ zabbix_proxy_historyindexcachesize | default('') }} +{{ (zabbix_proxy_hostname is defined and zabbix_proxy_hostname is not none) | ternary('','# ') }}Hostname={{ zabbix_proxy_hostname | default('') }} +{{ (zabbix_proxy_hostnameitem is defined and zabbix_proxy_hostnameitem is not none) | ternary('','# ') }}HostnameItem={{ zabbix_proxy_hostnameitem | default('') }} +{{ (zabbix_proxy_housekeepingfrequency is defined and zabbix_proxy_housekeepingfrequency is not none) | ternary('','# ') }}HousekeepingFrequency={{ zabbix_proxy_housekeepingfrequency | default('') }} +{{ (zabbix_proxy_include is defined and zabbix_proxy_include is not none) | ternary('','# ') }}Include={{ zabbix_proxy_include | default('') }} +{{ (zabbix_proxy_javagateway is defined and zabbix_proxy_javagateway is not none) | ternary('','# ') }}JavaGateway={{ zabbix_proxy_javagateway | default('') }} +{{ (zabbix_proxy_javagatewayport is defined and zabbix_proxy_javagatewayport is not none) | ternary('','# ') }}JavaGatewayPort={{ zabbix_proxy_javagatewayport | default('') }} +{{ (zabbix_proxy_listenbacklog is defined and zabbix_proxy_listenbacklog is not none) | ternary('','# ') }}ListenBacklog={{ zabbix_proxy_listenbacklog | default('') }} +{{ (zabbix_proxy_listenip is defined and zabbix_proxy_listenip is not none) | ternary('','# ') }}ListenIP={{ zabbix_proxy_listenip | default('') }} +{{ (zabbix_proxy_listenport is defined and zabbix_proxy_listenport is not none) | ternary('','# ') }}ListenPort={{ zabbix_proxy_listenport | default('') }} +{{ (zabbix_proxy_loadmodule is defined and zabbix_proxy_loadmodule is not none) | ternary('','# ') }}LoadModule={{ zabbix_proxy_loadmodule | default('') }} +{{ (zabbix_proxy_loadmodulepath is defined and zabbix_proxy_loadmodulepath is not none) | ternary('','# ') }}LoadModulePath={{ zabbix_proxy_loadmodulepath | default('') }} +{{ (zabbix_proxy_logfile is defined and zabbix_proxy_logfile is not none) | ternary('','# ') }}LogFile={{ zabbix_proxy_logfile | default('') }} +{{ (zabbix_proxy_logfilesize is defined and zabbix_proxy_logfilesize is not none) | ternary('','# ') }}LogFileSize={{ zabbix_proxy_logfilesize | default('') }} +{{ (zabbix_proxy_logremotecommands is defined and zabbix_proxy_logremotecommands is not none) | ternary('','# ') }}LogRemoteCommands={{ zabbix_proxy_logremotecommands | default('') }} +{{ (zabbix_proxy_logslowqueries is defined and zabbix_proxy_logslowqueries is not none) | ternary('','# ') }}LogSlowQueries={{ zabbix_proxy_logslowqueries | default('') }} +{{ (zabbix_proxy_logtype is defined and zabbix_proxy_logtype is not none) | ternary('','# ') }}LogType={{ zabbix_proxy_logtype | default('') }} +{{ (zabbix_proxy_pidfile is defined and zabbix_proxy_pidfile is not none) | ternary('','# ') }}PidFile={{ zabbix_proxy_pidfile | default('') }} +{{ (zabbix_proxy_proxylocalbuffer is defined and zabbix_proxy_proxylocalbuffer is not none) | ternary('','# ') }}ProxyLocalBuffer={{ zabbix_proxy_proxylocalbuffer | default('') }} +{{ (zabbix_proxy_proxymode is defined and zabbix_proxy_proxymode is not none) | ternary('','# ') }}ProxyMode={{ zabbix_proxy_proxymode | default('') }} +{{ (zabbix_proxy_proxyofflinebuffer is defined and zabbix_proxy_proxyofflinebuffer is not none) | ternary('','# ') }}ProxyOfflineBuffer={{ zabbix_proxy_proxyofflinebuffer | default('') }} +{{ (zabbix_proxy_server is defined and zabbix_proxy_server is not none) | ternary('','# ') }}Server={{ zabbix_proxy_server | default('') }} +{{ (zabbix_proxy_snmptrapperfile is defined and zabbix_proxy_snmptrapperfile is not none) | ternary('','# ') }}SNMPTrapperFile={{ zabbix_proxy_snmptrapperfile | default('') }} +{{ (zabbix_proxy_socketdir is defined and zabbix_proxy_socketdir is not none) | ternary('','# ') }}SocketDir={{ zabbix_proxy_socketdir | default('') }} +{{ (zabbix_proxy_sourceip is defined and zabbix_proxy_sourceip is not none) | ternary('','# ') }}SourceIP={{ zabbix_proxy_sourceip | default('') }} +{{ (zabbix_proxy_sshkeylocation is defined and zabbix_proxy_sshkeylocation is not none) | ternary('','# ') }}SSHKeyLocation={{ zabbix_proxy_sshkeylocation | default('') }} +{{ (zabbix_proxy_sslcalocation is defined and zabbix_proxy_sslcalocation is not none) | ternary('','# ') }}SSLCALocation={{ zabbix_proxy_sslcalocation | default('') }} +{{ (zabbix_proxy_sslcertlocation is defined and zabbix_proxy_sslcertlocation is not none) | ternary('','# ') }}SSLCertLocation={{ zabbix_proxy_sslcertlocation | default('') }} +{{ (zabbix_proxy_sslkeylocation is defined and zabbix_proxy_sslkeylocation is not none) | ternary('','# ') }}SSLKeyLocation={{ zabbix_proxy_sslkeylocation | default('') }} +{{ (zabbix_proxy_startdbsyncers is defined and zabbix_proxy_startdbsyncers is not none) | ternary('','# ') }}StartDBSyncers={{ zabbix_proxy_startdbsyncers | default('') }} +{{ (zabbix_proxy_startdiscoverers is defined and zabbix_proxy_startdiscoverers is not none) | ternary('','# ') }}StartDiscoverers={{ zabbix_proxy_startdiscoverers | default('') }} +{% if zabbix_proxy_version is version('6.0', '==') %} +{{ (zabbix_proxy_starthistorypollers is defined and zabbix_proxy_starthistorypollers is not none) | ternary('','# ') }}={{ zabbix_proxy_starthistorypollers | default('') }} +{% endif %} +{{ (zabbix_proxy_starthttppollers is defined and zabbix_proxy_starthttppollers is not none) | ternary('','# ') }}StartHTTPPollers={{ zabbix_proxy_starthttppollers | default('') }} +{{ (zabbix_proxy_startipmipollers is defined and zabbix_proxy_startipmipollers is not none) | ternary('','# ') }}StartIPMIPollers={{ zabbix_proxy_startipmipollers | default('') }} +{{ (zabbix_proxy_startjavapollers is defined and zabbix_proxy_startjavapollers is not none) | ternary('','# ') }}StartJavaPollers={{ zabbix_proxy_startjavapollers | default('') }} +{{ (zabbix_proxy_startodbcpollers is defined and zabbix_proxy_startodbcpollers is not none) | ternary('','# ') }}StartODBCPollers={{ zabbix_proxy_startodbcpollers | default('') }} +{{ (zabbix_proxy_startpingers is defined and zabbix_proxy_startpingers is not none) | ternary('','# ') }}StartPingers={{ zabbix_proxy_startpingers | default('') }} +{{ (zabbix_proxy_startpollers is defined and zabbix_proxy_startpollers is not none) | ternary('','# ') }}StartPollers={{ zabbix_proxy_startpollers | default('') }} +{{ (zabbix_proxy_startpollersunreachable is defined and zabbix_proxy_startpollersunreachable is not none) | ternary('','# ') }}StartPollersUnreachable={{ zabbix_proxy_startpollersunreachable | default('') }} +{{ (zabbix_proxy_startpreprocessors is defined and zabbix_proxy_startpreprocessors is not none) | ternary('','# ') }}StartPreprocessors={{ zabbix_proxy_startpreprocessors | default('') }} +{{ (zabbix_proxy_startsnmptrapper is defined and zabbix_proxy_startsnmptrapper is not none) | ternary('','# ') }}StartSNMPTrapper={{ zabbix_proxy_startsnmptrapper | default('') }} +{{ (zabbix_proxy_starttrappers is defined and zabbix_proxy_starttrappers is not none) | ternary('','# ') }}StartTrappers={{ zabbix_proxy_starttrappers | default('') }} +{{ (zabbix_proxy_startvmwarecollectors is defined and zabbix_proxy_startvmwarecollectors is not none) | ternary('','# ') }}StartVMwareCollectors={{ zabbix_proxy_startvmwarecollectors | default('') }} +{{ (zabbix_proxy_statsallowedip is defined and zabbix_proxy_statsallowedip is not none) | ternary('','# ') }}StatsAllowedIP={{ zabbix_proxy_statsallowedip | default('') }} +{{ (zabbix_proxy_timeout is defined and zabbix_proxy_timeout is not none) | ternary('','# ') }}Timeout={{ zabbix_proxy_timeout | default('') }} +{{ (zabbix_proxy_tlsaccept is defined and zabbix_proxy_tlsaccept is not none) | ternary('','# ') }}TLSAccept={{ zabbix_proxy_tlsaccept | default('') }} +{{ (zabbix_proxy_tlscafile is defined and zabbix_proxy_tlscafile is not none) | ternary('','# ') }}TLSCAFile={{ zabbix_proxy_tlscafile | default('') }} +{{ (zabbix_proxy_tlscertfile is defined and zabbix_proxy_tlscertfile is not none) | ternary('','# ') }}TLSCertFile={{ zabbix_proxy_tlscertfile | default('') }} +{{ (zabbix_proxy_tlscipherall is defined and zabbix_proxy_tlscipherall is not none) | ternary('','# ') }}TLSCipherAll={{ zabbix_proxy_tlscipherall | default('') }} +{{ (zabbix_proxy_tlscipherall13 is defined and zabbix_proxy_tlscipherall13 is not none) | ternary('','# ') }}TLSCipherAll13={{ zabbix_proxy_tlscipherall13 | default('') }} +{{ (zabbix_proxy_tlsciphercert is defined and zabbix_proxy_tlsciphercert is not none) | ternary('','# ') }}TLSCipherCert={{ zabbix_proxy_tlsciphercert | default('') }} +{{ (zabbix_proxy_tlsciphercert13 is defined and zabbix_proxy_tlsciphercert13 is not none) | ternary('','# ') }}TLSCipherCert13={{ zabbix_proxy_tlsciphercert13 | default('') }} +{{ (zabbix_proxy_tlscipherpsk is defined and zabbix_proxy_tlscipherpsk is not none) | ternary('','# ') }}TLSCipherPSK={{ zabbix_proxy_tlscipherpsk | default('') }} +{{ (zabbix_proxy_tlscipherpsk13 is defined and zabbix_proxy_tlscipherpsk13 is not none) | ternary('','# ') }}TLSCipherPSK13={{ zabbix_proxy_tlscipherpsk13 | default('') }} +{{ (zabbix_proxy_tlsconnect is defined and zabbix_proxy_tlsconnect is not none) | ternary('','# ') }}TLSConnect={{ zabbix_proxy_tlsconnect | default('') }} +{{ (zabbix_proxy_tlscrlfile is defined and zabbix_proxy_tlscrlfile is not none) | ternary('','# ') }}TLSCRLFile={{ zabbix_proxy_tlscrlfile | default('') }} +{{ (zabbix_proxy_tlskeyfile is defined and zabbix_proxy_tlskeyfile is not none) | ternary('','# ') }}TLSKeyFile={{ zabbix_proxy_tlskeyfile | default('') }} +{{ (zabbix_proxy_tlspskfile is defined and zabbix_proxy_tlspskfile is not none) | ternary('','# ') }}TLSPSKFile={{ zabbix_proxy_tlspskfile | default('') }} +{{ (zabbix_proxy_tlspskidentity is defined and zabbix_proxy_tlspskidentity is not none) | ternary('','# ') }}TLSPSKIdentity={{ zabbix_proxy_tlspskidentity | default('') }} +{{ (zabbix_proxy_tlsservercertissuer is defined and zabbix_proxy_tlsservercertissuer is not none) | ternary('','# ') }}TLSServerCertIssuer={{ zabbix_proxy_tlsservercertissuer | default('') }} +{{ (zabbix_proxy_tlsservercertsubject is defined and zabbix_proxy_tlsservercertsubject is not none) | ternary('','# ') }}TLSServerCertSubject={{ zabbix_proxy_tlsservercertsubject | default('') }} +{{ (zabbix_proxy_tmpdir is defined and zabbix_proxy_tmpdir is not none) | ternary('','# ') }}TmpDir={{ zabbix_proxy_tmpdir | default('') }} +{{ (zabbix_proxy_trappertimeout is defined and zabbix_proxy_trappertimeout is not none) | ternary('','# ') }}TrapperTimeout={{ zabbix_proxy_trappertimeout | default('') }} +{{ (zabbix_proxy_unavailabledelay is defined and zabbix_proxy_unavailabledelay is not none) | ternary('','# ') }}UnavailableDelay={{ zabbix_proxy_unavailabledelay | default('') }} +{{ (zabbix_proxy_unreachabledelay is defined and zabbix_proxy_unreachabledelay is not none) | ternary('','# ') }}UnreachableDelay={{ zabbix_proxy_unreachabledelay | default('') }} +{{ (zabbix_proxy_unreachableperiod is defined and zabbix_proxy_unreachableperiod is not none) | ternary('','# ') }}UnreachablePeriod={{ zabbix_proxy_unreachableperiod | default('') }} +{{ (zabbix_proxy_user is defined and zabbix_proxy_user is not none) | ternary('','# ') }}User={{ zabbix_proxy_user | default('') }} +{% if zabbix_proxy_version is version('6.2', '>=') %} +{{ (zabbix_proxy_vault is defined and zabbix_proxy_vault is not none) | ternary('','# ') }}Vault={{ zabbix_proxy_vault | default('') }} +{% endif %} +{{ (zabbix_proxy_vaultdbpath is defined and zabbix_proxy_vaultdbpath is not none) | ternary('','# ') }}VaultDBPath={{ zabbix_proxy_vaultdbpath | default('') }} +{% if zabbix_proxy_version is version('6.2', '>=') %} +{{ (zabbix_proxy_vaulttlscertfile is defined and zabbix_proxy_vaulttlscertfile is not none) | ternary('','# ') }}VaultTLSCertFile={{ zabbix_proxy_vaulttlscertfile | default('') }} +{{ (zabbix_proxy_vaulttlskeyfile is defined and zabbix_proxy_vaulttlskeyfile is not none) | ternary('','# ') }}VaultTLSKeyFile={{ zabbix_proxy_vaulttlskeyfile | default('') }} +{% endif %} +{{ (zabbix_proxy_vaulttoken is defined and zabbix_proxy_vaulttoken is not none) | ternary('','# ') }}VaultToken={{ zabbix_proxy_vaulttoken | default('') }} +{{ (zabbix_proxy_vaulturl is defined and zabbix_proxy_vaulturl is not none) | ternary('','# ') }}VaultURL={{ zabbix_proxy_vaulturl | default('') }} +{{ (zabbix_proxy_vmwarecachesize is defined and zabbix_proxy_vmwarecachesize is not none) | ternary('','# ') }}VMwareCacheSize={{ zabbix_proxy_vmwarecachesize | default('') }} +{{ (zabbix_proxy_vmwarefrequency is defined and zabbix_proxy_vmwarefrequency is not none) | ternary('','# ') }}VMwareFrequency={{ zabbix_proxy_vmwarefrequency | default('') }} +{{ (zabbix_proxy_vmwareperffrequency is defined and zabbix_proxy_vmwareperffrequency is not none) | ternary('','# ') }}VMwarePerfFrequency={{ zabbix_proxy_vmwareperffrequency | default('') }} +{{ (zabbix_proxy_vmwaretimeout is defined and zabbix_proxy_vmwaretimeout is not none) | ternary('','# ') }}VMwareTimeout={{ zabbix_proxy_vmwaretimeout | default('') }} diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Amazon.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Amazon.yml deleted file mode 100644 index 605be3896..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Amazon.yml +++ /dev/null @@ -1,2 +0,0 @@ ---- -ansible_distribution_major_version: "6" diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Debian.yml index 2c87e2d61..cd9527eb2 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/Debian.yml @@ -1,26 +1,57 @@ zabbix_valid_proxy_versions: # Debian + "12": + - 6.4 + - 6.0 "11": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "10": + - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 - "9": - - 4.0 - # Ubuntu "22": - 6.4 + - 6.2 - 6.0 "20": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "18": + - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 + +mysql_client_pkgs: + # Debian + "12": + - default-mysql-client + - "{{ zabbix_python_prefix }}-mysqldb" + "11": + - default-mysql-client + - "{{ zabbix_python_prefix }}-mysqldb" + "10": + - mariadb-client + - "{{ zabbix_python_prefix }}-mysqldb" + # Ubuntu + "22": + - default-mysql-client + - "{{ zabbix_python_prefix }}-mysqldb" + "20": + - default-mysql-client + - "{{ zabbix_python_prefix }}-mysqldb" + "18": + - default-mysql-client + - "{{ zabbix_python_prefix }}-mysqldb" + +mysql_plugin: + "18": mysql_native_password + "10": mysql_native_password + +debian_keyring_path: /etc/apt/keyrings/ +zabbix_gpg_key: "{{ debian_keyring_path }}/zabbix-official-repo.asc" +_zabbix_repo_deb_url: "http://repo.zabbix.com/zabbix/{{ zabbix_proxy_version }}" +_zabbix_proxy_fping6location: /usr/bin/fping6 +_zabbix_proxy_fpinglocation: /usr/bin/fping diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/RedHat.yml index 31da6800f..e8ee7e2ae 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/RedHat.yml @@ -1,12 +1,55 @@ zabbix_valid_proxy_versions: "9": - 6.4 + - 6.2 - 6.0 "8": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "7": - - 5.0 - - 4.0 + - 6.4 + - 6.2 + - 6.0 + +pgsql_depenencies: + "9": + - python3-psycopg2 + - postgresql + "8": + - python3-psycopg2 + - postgresql + "7": + - python-psycopg2 + - postgresql + +mysql_client_pkgs: + "9": + - mysql + - python3-PyMySQL + "8": + - mysql + - python3-PyMySQL + "7": + - MariaDB-client + - MySQL-python + +selinux_pkgs: + "9": + - policycoreutils + - checkpolicy + - python3-libsemanage + "8": + - policycoreutils + - checkpolicy + - python3-libsemanage + "7": + - policycoreutils-python + - libsemanage-python + - checkpolicy + +mysql_plugin: + "7": mysql_native_password + +_zabbix_proxy_fping6location: /usr/sbin/fping6 +_zabbix_proxy_fpinglocation: /usr/sbin/fping diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/main.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/main.yml index ea434bdc4..90779c270 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/main.yml @@ -1,2 +1,7 @@ --- # vars file for zabbix_proxy +db_file_path: + "62": "/usr/share/zabbix-sql-scripts/{{ zabbix_proxy_db_long }}/proxy.sql" + "64": "/usr/share/zabbix-sql-scripts/{{ zabbix_proxy_db_long }}/proxy.sql" + "60": "/usr/share/zabbix-sql-scripts/{{ zabbix_proxy_db_long }}/proxy.sql" + "50": "/usr/share/doc/zabbix-proxy-{{ zabbix_proxy_database }}*/schema.sql.gz" diff --git a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/zabbix.yml b/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/zabbix.yml deleted file mode 100644 index 7ac7dc354..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_proxy/vars/zabbix.yml +++ /dev/null @@ -1,255 +0,0 @@ ---- -sign_keys: - "64": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "62": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "60": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "54": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "52": - # bullseye: not available upstream - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "50": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "44": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "42": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "40": - bullseye: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "34": - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "32": - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - sonya: - sign_key: 79EA5ED4 - serena: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "30": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "24": - jessie: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - "22": - squeeze: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - lucid: - sign_key: 79EA5ED4 - -suse: - "openSUSE Leap": - "42": - name: server:monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_Leap_{{ ansible_distribution_version }}/ - "openSUSE": - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_{{ ansible_distribution_version }} - "SLES": - "11": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_11_SP3/ diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/README.md b/ansible_collections/community/zabbix/roles/zabbix_server/README.md index 4643fbc3f..f154f4951 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/README.md +++ b/ansible_collections/community/zabbix/roles/zabbix_server/README.md @@ -75,26 +75,16 @@ ansible-galaxy collection install community.postgresql See the following list of supported Operating systems with the Zabbix releases: -| Zabbix | 6.4 | 6.2 | 6.0 | 5.4 | 5.2 | 5.0 (LTS) | 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----|-----|-----|-----------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | | | | | | V | V | V | V | -| Red Hat Fam 6 | | | | | V | V | | | V | -| Red Hat Fam 5 | | | | | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | | V | | -| Ubuntu 18.04 bionic | | | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | | V | V | V | V | V | -| Debian 10 buster | | | V | V | V | V | V | | | -| Debian 9 stretch | | | V | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | - -See https://support.zabbix.com/browse/ZBX-18790 why RHEL7 is not supported anymore. +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | | | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | | | V | # Installation @@ -110,112 +100,48 @@ The following is an overview of all available configuration default for this rol ### Overall Zabbix -* `zabbix_server_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2, 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. +* `zabbix_server_version`: Optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_server_version: 6.0`. * `zabbix_server_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. +* `zabbix_server_disable_repo`: A list of repos to disable during install. Default `epel`. * `zabbix_service_state`: Default: `started`. Can be overridden to stopped if needed * `zabbix_service_enabled`: Default: `True` Can be overridden to `False` if needed +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_server_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### SElinux -* `zabbix_selinux`: Default: `False`. Enables an SELinux policy so that the server will run. +* `zabbix_server_selinux`: Default: `False`. Enables an SELinux policy so that the server will run. * `selinux_allow_zabbix_can_network`: Default: `False`. * `selinux_allow_zabbix_can_http`: Default: `False`. ### Zabbix Server * `zabbix_server_package_state`: Default: `present`. Can be overridden to `latest` to update packages when needed. -* `zabbix_server_listenport`: Default: `10051`. On which port the Zabbix Server is available. * `zabbix_server_install_recommends`: Default: `True`. `False` does not install the recommended packages that come with the zabbix-server install. * `zabbix_server_manage_service`: Default: `True`. When you run multiple Zabbix servers in a High Available cluster setup (e.g. pacemaker), you don't want Ansible to manage the zabbix-server service, because Pacemaker is in control of zabbix-server service and in this case, it needs to be set to `False`. -* `zabbix_proxy_startpreprocessors`: Number of pre-forked instances of preprocessing workers. The preprocessing manager process is automatically started when a preprocessor worker is started. This parameter is supported since Zabbix 4.2.0. -* `zabbix_server_username`: Default: `zabbix`. The name of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_server_userid`: The UID of the account on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_server_groupname`: Default: `zabbix`. The name of the group of the user on the host. Will only be used when `zabbix_repo: epel` is used. -* `zabbix_server_groupid`: The GID of the group on the host. Will only be used when `zabbix_repo: epel` is used. * `zabbix_server_include_mode`: Default: `0755`. The "mode" for the directory configured with `zabbix_server_include`. * `zabbix_server_conf_mode`: Default: `0640`. The "mode" for the Zabbix configuration file. -* `zabbix_server_listenbacklog`: The maximum number of pending connections in the queue. -* `zabbix_server_trendcachesize`: Size of trend cache, in bytes. -* `zabbix_server_trendfunctioncachesize`: Size of trend function cache, in bytes. -* `zabbix_server_vaulttoken`: Vault authentication token that should have been generated exclusively for Zabbix server with read only permission -* `zabbix_server_vaulturl`: Vault server HTTP[S] URL. System-wide CA certificates directory will be used if SSLCALocation is not specified. -* `zabbix_server_vaultdbpath`: Vault path from where credentials for database will be retrieved by keys 'password' and 'username'. -* `zabbix_server_startreportwriters`: Number of pre-forked report writer instances. -* `zabbix_server_webserviceurl`: URL to Zabbix web service, used to perform web related tasks. -* `zabbix_server_servicemanagersyncfrequency`: How often Zabbix will synchronize configuration of a service manager (in seconds). -* `zabbix_server_problemhousekeepingfrequency`: How often Zabbix will delete problems for deleted triggers (in seconds). -* `zabbix_server_connectors`: Number of pre-forked instances of preprocessing workers. - -### High Availability - -These variables are specific for Zabbix 6.0 and higher: - -* `zabbix_server_hanodename`: The high availability cluster node name. When empty, server is working in standalone mode; a node with empty name is registered with address for the frontend to connect to. (Default: empty) -* `zabbix_server_nodeaddress`: IP or hostname with optional port to specify how frontend should connect to the server. ### Database specific * `zabbix_server_dbhost_run_install`: Default: `True`. When set to `True`, sql files will be executed on the host running the database. * `zabbix_server_database`: Default: `pgsql`. The type of database used. Can be: `mysql` or `pgsql` -* `zabbix_server_database_long`: Default: `postgresql`. The type of database used, but long name. Can be: `mysql` or `postgresql` * `zabbix_server_dbhost`: The hostname on which the database is running. * `zabbix_server_real_dbhost`: The hostname of the dbhost that is running behind a loadbalancer/VIP (loadbalancers doesn't accept ssh connections) * `zabbix_server_dbname`: The database name which is used by the Zabbix Server. * `zabbix_server_dbuser`: The database username which is used by the Zabbix Server. * `zabbix_server_dbpassword`: The database user password which is used by the Zabbix Server. +* `zabbix_server_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. * `zabbix_server_dbport`: The database port which is used by the Zabbix Server. * `zabbix_server_dbpassword_hash_method`: Default: `md5`. Allow switching postgresql user password creation to `scram-sha-256`, when anything other than `md5` is used then ansible won't hash the password with `md5`. -* `zabbix_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. +* `zabbix_server_database_creation`: Default: `True`. When you don't want to create the database including user, you can set it to False. * `zabbix_server_install_database_client`: Default: `True`. False does not install database client. Default true -* `zabbix_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. -* `zabbix_database_timescaledb`:False / True. When you want to use timescaledb extension into the database, you can set it to True (this option only works for postgreSQL database). +* `zabbix_server_database_sqlload`:True / False. When you don't want to load the sql files into the database, you can set it to False. +* `zabbix_server_database_timescaledb`:False / True. When you want to use timescaledb extension into the database, you can set it to True (this option only works for postgreSQL database). * `zabbix_server_dbencoding`: Default: `utf8`. The encoding for the MySQL database. * `zabbix_server_dbcollation`: Default: `utf8_bin`. The collation for the MySQL database. -* `zabbix_server_allowunsupporteddbversions`: Allow server to work with unsupported database versions. - -### TLS Specific configuration - -These variables are specific for Zabbix 3.0 and higher: - -* `zabbix_server_tlsconnect`: How the agent should connect to server or proxy. Used for active checks. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_server_tlsaccept`: What incoming connections to accept. - Possible values: - * unencrypted - * psk - * cert -* `zabbix_server_tlscafile`: Full pathname of a file containing the top-level CA(s) certificates for peer certificate verification. -* `zabbix_server_tlscrlfile`: Full pathname of a file containing revoked certificates. -* `zabbix_server_tlsservercertissuer`: Allowed server certificate issuer. -* `zabbix_server_tlsservercertsubject`: Allowed server certificate subject. -* `zabbix_server_tlscertfile`: Full pathname of a file containing the agent certificate or certificate chain. -* `zabbix_server_tlskeyfile`: Full pathname of a file containing the agent private key. -* `zabbix_server_dbtlsconnect`: Setting this option enforces to use TLS connection to database: - -`required` - connect using TLS -`verify_ca` - connect using TLS and verify certificate -`verify_full` - connect using TLS, verify certificate and verify that database identity specified by DBHost matches its certificate - -On `MySQL` starting from 5.7.11 and `PostgreSQL` the following values are supported: `required`, `verify`, `verify_full`. On MariaDB starting from version 10.2.6 `required` and `verify_full` values are supported. -By default not set to any option and the behaviour depends on database configuration. -This parameter is supported since Zabbix 5.0.0. - -* `zabbix_server_dbtlscafile`: Full pathname of a file containing the top-level CA(s) certificates for database certificate verification. This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlscertfile`: Full pathname of file containing Zabbix server certificate for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlskeyfile`: Full pathname of file containing the private key for authenticating to database. This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlscipher`: The list of encryption ciphers that Zabbix server permits for TLS protocols up through TLSv1.2. Supported only for MySQL.This parameter is supported since Zabbix 5.0.0. -* `zabbix_server_dbtlscipher13`: The list of encryption ciphersuites that Zabbix server permits for TLSv1.3 protocol. Supported only for MySQL, starting from version 8.0.16. This parameter is supported since Zabbix 5.0.0. ### Custom Zabbix Scripts @@ -350,6 +276,135 @@ The `zabbix_server_privileged_host` can be set to the hostname/ip of the host ru 3. Execute the role by running the Ansible playbook that calls this role. At the end of this run, the Zabbix Server with `PgSQL` on a different host will be running. +## Configuration Variables + +The following table lists all variables that are exposed to modify the configuration of the zabbix_server.conf file. Specific details of each variable can be found in the Zabbix documentation. + +**NOTE**: Only variables with a default value appear in the defaults file, all others must be added. + +| Zabbix Name | Variable Name | Default Value |Notes | +|-----------|------------------|--------|--------| +|AlertScriptsPath | zabbix_server_alertscriptspath | /usr/lib/zabbix/alertscripts | | +|AllowRoot | zabbix_server_allowroot | 0 | | +|AllowUnsupportedDBVersions | zabbix_server_allowunsupporteddbversions |0 | | +|CacheSize | zabbix_server_cachesize | | | +|CacheUpdateFrequency | zabbix_server_cacheupdatefrequency | | | +|DBHost | zabbix_server_dbhost | localhost | | +|DBName | zabbix_server_dbname | zabbix-server | | +|DBPassword | zabbix_server_dbpassword | zabbix-server | | +|DBPort | zabbix_server_dbport | 5432 | | +|DBSchema | zabbix_server_dbschema | | | +|DBSocket | zabbix_server_dbsocket | | | +|DBTLSCAFile | zabbix_server_dbtlscafile | | | +|DBTLSCertFile | zabbix_server_dbtlscertfile | | | +|DBTLSCipher | zabbix_server_dbtlscipher | | | +|DBTLSCipher13 | zabbix_server_dbtlscipher13 | | | +|DBTLSConnect | zabbix_server_dbtlsconnect | | | +|DBTLSKeyFile | zabbix_server_dbtlskeyfile | | | +|DBUser | zabbix_server_dbuser | zabbix-server | | +|DebugLevel | zabbix_server_debuglevel | 3 | | +|ExportDir | zabbix_server_exportdir | | | +|ExportFileSize | zabbix_server_exportfilesize | 1G | | +|ExportType | zabbix_server_exporttype | | | +|ExternalScripts | zabbix_server_externalscriptspath | /usr/lib/zabbix/externalscripts | | +|Fping6Location | zabbix_server_fping6location | OS Specific Value | | +|FpingLocation | zabbix_server_fpinglocation | OS Specific Value | | +|HANodeName | zabbix_server_hanodename | | | +|HistoryCacheSize | zabbix_server_historycachesize | | | +|HistoryIndexCacheSize | zabbix_server_historyindexcachesize | | | +|HistoryStorageDateIndex | zabbix_server_historystoragedateindex | 0 | | +|HistoryStorageTypes | zabbix_server_historystoragetypes | uint,dbl,str,log,text | | +|HistoryStorageURL | zabbix_server_historystorageurl | | | +|HousekeepingFrequency | zabbix_server_housekeepingfrequency | 1 | | +|Include | zabbix_server_include | /etc/zabbix/zabbix_server.conf.d | | +|JavaGateway | zabbix_server_javagateway | | | +|JavaGatewayPort | zabbix_server_javagatewayport | 10052 | | +|ListenBacklog | zabbix_server_listenbacklog | | | +|ListenIP | zabbix_server_listenip | | | +|ListenPort | zabbix_server_listenport | 10051 | | +|LoadModule | zabbix_server_loadmodule | | | +|LoadModulePath | zabbix_server_loadmodulepath | ${libdir}/modules | | +|LogFile | zabbix_server_logfile | /var/log/zabbix/zabbix_server.log | | +|LogFileSize | zabbix_server_logfilesize | 10 | | +|LogSlowQueries | zabbix_server_logslowqueries | 0 | | +|LogType | zabbix_server_logtype | file | | +|MaxHousekeeperDelete | zabbix_server_maxhousekeeperdelete | 500 | | +|NodeAddress | zabbix_server_nodeaddress | | | +|PidFile | zabbix_server_pidfile | /var/run/zabbix/zabbix_server.pid | | +|ProxyConfigFrequency | zabbix_server_proxyconfigfrequency | | | +|ProxyDataFrequency | zabbix_server_proxydatafrequency | 1 | | +|SNMPTrapperFile | zabbix_server_snmptrapperfile | | | +|SocketDir | zabbix_server_socketdir | /var/run/zabbix | | +|SourceIP | zabbix_server_sourceip | | | +|SSHKeyLocation | zabbix_server_sshkeylocation | | | +|SSLCALocation | zabbix_server_sslcalocation | | | +|SSLCertLocation | zabbix_server_sslcertlocation | ${datadir}/zabbix/ssl/certs | | +|SSLKeyLocation | zabbix_server_sslkeylocation | ${datadir}/zabbix/ssl/keys | | +|StartAlerters | zabbix_server_startalerters | | | +|StartConnectors | zabbix_server_connectors | | Version 6.4 or later | +|StartDBSyncers | zabbix_server_startdbsyncers | 4 | | +|StartDiscoverers | zabbix_server_startdiscoverers | 1 | | +|StartEscalators | zabbix_server_startescalators | 1 | | +|StartHistoryPollers | zabbix_server_starthistorypollers | | | +|StartHTTPPollers | zabbix_server_starthttppollers | 1 | | +|StartIPMIPollers | zabbix_server_startipmipollers | 0 | | +|StartJavaPollers | zabbix_server_startjavapollers | 0 | | +|StartLLDProcessors | zabbix_server_startlldprocessors | | | +|StartODBCPollers | zabbix_server_startodbcpollers | | | +|StartPingers | zabbix_server_startpingers | 1 | | +|StartPollers | zabbix_server_startpollers | 5 | | +|StartPollersUnreachable | zabbix_server_startpollersunreachable | 1 | | +|StartPreprocessors | zabbix_server_startpreprocessors | | | +|StartProxyPollers | zabbix_server_startproxypollers | | | +|StartReportWriters | zabbix_server_startreportwriters | 0 | | +|StartSNMPTrapper | zabbix_server_startsnmptrapper | 0 | | +|StartTimers | zabbix_server_starttimers | 1 | | +|StartTrappers | zabbix_server_starttrappers | 5 | | +|StartVMwareCollectors | zabbix_server_startvmwarecollectors | 0 | | +|StasAllowedIP | zabbix_server_statsallowedip | | | +|Timeout | zabbix_server_timeout | 3 | | +|TLSCAFile | zabbix_server_tlscafile | | | +|TLSCertFile | zabbix_server_tlscertfile | | | +|TLSCipherAll | zabbix_server_tlscipherall | | | +|TLSCipherAll13 | zabbix_server_tlscipherall13 | | | +|TLSCipherCert | zabbix_server_tlsciphercert | | | +|TLSCipherCert13 | zabbix_server_tlsciphercert13 | | | +|TLSCipherPSK | zabbix_server_tlscipherpsk | | | +|TLSCipherPSK13 | zabbix_server_tlscipherpsk13 | | | +|TLSCRLFile | zabbix_server_tlscrlfile | | | +|TLSKeyFile | zabbix_server_tlskeyfile | | | +|TmpDir | zabbix_server_tmpdir | /tmp | | +|TrapperTimeout | zabbix_server_trappertimeout | 300 | | +|TrendCacheSize | zabbix_server_trendcachesize | | | +|TrendFunctionCacheSize | zabbix_server_trendfunctioncachesize | | | +|UnavailableDelay | zabbix_server_unavailabledelay | 60 | | +|UnreachableDelay | zabbix_server_unreachabledelay | 15 | | +|UnreachablePeriod | zabbix_server_unreachableperiod | 45 | | +|User | zabbix_server_user | zabbix | | +|ValueCacheSize | zabbix_server_valuecachesize | | | +|Vault | zabbix_server_vault | | Version 6.2 or later | +|VaultDBPath | zabbix_server_vaultdbpath | | | +|VaultTLSKeyFile | zabbix_server_vaulttlskeyfile | | Version 6.2 or later | +|VaultTLSCertFile | zabbix_server_vaulttlscertfile | | Version 6.2 or later | +|VaultToken | zabbix_server_vaulttoken | | | +|VaultURL | zabbix_server_vaulturl | https://127.0.0.1:8200 | | +|VMwareCacheSize | zabbix_server_vmwarecachesize | | | +|VMwareFrequency | zabbix_server_vmwarefrequency | 60 | | +|VMwarePerfFrequency | zabbix_server_vmwareperffrequency | 60 | | +|VMwareTimeout | zabbix_server_vmwaretimeout | 10 | | +|WebServiceURL | zabbix_server_webserviceurl | | | + +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Example Playbook Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/defaults/main.yml b/ansible_collections/community/zabbix/roles/zabbix_server/defaults/main.yml index e9b837c99..6aec202dd 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/defaults/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/defaults/main.yml @@ -1,28 +1,52 @@ --- # defaults file for zabbix_server +# zabbix_server_version: +zabbix_os_user: zabbix +zabbix_service_enabled: true +zabbix_server_manage_service: true -# zabbix_server_version: 6.0 -zabbix_server_version_minor: "*" -zabbix_version: "{{ zabbix_server_version }}" -zabbix_repo: zabbix - -zabbix_server_apt_priority: -zabbix_server_package_state: present -zabbix_server_install_recommends: true +# Database +zabbix_server_database_sqlload: true +zabbix_server_database_timescaledb: false +zabbix_server_real_dbhost: +zabbix_server_dbhost: localhost +zabbix_server_dbname: zabbix-server +zabbix_server_privileged_host: localhost +zabbix_server_dbencoding: utf8 +zabbix_server_dbcollation: utf8_bin +zabbix_server_dbschema: +zabbix_server_dbuser: zabbix-server +zabbix_server_dbpassword: zabbix-server +zabbix_server_dbpassword_hash_method: md5 +zabbix_server_dbsocket: +zabbix_server_dbport: 5432 +zabbix_server_dbhost_run_install: true +zabbix_server_database: pgsql +zabbix_server_database_creation: true zabbix_server_install_database_client: true -zabbix_server_conf_mode: 0640 +# SELinux specific +zabbix_server_selinux: false +selinux_allow_zabbix_can_network: false +selinux_allow_zabbix_can_http: false + +#Misc. +zabbix_server_include_mode: "0755" +zabbix_server_config: /etc/zabbix/zabbix_server.conf zabbix_service_state: started -zabbix_service_enabled: true +# Yum/APT Variables +zabbix_server_version_minor: "*" +zabbix_server_package_state: present zabbix_repo_yum_gpgcheck: 0 zabbix_repo_yum_schema: https -zabbix_repo_yum_disabled: "*" -zabbix_repo_yum_enabled: [] +zabbix_repo_deb_component: main +zabbix_server_disable_repo: + - epel zabbix_repo_yum: - name: zabbix description: Zabbix Official Repository - $basearch - baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/" + baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_server_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/" gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" mode: "0644" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX @@ -34,128 +58,58 @@ zabbix_repo_yum: gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX state: present +zabbix_server_apt_priority: +zabbix_server_install_recommends: true +zabbix_server_conf_mode: 0640 -# User (EPEL specific) -zabbix_server_username: zabbix -zabbix_server_groupname: zabbix - -# Database -zabbix_server_database: pgsql -zabbix_server_database_long: postgresql -zabbix_database_creation: true -zabbix_database_sqlload: true -zabbix_database_timescaledb: false -zabbix_server_dbtlsconnect: -zabbix_server_dbtlscafile: -zabbix_server_dbtlscertfile: -zabbix_server_dbtlskeyfile: -zabbix_server_dbtlscipher: -zabbix_server_dbtlscipher13: - -# zabbix-server specific vars +# Server Configuration Variables (Only ones with role provided defaults) +zabbix_server_alertscriptspath: /usr/lib/zabbix/alertscripts +zabbix_server_allowroot: 0 +zabbix_server_allowunsupporteddbversions: 0 +zabbix_server_debuglevel: 3 +zabbix_server_exportfilesize: 1G +zabbix_server_externalscriptspath: /usr/lib/zabbix/externalscripts +zabbix_server_historystoragedateindex: 0 +zabbix_server_historystoragetypes: uint,dbl,str,log,text +zabbix_server_housekeepingfrequency: 1 +zabbix_server_include: /etc/zabbix/zabbix_server.conf.d +zabbix_server_javagatewayport: 10052 zabbix_server_listenport: 10051 -zabbix_server_sourceip: -zabbix_server_logtype: file +zabbix_server_loadmodulepath: ${libdir}/modules zabbix_server_logfile: /var/log/zabbix/zabbix_server.log zabbix_server_logfilesize: 10 -zabbix_server_debuglevel: 3 +zabbix_server_logslowqueries: 0 +zabbix_server_logtype: file +zabbix_server_maxhousekeeperdelete: 500 zabbix_server_pidfile: /var/run/zabbix/zabbix_server.pid +zabbix_server_proxydatafrequency: 1 +zabbix_server_snmptrapperfile: /tmp/zabbix_traps.tmp zabbix_server_socketdir: /var/run/zabbix -zabbix_server_real_dbhost: -zabbix_server_dbhost: localhost -zabbix_server_dbname: zabbix-server -zabbix_server_dbencoding: utf8 -zabbix_server_dbcollation: utf8_bin -zabbix_server_dbschema: -zabbix_server_dbuser: zabbix-server -zabbix_server_dbpassword: zabbix-server -zabbix_server_dbsocket: -zabbix_server_dbport: 5432 -zabbix_server_dbhost_run_install: true -zabbix_server_dbpassword_hash_method: md5 -zabbix_server_allowunsupporteddbversions: 0 -zabbix_server_privileged_host: localhost -zabbix_server_historystorageurl: -zabbix_server_historystoragetypes: uint,dbl,str,log,text -zabbix_server_historystoragedateindex: 0 -zabbix_server_exportdir: -zabbix_server_exportfilesize: 1G -zabbix_server_startpollers: 5 -zabbix_server_startlldprocessors: 2 -zabbix_server_startipmipollers: 0 -zabbix_server_startpollersunreachable: 1 -zabbix_server_starttrappers: 5 -zabbix_server_startpingers: 1 +zabbix_server_sslcertlocation: ${datadir}/zabbix/ssl/certs +zabbix_server_sslkeylocation: ${datadir}/zabbix/ssl/keys +zabbix_server_startdbsyncers: 4 zabbix_server_startdiscoverers: 1 +zabbix_server_startescalators: 1 zabbix_server_starthttppollers: 1 -zabbix_server_startpreprocessors: 3 -zabbix_server_connectors: 0 -zabbix_server_startodbcpollers: 1 +zabbix_server_startipmipollers: 0 +zabbix_server_startjavapollers: 0 +zabbix_server_startpingers: 1 +zabbix_server_startpollers: 5 +zabbix_server_startpollersunreachable: 1 +zabbix_server_startproxypollers: 1 +zabbix_server_startreportwriters: 0 +zabbix_server_startsnmptrapper: 0 zabbix_server_starttimers: 1 -zabbix_server_starthistorypollers: 5 -zabbix_server_javagateway: -zabbix_server_javagatewayport: 10052 -zabbix_server_startjavapollers: 5 +zabbix_server_starttrappers: 5 zabbix_server_startvmwarecollectors: 0 -zabbix_server_vmwarefrequency: 60 -zabbix_server_vmwarecachesize: 8M -zabbix_server_snmptrapperfile: /tmp/zabbix_traps.tmp -zabbix_server_startsnmptrapper: 0 -zabbix_server_listenip: -zabbix_server_housekeepingfrequency: 1 -zabbix_server_maxhousekeeperdelete: 500 -zabbix_server_senderfrequency: 30 -zabbix_server_cachesize: 32M -zabbix_server_startdbsyncers: 4 -zabbix_server_historycachesize: 16M -zabbix_server_historyindexcachesize: 4M -zabbix_server_trendcachesize: 4M -zabbix_server_trendfunctioncachesize: 4M -zabbix_server_historytextcachesize: 16M -zabbix_server_valuecachesize: 8M -zabbix_server_nodenoevents: 0 -zabbix_server_nodenohistory: 0 zabbix_server_timeout: 3 +zabbix_server_tmpdir: /tmp zabbix_server_trappertimeout: 300 -zabbix_server_unreachableperiod: 45 zabbix_server_unavailabledelay: 60 zabbix_server_unreachabledelay: 15 -zabbix_server_alertscriptspath: /usr/lib/zabbix/alertscripts -zabbix_server_externalscriptspath: /usr/lib/zabbix/externalscripts -zabbix_server_sshkeylocation: -zabbix_server_logslowqueries: 0 -zabbix_server_tmpdir: /tmp -zabbix_server_startproxypollers: 1 -zabbix_server_proxydatafrequency: 1 -zabbix_server_allowroot: 0 +zabbix_server_unreachableperiod: 45 zabbix_server_user: zabbix -zabbix_server_include: /etc/zabbix/zabbix_server.conf.d -zabbix_server_include_mode: "0755" -zabbix_server_sslcertlocation: ${datadir}/zabbix/ssl/certs -zabbix_server_sslkeylocation: ${datadir}/zabbix/ssl/keys -zabbix_server_sslcalocation: -zabbix_server_loadmodulepath: ${libdir}/modules -zabbix_server_loadmodule: -zabbix_server_tlscafile: -zabbix_server_tlscrlfile: -zabbix_server_tlscertfile: -zabbix_server_tlskeyfile: -zabbix_server_startescalators: 1 +zabbix_server_vaulturl: https://127.0.0.1:8200 +zabbix_server_vmwarefrequency: 60 zabbix_server_vmwareperffrequency: 60 zabbix_server_vmwaretimeout: 10 -zabbix_server_manage_service: true -zabbix_server_vaulttoken: -zabbix_server_vaulturl: https://127.0.0.1:8200 -zabbix_server_vaultdbpath: -zabbix_server_startreportwriters: 0 -zabbix_server_webserviceurl: -zabbix_server_servicemanagersyncfrequency: 60 -zabbix_server_problemhousekeepingfrequency: 60 -zabbix_server_listenbacklog: -zabbix_server_hanodename: -zabbix_server_nodeaddress: - -# SELinux specific -zabbix_selinux: false -selinux_allow_zabbix_can_network: false -selinux_allow_zabbix_can_http: false diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/handlers/main.yml b/ansible_collections/community/zabbix/roles/zabbix_server/handlers/main.yml index 74b15bdc5..b0e272e2d 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/handlers/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/handlers/main.yml @@ -2,7 +2,7 @@ # handlers file for wdijkerman.zabbix - name: zabbix-server restarted - service: + ansible.builtin.service: name: zabbix-server state: restarted enabled: true @@ -10,20 +10,9 @@ become: true when: - zabbix_server_manage_service | bool - - zabbix_repo != 'epel' - -- name: zabbix-server restarted - service: - name: zabbix-proxy-mysql{{ zabbix_proxy_database_long }} - state: restarted - enabled: true - become: true - when: - - zabbix_proxy_manage_service | bool - - zabbix_repo == 'epel' - name: "clean repo files from proxy creds" - shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true + ansible.builtin.shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true become: true when: - ansible_os_family == 'RedHat' diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/Debian.yml index d7d9a08e3..ccfe6f121 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/Debian.yml @@ -1,76 +1,47 @@ --- - -- name: "Include Zabbix gpg ids" - include_vars: zabbix.yml - -- name: "Set some variables" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - zabbix_server_apt_repository: - - "http://repo.zabbix.com/zabbix/{{ zabbix_version }}/{{ ansible_distribution.lower() }}/" - - "{{ ansible_distribution_release }}" - - "main" - zabbix_underscore_version: "{{ zabbix_version | regex_replace('\\.', '_') }}" - zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" - when: - - ansible_machine != "aarch64" - -- name: "Set some variables" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - zabbix_server_apt_repository: - - "http://repo.zabbix.com/zabbix/{{ zabbix_version }}/{{ ansible_distribution.lower() }}-arm64/" - - "{{ ansible_distribution_release }}" - - "main" - zabbix_underscore_version: "{{ zabbix_version | regex_replace('\\.', '_') }}" +- name: "Debian | Set some variables" + ansible.builtin.set_fact: + zabbix_short_version: "{{ zabbix_server_version | regex_replace('\\.', '') }}" + zabbix_underscore_version: "{{ zabbix_server_version | regex_replace('\\.', '_') }}" zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" - when: - - ansible_machine == "aarch64" - - -- name: "Debian | Set some facts" - set_fact: - datafiles_path: /usr/share/zabbix-server-{{ zabbix_server_database }} - when: - - zabbix_version is version('3.0', '<') tags: - - zabbix-server - - init - - config + - always -- name: "Debian | Set some facts for Zabbix >= 3.0 && < 5.4" - set_fact: - datafiles_path: /usr/share/doc/zabbix-server-{{ zabbix_server_database }} - when: - - zabbix_version is version('3.0', '>=') - - zabbix_version is version('5.4', '<') +- name: "Debian | Installing lsb-release" + ansible.builtin.apt: + pkg: lsb-release + update_cache: true + cache_valid_time: 3600 + force: true + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + become: true tags: - - zabbix-server - - init - - config + - install -- name: "Debian | Set some facts for Zabbix == 5.4" - set_fact: - datafiles_path: /usr/share/doc/zabbix-sql-scripts/{{ zabbix_server_database_long }} +- name: "Debian | Update ansible_lsb fact" + ansible.builtin.setup: + gather_subset: + - lsb + +- name: "Debian | Repo URL" + ansible.builtin.set_fact: + zabbix_repo_deb_url: "{{ _zabbix_repo_deb_url }}/{{ ansible_lsb.id.lower() }}{{ '-arm64' if ansible_machine == 'aarch64' and ansible_lsb.id == 'debian' else ''}}" when: - - zabbix_version is version('5.4', '==') + - zabbix_repo_deb_url is undefined tags: - - zabbix-server - - init - - config + - always -- name: "Debian | Set some facts for Zabbix >= 6.0" - set_fact: - datafiles_path: /usr/share/zabbix-sql-scripts/{{ zabbix_server_database_long }} - when: - - zabbix_version is version('6.0', '>=') +- name: "Debian | Set some facts for Zabbix" + ansible.builtin.set_fact: + datafiles_path: /usr/share/zabbix-sql-scripts/{{ 'postgresql' if zabbix_server_database == 'pgsql' else 'mysql' }} tags: - - zabbix-server - - init - - config + - always - name: "Debian | Installing gnupg" - apt: + ansible.builtin.apt: pkg: gnupg update_cache: true cache_valid_time: 3600 @@ -82,90 +53,104 @@ register: gnupg_installed until: gnupg_installed is succeeded become: true + tags: + - install + +# In releases older than Debian 12 and Ubuntu 22.04, /etc/apt/keyrings does not exist by default. +# It SHOULD be created with permissions 0755 if it is needed and does not already exist. +# See: https://wiki.debian.org/DebianRepository/UseThirdParty +- name: "Debian | Create /etc/apt/keyrings/ on older versions" + ansible.builtin.file: + path: /etc/apt/keyrings/ + state: directory + mode: "0755" + become: true + when: + - (ansible_distribution == "Ubuntu" and ansible_distribution_major_version < "22") or + (ansible_distribution == "Debian" and ansible_distribution_major_version < "12") -- name: "Debian | Install gpg key" - apt_key: - id: "{{ sign_keys[zabbix_short_version][ansible_distribution_release]['sign_key'] }}" +- name: "Debian | Download gpg key" + ansible.builtin.get_url: url: http://repo.zabbix.com/zabbix-official-repo.key + dest: "{{ zabbix_gpg_key }}" + mode: "0644" + force: true register: zabbix_server_repo_files_installed until: zabbix_server_repo_files_installed is succeeded - when: - - zabbix_repo == "zabbix" become: true tags: - - zabbix-server - - init + - install - name: "Debian | Installing repository {{ ansible_distribution }}" - apt_repository: - repo: "{{ item }} {{ zabbix_server_apt_repository | join(' ') }}" - state: present - when: zabbix_repo == "zabbix" + ansible.builtin.copy: + dest: /etc/apt/sources.list.d/zabbix.sources + owner: root + group: root + mode: 0644 + content: | + Types: deb deb-src + Enabled: yes + URIs: {{ zabbix_repo_deb_url }} + Suites: {{ ansible_distribution_release }} + Components: {{ zabbix_repo_deb_component }} + Architectures: {{ 'amd64' if ansible_machine != 'aarch64' else 'arm64'}} + Signed-By: {{ zabbix_gpg_key }} become: true - with_items: - - deb-src - - deb tags: - - zabbix-server - - init + - install - name: "Debian | Create /etc/apt/preferences.d/" - file: + ansible.builtin.file: path: /etc/apt/preferences.d/ state: directory - mode: '0755' + mode: "0755" when: - zabbix_server_apt_priority | int become: true + tags: + - install - name: "Debian | Configuring the weight for APT" - copy: + ansible.builtin.copy: dest: "/etc/apt/preferences.d/zabbix_server-{{ zabbix_proxy_database }}" content: | Package: zabbix_server-{{ zabbix_proxy_database }} Pin: origin repo.zabbix.com Pin-Priority: {{ zabbix_server_apt_priority }} owner: root - mode: '0644' + mode: "0644" when: - zabbix_server_apt_priority | int become: true - -- name: Check if warn parameter can be used for shell module - set_fact: - produce_warn: False - when: ansible_version.full is version("2.14", "<") - -- name: apt-get clean - shell: apt-get clean; apt-get update - args: - warn: "{{ produce_warn | default(omit) }}" - changed_when: false - become: true tags: - - skip_ansible_lint + - install # On certain 18.04 images, such as docker or lxc, dpkg is configured not to # install files into paths /usr/share/doc/* # Since this is where Zabbix installs its database schemas, we need to allow # files to be installed to /usr/share/doc/zabbix* -- name: Check for the dpkg exclude line - command: grep -F 'path-exclude=/usr/share/doc/*' /etc/dpkg/dpkg.cfg.d/excludes +- name: "Debian | Check for the dpkg exclude line" + ansible.builtin.command: grep -F 'path-exclude=/usr/share/doc/*' /etc/dpkg/dpkg.cfg.d/excludes register: dpkg_exclude_line failed_when: false changed_when: false check_mode: false + become: true + tags: + - install -- name: Allow Zabbix dpkg installs to /usr/share/doc/zabbix* - lineinfile: +- name: "Debian | Allow Zabbix dpkg installs to /usr/share/doc/zabbix*" + ansible.builtin.lineinfile: path: /etc/dpkg/dpkg.cfg.d/excludes - line: 'path-include=/usr/share/doc/zabbix*' + line: "path-include=/usr/share/doc/zabbix*" become: true when: - dpkg_exclude_line.rc == 0 + tags: + - install - name: "Debian | Installing zabbix-server-{{ zabbix_server_database }}" - apt: + ansible.builtin.apt: pkg: zabbix-server-{{ zabbix_server_database }} state: "{{ zabbix_server_package_state }}" update_cache: true @@ -179,11 +164,10 @@ until: zabbix_server_package_installed is succeeded become: true tags: - - zabbix-server - - init + - install - name: "Debian | Installing zabbix-sql-scripts" - apt: + ansible.builtin.apt: pkg: zabbix-sql-scripts state: "{{ zabbix_server_package_state }}" update_cache: true @@ -196,84 +180,61 @@ register: zabbix_server_package_sql_installed until: zabbix_server_package_sql_installed is succeeded when: - - zabbix_version is version('5.4', '>=') - become: true - tags: - - zabbix-server - - init - -- name: "Debian | Install Ansible module dependencies" - apt: - name: "{{ zabbix_python_prefix }}-psycopg2" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_database_creation - tags: - - zabbix-server - - init - -- name: "Debian | Install Mysql Client package" - apt: - name: - - default-mysql-client - - "{{ zabbix_python_prefix }}-mysqldb" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded + - zabbix_server_version is version('5.4', '>=') become: true - when: - - zabbix_server_database == 'mysql' - - zabbix_server_install_database_client - - ansible_distribution_release != "buster" tags: - - zabbix-server - - init - - database - -- name: "Debian 10 | Install Mysql Client package" - apt: - name: - - mariadb-client - - "{{ zabbix_python_prefix }}-mysqldb" - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_server_database == 'mysql' - - zabbix_server_install_database_client - - ansible_distribution_release == "buster" - tags: - - zabbix-server - - init - - database - -- name: "Debian | Install PostgreSQL Client package" - apt: - name: postgresql-client - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_server_database == 'pgsql' - - zabbix_server_install_database_client + - install + +- name: "Debian | Install Database Client Package" + block: + - name: "Debian | Install Mysql Client package" + ansible.builtin.apt: + name: + - default-mysql-client + - "{{ zabbix_python_prefix }}-mysqldb" + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_server_dependencies_installed + until: zabbix_server_dependencies_installed is succeeded + become: true + when: + - zabbix_server_database == 'mysql' + - ansible_distribution_release != "buster" + + - name: "Debian 10 | Install Mysql Client package" + ansible.builtin.apt: + name: + - mariadb-client + - "{{ zabbix_python_prefix }}-mysqldb" + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_server_dependencies_installed + until: zabbix_server_dependencies_installed is succeeded + become: true + when: + - zabbix_server_database == 'mysql' + - ansible_distribution_release == "buster" + + - name: "Debian | Install PostgreSQL Client package" + ansible.builtin.apt: + name: + - postgresql-client + - "{{ zabbix_python_prefix }}-psycopg2" + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_server_dependencies_installed + until: zabbix_server_dependencies_installed is succeeded + become: true + when: + - zabbix_server_database == 'pgsql' + when: zabbix_server_install_database_client tags: - - zabbix-server - - init + - install - database + - dependencies diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/RedHat.yml index 5d6c33b31..fefd7e86c 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/RedHat.yml @@ -1,191 +1,84 @@ --- # Tasks specific for RedHat systems -- name: "Set short version name" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" +- name: "RedHat | Set short version name" + ansible.builtin.set_fact: + zabbix_short_version: "{{ zabbix_server_version | regex_replace('\\.', '') }}" + tags: + - always - name: "RedHat | Use Zabbix package name" - set_fact: + ansible.builtin.set_fact: zabbix_server_package: "zabbix-server-{{ zabbix_server_database }}" - when: - - zabbix_repo == "zabbix" or zabbix_repo == "other" - tags: - - zabbix-server - -- name: "RedHat | Use EPEL package name" - set_fact: - zabbix_server_package: "zabbix{{ zabbix_short_version }}-server-{{ zabbix_server_database }}" - when: - - zabbix_repo == "epel" - tags: - - zabbix-server - -- name: "RedHat | Set some facts Zabbix <= 3.2" - set_fact: - datafiles_path: "/usr/share/doc/zabbix-server-{{ zabbix_server_database }}-{{ zabbix_version }}*" - when: - - zabbix_version is version('3.2', '<=') tags: - - zabbix-server + - always -- name: "RedHat | Set facts for Zabbix > 3.2 && < 5.4" - set_fact: - datafiles_path: "/usr/share/doc/zabbix-server-{{ zabbix_server_database }}*" - when: - - zabbix_version is version('3.2', '>') - - zabbix_version is version('5.4', '<') +- name: "RedHat | Set facts for Zabbix" + ansible.builtin.set_fact: + datafiles_path: "/usr/share/zabbix-sql-scripts/{{ 'postgresql' if zabbix_server_database == 'pgsql' else 'mysql' }}" tags: - - zabbix-server + - always -- name: "RedHat | Set facts for Zabbix == 5.4" - set_fact: - datafiles_path: "/usr/share/doc/zabbix-sql-scripts/{{ zabbix_server_database_long }}" - when: - - zabbix_version is version('5.4', '==') - tags: - - zabbix-server - -- name: "RedHat | Set facts for Zabbix >= 6.0" - set_fact: - datafiles_path: "/usr/share/zabbix-sql-scripts/{{ zabbix_server_database_long }}" - when: - - zabbix_version is version('6.0', '>=') - tags: - - zabbix-server - -- name: "RedHat | Set facts for RHEL8" - set_fact: - datafiles_path: "/usr/share/doc/zabbix-server-{{ zabbix_server_database }}" - when: - - ansible_distribution_major_version == "8" - - zabbix_version is version('5.4', '<') - tags: - - zabbix-server - -- name: "RedHat | Set some facts EPEL" - set_fact: - datafiles_path: "/usr/share/zabbix-{{ zabbix_server_database_long }}" - when: - - zabbix_repo == "epel" - tags: - - zabbix-server - -- name: "RedHat | Create 'zabbix' group (EPEL)" - group: - name: "{{ zabbix_server_groupname | default('zabbix') }}" - gid: "{{ zabbix_server_groupid | default(omit) }}" - state: present - become: true - when: - - zabbix_repo == "epel" - -- name: "RedHat | Create 'zabbix' user (EPEL)" - user: - name: "{{ zabbix_server_username | default('zabbix') }}" - comment: Zabbix Monitoring System - uid: "{{ zabbix_server_userid | default(omit) }}" - group: zabbix - become: true - when: - - zabbix_repo == "epel" - -- name: "Make sure old file is absent" - file: +- name: "RedHat | Make sure old file is absent" + ansible.builtin.file: path: /etc/yum.repos.d/zabbix-supported.repo state: absent become: true + tags: + - install - name: "RedHat | Install basic repo file" - yum_repository: + ansible.builtin.yum_repository: name: "{{ item.name }}" description: "{{ item.description }}" baseurl: "{{ item.baseurl }}" gpgcheck: "{{ item.gpgcheck }}" gpgkey: "{{ item.gpgkey }}" mode: "{{ item.mode | default('0644') }}" - priority: "{{ item.priority | default('98') }}" + priority: "{{ item.priority | default('99') }}" state: "{{ item.state | default('present') }}" proxy: "{{ zabbix_http_proxy | default(omit) }}" with_items: "{{ zabbix_repo_yum }}" register: yum_repo_installed become: true - when: - zabbix_repo == "zabbix" notify: - "clean repo files from proxy creds" tags: - - zabbix-server + - install - name: "RedHat | Installing zabbix-server-{{ zabbix_server_database }}" - package: + ansible.builtin.package: pkg: "{{ zabbix_server_package }}-{{ zabbix_server_version }}.{{ zabbix_server_version_minor }}" state: "{{ zabbix_server_package_state }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_server_disable_repo | default(omit) }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" register: zabbix_server_package_installed until: zabbix_server_package_installed is succeeded - when: - zabbix_repo != "other" become: true tags: - - zabbix-server - -- name: "RedHat | Installing zabbix-server-{{ zabbix_server_database }} (When zabbix_repo == other)" - package: - pkg: "{{ zabbix_server_package }}-{{ zabbix_server_version }}.{{ zabbix_server_version_minor }}" - state: "{{ zabbix_server_package_state }}" - register: zabbix_server_package_installed - until: zabbix_server_package_installed is succeeded - when: - zabbix_repo == "other" - become: true - tags: - - zabbix-server + - install - name: "RedHat | Installing zabbix-sql-scripts" - package: - pkg: "zabbix-sql-scripts-{{ zabbix_server_version }}.{{ zabbix_server_version_minor }}" - state: "{{ zabbix_server_package_state }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_sql_package_installed - until: zabbix_server_sql_package_installed is succeeded - when: - - zabbix_version is version('5.4', '>=') - - zabbix_repo != "other" - become: true - tags: - - zabbix-server - - -- name: "RedHat | Installing zabbix-sql-scripts (When zabbix_repo == other)" - package: + ansible.builtin.package: pkg: "zabbix-sql-scripts-{{ zabbix_server_version }}.{{ zabbix_server_version_minor }}" state: "{{ zabbix_server_package_state }}" - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_server_disable_repo | default(omit) }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" register: zabbix_server_sql_package_installed until: zabbix_server_sql_package_installed is succeeded when: - - zabbix_version is version('5.4', '>=') - - zabbix_repo == "other" + - zabbix_server_version is version('6.0', '>=') become: true tags: - - zabbix-server + - install - name: "RedHat | Install Ansible module dependencies" - yum: - name: python-psycopg2 + ansible.builtin.yum: + name: "{{ pgsql_depenencies[ansible_distribution_major_version] }}" state: present environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" @@ -194,103 +87,46 @@ until: zabbix_server_dependencies_installed is succeeded become: true when: - - zabbix_database_creation + - zabbix_server_database_creation - zabbix_server_database == 'pgsql' - - ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6" tags: - - zabbix-server - -- name: "RedHat | Install Ansible module dependencies on RHEL9 or RHEL8" - yum: - name: python3-psycopg2 - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_database_creation - - zabbix_server_database == 'pgsql' - - ansible_distribution_major_version|int >= 8 - tags: - - zabbix-server - -- name: "RedHat | Install Mysql Client packages RHEL9 or RHEL8" - yum: - name: - - mysql - - python3-PyMySQL - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_server_database == 'mysql' - - zabbix_server_install_database_client - - ansible_distribution_major_version|int >= 8 - tags: - - zabbix-server - -- name: "RedHat | Install Mysql Client package RHEL7" - yum: - name: - - mariadb - - MySQL-python - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_server_database == 'mysql' - - zabbix_server_install_database_client - - ansible_distribution_major_version == "7" - tags: - - zabbix-server - -- name: "RedHat | Install Mysql Client package RHEL5 - 6" - yum: - name: - - mysql - - MySQL-python - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_server_database == 'mysql' - - zabbix_server_install_database_client - - ansible_distribution_major_version == "6" or ansible_distribution_major_version == "5" - tags: - - zabbix-server - -- name: "RedHat | Install PostgreSQL client package" - yum: - name: postgresql - state: present - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_server_dependencies_installed - until: zabbix_server_dependencies_installed is succeeded - become: true - when: - - zabbix_server_database == 'pgsql' - - zabbix_server_install_database_client - tags: - - zabbix-server - -- name: "Configure SELinux when enabled" - include_tasks: selinux.yml - when: - - zabbix_selinux | bool + - install + - dependencies + +- name: RedHat | Install Database Client Package + block: + - name: "RedHat | Install Mysql Client packages" + ansible.builtin.yum: + name: "{{ mysql_client_pkgs[ansible_distribution_major_version] }}" + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_server_dependencies_installed + until: zabbix_server_dependencies_installed is succeeded + become: true + when: + - zabbix_server_database == 'mysql' + + - name: "RedHat | Install PostgreSQL client package" + ansible.builtin.yum: + name: postgresql + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_server_dependencies_installed + until: zabbix_server_dependencies_installed is succeeded + become: true + when: + - zabbix_server_database == 'pgsql' + when: zabbix_server_install_database_client + tags: + - install + - dependencies + - database + +- name: "RedHat | Configure SELinux when enabled" + ansible.builtin.include_tasks: selinux.yml + when: + - zabbix_server_selinux | bool diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/main.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/main.yml index d3264883d..62674a7ff 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/main.yml @@ -1,56 +1,74 @@ --- -# tasks file for wdijkerman.zabbix - -- name: "Include OS-specific variables" - include_vars: "{{ ansible_os_family }}.yml" +- name: Include OS-specific variables + ansible.builtin.include_vars: "{{ ansible_os_family }}.yml" + tags: + - always - name: Determine Latest Supported Zabbix Version - set_fact: - zabbix_server_version: "{{ zabbix_valid_server_versions[ansible_distribution_major_version][0] | default(6.0) }}" + ansible.builtin.set_fact: + zabbix_server_version: "{{ zabbix_valid_server_versions[ansible_distribution_major_version][0] | default(6.4) }}" when: zabbix_server_version is not defined + tags: + - always + +- name: Set More Variables + ansible.builtin.set_fact: + zabbix_db_type_long: "{{ 'postgresql' if zabbix_server_database == 'pgsql' else 'mysql' }}" + zabbix_valid_version: "{{ zabbix_server_version|float in zabbix_valid_server_versions[ansible_distribution_major_version] }}" + zabbix_server_fpinglocation: "{{ zabbix_server_fpinglocation if zabbix_server_fpinglocation is defined else _zabbix_server_fpinglocation}}" + zabbix_server_fping6location: "{{ zabbix_server_fping6location if zabbix_server_fping6location is defined else _zabbix_server_fping6location}}" + tags: + - always + +- name: Stopping Install of Invalid Version + ansible.builtin.fail: + msg: Zabbix version {{ zabbix_server_version }} is not supported on {{ ansible_distribution }} {{ ansible_distribution_major_version }} + when: not zabbix_valid_version + tags: + - always -- name: "Install the correct repository" - include_tasks: "{{ ansible_os_family }}.yml" +- name: Install the correct repository + ansible.builtin.include_tasks: "{{ ansible_os_family }}.yml" -- name: "Installing the {{ zabbix_server_database_long }} database" - include_tasks: "{{ zabbix_server_database_long }}.yml" +- name: Installing the {{ zabbix_db_type_long }} database + ansible.builtin.include_tasks: "{{ zabbix_db_type_long }}.yml" - name: "Configure zabbix-server" - template: + ansible.builtin.template: src: zabbix_server.conf.j2 - dest: /etc/zabbix/zabbix_server.conf - owner: zabbix - group: zabbix + dest: "{{ zabbix_server_config }}" + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" mode: "{{ zabbix_server_conf_mode }}" + become: true notify: - zabbix-server restarted tags: - - zabbix-server - - init - config - name: "Create include dir zabbix-server" - file: + ansible.builtin.file: path: "{{ zabbix_server_include }}" - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" state: directory mode: "{{ zabbix_server_include_mode }}" + become: true tags: - - zabbix-server - - init + - install - config - name: "Add zabbix-server scripts" - include_tasks: "scripts.yml" + ansible.builtin.include_tasks: "scripts.yml" when: ( zabbix_server_alertscripts is defined ) or ( zabbix_server_externalscripts is defined ) - name: "Zabbix-server started" - service: + ansible.builtin.service: name: zabbix-server state: "{{ zabbix_service_state }}" enabled: "{{ zabbix_service_enabled }}" + become: true tags: - - zabbix-server + - service when: zabbix_server_manage_service | bool diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/mysql.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/mysql.yml index 9e419b125..aad009816 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/mysql.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/mysql.yml @@ -1,21 +1,28 @@ --- # task file for mysql -- name: "Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" - set_fact: + +- name: "MySQL | Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ zabbix_server_dbhost if (zabbix_server_dbhost != 'localhost') else inventory_hostname }}" when: - zabbix_server_dbhost_run_install + tags: + - database -- name: "Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" - set_fact: +- name: "MySQL | Set the correct delegated_dbhost (to support MySQL db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ inventory_hostname }}" when: - not zabbix_server_dbhost_run_install + tags: + - database -- name: "Override delegated_dbhost with real dbhost when dbhost is behind loadbalancer" - set_fact: +- name: "MySQL | Override delegated_dbhost with real dbhost when dbhost is behind loadbalancer" + ansible.builtin.set_fact: delegated_dbhost: "{{ zabbix_server_real_dbhost }}" when: zabbix_server_real_dbhost | default(false) + tags: + - database - name: "MySQL | Create database" community.mysql.mysql_db: @@ -28,11 +35,10 @@ login_port: "{{ zabbix_server_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" state: present - when: zabbix_database_creation + when: zabbix_server_database_creation register: zabbix_database_created delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-server - database - skip_ansible_lint @@ -45,57 +51,44 @@ login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" name: "{{ zabbix_server_dbuser }}" password: "{{ zabbix_server_dbpassword }}" + plugin: "{{ 'mysql_native_password' if (ansible_os_family == 'RedHat' and ansible_distribution_major_version == '7') else omit }}" priv: "{{ zabbix_server_dbname }}.*:ALL" host: "{{ zabbix_server_privileged_host }}" state: present - when: zabbix_database_creation + when: zabbix_server_database_creation delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-server - database -- name: "Get the file for create.sql >= 3.0" - shell: ls -1 {{ datafiles_path }}/{{ 'create' if zabbix_version is version('6.0', '<') else 'server' }}.sq* +- name: "MySQL | Get the file for create.sql" + ansible.builtin.shell: ls -1 {{ datafiles_path }}/{{ 'create' if zabbix_server_version is version('6.0', '<') else 'server' }}.sq* changed_when: false + become: true when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool register: ls_output_create tags: - - zabbix-server - database - name: MySQL | Get current database version - shell: | + ansible.builtin.shell: | mysql -h {{ zabbix_server_dbhost }} -u{{ zabbix_server_dbuser }} \ -p'{{ zabbix_server_dbpassword }}' -D '{{ zabbix_server_dbname }}' \ -e 'SELECT mandatory FROM dbversion;' register: mysql_db_version + become: true changed_when: false ignore_errors: true + tags: + - database # If the above check failed, then there was no dbversion table in the database. # We'll create it, below. Otherwise, we can access the database version in # `mysql_db_version["stdout_lines"][1]`, for example 5000000 for Zabbix 5.0. - name: MySQL | Check if database needs to be populated - set_fact: + ansible.builtin.set_fact: mysql_schema_empty: "{{ mysql_db_version is failed }}" -- name: "MySQL | Get version_comment" - community.mysql.mysql_variables: - variable: version - login_host: "{{ zabbix_server_mysql_login_host | default(omit) }}" - login_user: "{{ zabbix_server_mysql_login_user | default(omit) }}" - login_password: "{{ zabbix_server_mysql_login_password | default(omit) }}" - login_port: "{{ zabbix_server_mysql_login_port | default(omit) }}" - login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" - delegate_to: "{{ delegated_dbhost }}" - register: install_mysql_version - tags: - - zabbix-server - - database - - name: "MySQL | Get current value for innodb_default_row_format" community.mysql.mysql_variables: variable: innodb_default_row_format @@ -106,11 +99,7 @@ login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" delegate_to: "{{ delegated_dbhost }}" register: mysql_innodb_default_row_format - when: - - not ansible_check_mode - - install_mysql_version.msg is version('5.6', '>=') tags: - - zabbix-server - database - name: "MySQL | Set innodb_default_row_format to dynamic" @@ -123,15 +112,11 @@ login_port: "{{ zabbix_server_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty - - install_mysql_version.msg is version('5.6', '>=') - mysql_innodb_default_row_format.msg != 'dynamic' delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-server - database - name: "MySQL | Disable InnoDB Strict Mode" @@ -144,45 +129,45 @@ login_port: "{{ zabbix_server_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty - - install_mysql_version.msg is version('5.6', '>=') - ansible_distribution_release == "buster" delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-server - database -- name: "Fetch sql create file" +- name: "MySQL | Fetch sql create file" fetch: src: "{{ ls_output_create.stdout }}" dest: /tmp/{{ role_name }}/ flat: true + become: true when: - delegated_dbhost != inventory_hostname - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty + tags: + - database -- name: "Copy sql create file" - copy: +- name: "MySQL | Copy sql create file" + ansible.builtin.copy: src: /tmp/{{ role_name }}/ dest: "{{ ls_output_create.stdout | dirname }}" - mode: '0640' + mode: "0640" delegate_to: "{{ delegated_dbhost }}" + become: true when: - delegated_dbhost != inventory_hostname - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty + tags: + - database -- name: "MySQL | Create database and import file >= 3.0" +- name: "MySQL | Create database and import file" community.mysql.mysql_db: login_host: "{{ zabbix_server_mysql_login_host | default(omit) }}" - login_user: "{{ zabbix_server_mysql_login_user | default(omit) }}" - login_password: "{{ zabbix_server_mysql_login_password | default(omit) }}" + login_user: "{{ zabbix_server_dbuser if (ansible_os_family == 'RedHat' and ansible_distribution_major_version == '7') else zabbix_server_mysql_login_user }}" + login_password: "{{ zabbix_server_dbpassword if (ansible_os_family == 'RedHat' and ansible_distribution_major_version == '7') else zabbix_server_mysql_login_password }}" login_port: "{{ zabbix_server_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" name: "{{ zabbix_server_dbname }}" @@ -190,118 +175,39 @@ collation: "{{ zabbix_server_dbcollation }}" state: import target: "{{ ls_output_create.stdout }}" + use_shell: "{{ true if zabbix_server_version is version('5.0', '==') else false }}" when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-server - database - name: "MySQL | Revert innodb_default_row_format to previous value" community.mysql.mysql_variables: variable: innodb_default_row_format - value: '{{ mysql_innodb_default_row_format.msg }}' + value: "{{ mysql_innodb_default_row_format.msg }}" login_host: "{{ zabbix_server_mysql_login_host | default(omit) }}" login_user: "{{ zabbix_server_mysql_login_user | default(omit) }}" login_password: "{{ zabbix_server_mysql_login_password | default(omit) }}" login_port: "{{ zabbix_server_mysql_login_port | default(omit) }}" login_unix_socket: "{{ zabbix_server_mysql_login_unix_socket | default(omit) }}" when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty - mysql_innodb_default_row_format.msg != 'dynamic' delegate_to: "{{ delegated_dbhost }}" tags: - - zabbix-server - database -- name: "Check if we have sql_done files >= 3.0" - file: +- name: "MySQL | Check if we have sql_done files" + ansible.builtin.file: path: /etc/zabbix/create.done state: touch - mode: '0644' + mode: "0644" + become: true when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload | bool - - zabbix_repo != "epel" + - zabbix_server_database_sqlload | bool - mysql_schema_empty - -- name: "Get the correct path for the SQL files < 3.0" - shell: ls -1 {{ datafiles_path }}/{{ mysql_create_dir }}{{ item }}.sql* - changed_when: false - register: ls_output_schema - with_items: - - schema - - images - - data - when: - - zabbix_version is version('3.0', '<') - - zabbix_database_sqlload | bool - tags: - - zabbix-server - - database - -- name: "Check if we have done files < 3.0" - stat: - path: /etc/zabbix/{{ item }}.done - register: done_files - with_items: - - schema - - images - - data - when: - - zabbix_version is version('3.0', '<') - - zabbix_database_sqlload | bool - tags: - - zabbix-server - - database - -- name: "Create fact if sql_done files exists" - set_fact: - sql_files_executed: "{{ sql_files_executed | default({}) | combine({item.item: item.stat}) }}" - with_items: "{{ done_files.results }}" - when: - - zabbix_version is version('3.0', '<') - - zabbix_database_sqlload | bool - tags: - - zabbix-server - - database - -- name: "MySQL | Create database and import files < 3.0" - community.mysql.mysql_db: - name: "{{ zabbix_server_dbname }}" - encoding: "{{ zabbix_server_dbencoding }}" - collation: "{{ zabbix_server_dbcollation }}" - state: import - target: "{{ item.stdout }}" - with_items: "{{ ls_output_schema.results }}" - when: - - zabbix_version is version('3.0', '<') - - zabbix_database_sqlload | bool - - not sql_files_executed[item.item].exists - delegate_to: "{{ delegated_dbhost }}" - tags: - - zabbix-server - - database - -- name: "Check if we have sql_done files < 3.0" - file: - path: /etc/zabbix/{{ item }}.done - state: touch - mode: '0644' - with_items: - - schema - - images - - data - when: - - zabbix_version is version('3.0', '<') - - zabbix_database_sqlload | bool - - not sql_files_executed[item].exists tags: - - zabbix-server - database diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/postgresql.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/postgresql.yml index 77e300c01..5177a55be 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/postgresql.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/postgresql.yml @@ -1,17 +1,21 @@ --- # task file for postgresql -- name: "Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" - set_fact: +- name: "PostgreSQL | Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ zabbix_server_dbhost if (zabbix_server_dbhost != 'localhost') else inventory_hostname }}" when: - zabbix_server_dbhost_run_install + tags: + - database -- name: "Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" - set_fact: +- name: "PostgreSQL | Set the correct delegated_dbhost (to support postgres db deployment on a remote dbhost)" + ansible.builtin.set_fact: delegated_dbhost: "{{ inventory_hostname }}" when: - not zabbix_server_dbhost_run_install + tags: + - database - name: "PostgreSQL | Delegated" block: @@ -20,6 +24,7 @@ name: "{{ zabbix_server_dbname }}" port: "{{ zabbix_server_dbport }}" state: present + - name: "PostgreSQL | Delegated | Create database user" community.postgresql.postgresql_user: db: "{{ zabbix_server_dbname }}" @@ -29,19 +34,19 @@ priv: ALL state: present encrypted: true + - name: "PostgreSQL | Delegated | Create timescaledb extension" community.postgresql.postgresql_ext: db: "{{ zabbix_server_dbname }}" name: timescaledb - when: zabbix_database_timescaledb + when: zabbix_server_database_timescaledb become: true become_user: postgres delegate_to: "{{ delegated_dbhost }}" when: - - zabbix_database_creation + - zabbix_server_database_creation - zabbix_server_pgsql_login_host is not defined tags: - - zabbix-server - database - name: "PostgreSQL | Remote" @@ -55,6 +60,7 @@ name: "{{ zabbix_server_dbname }}" port: "{{ zabbix_server_dbport }}" state: present + - name: "PostgreSQL | Remote | Create database user" community.postgresql.postgresql_user: login_host: "{{ zabbix_server_pgsql_login_host | default(omit) }}" @@ -67,6 +73,7 @@ priv: ALL state: present encrypted: true + - name: "PostgreSQL | Remote | Create timescaledb extension" community.postgresql.postgresql_ext: login_host: "{{ zabbix_server_pgsql_login_host | default(omit) }}" @@ -75,23 +82,17 @@ login_unix_socket: "{{ zabbix_server_pgsql_login_unix_socket | default(omit) }}" db: "{{ zabbix_server_dbname }}" name: timescaledb - when: zabbix_database_timescaledb + when: zabbix_server_database_timescaledb when: - - zabbix_database_creation + - zabbix_server_database_creation - zabbix_server_pgsql_login_host is defined tags: - - zabbix-server - database -- name: Check if warn parameter can be used for shell module - set_fact: - produce_warn: False - when: ansible_version.full is version("2.14", "<") - - name: "PostgreSQL | Create schema" - shell: | + ansible.builtin.shell: | set -euxo pipefail - FILE={{ 'create.sql' if zabbix_version is version('6.0', '<') else 'server.sql' }} + FILE={{ 'create.sql' if zabbix_server_version is version('6.0', '<') else 'server.sql' }} cd {{ datafiles_path }} if [ -f ${FILE}.gz ] then zcat ${FILE}.gz > /tmp/create.sql @@ -110,15 +111,14 @@ warn: "{{ produce_warn | default(omit) }}" environment: PGPASSWORD: "{{ zabbix_server_dbpassword }}" + become: true when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_sqlload + - zabbix_server_database_sqlload tags: - - zabbix-server - database - name: "PostgreSQL | Create TimescaleDB hypertables" - shell: | + ansible.builtin.shell: | set -euxo pipefail cd {{ datafiles_path }} && if [ -f timescaledb.sql.gz ]; then zcat timescaledb.sql.gz > /etc/timescaledb.sql ; else cp -p timescaledb.sql /etc/timescaledb.sql ; fi @@ -134,92 +134,8 @@ warn: "{{ produce_warn | default(omit) }}" environment: PGPASSWORD: "{{ zabbix_server_dbpassword }}" + become: true when: - - zabbix_version is version('3.0', '>=') - - zabbix_database_timescaledb - tags: - - zabbix-server - - database - -- name: "Get complete path" - shell: ls -d {{ datafiles_path }} - register: datafiles_path_full - changed_when: false - when: - - (zabbix_version is version('3.0', '<') and zabbix_database_sqlload) or (zabbix_repo == "epel" and zabbix_database_sqlload) - tags: - - skip_ansible_lint - -- name: "Check if we have a create dir" - stat: - path: "{{ datafiles_path_full.stdout }}/create" - register: create_dir_or_not - when: - - (zabbix_version is version('3.0', '<') and zabbix_database_sqlload) or (zabbix_repo == "epel" and zabbix_database_sqlload) - -- name: "Set fact" - set_fact: - datafiles_path: "{{ datafiles_path }}/create" - when: - - (zabbix_version is version('3.0', '<') and zabbix_database_sqlload) or (zabbix_repo == "epel" and zabbix_database_sqlload) - - create_dir_or_not.stat.isdir is defined and create_dir_or_not.stat.isdir - - create_dir_or_not.stat.exists - -- name: "PostgreSQL | Importing schema file" - shell: | - set -euxo pipefail - cd {{ datafiles_path }} - if [ -f schema.sql.gz ]; then zcat schema.sql.gz > /tmp/schema.sql ; else cp -p schema.sql /tmp/schema.sql ;fi - cat /tmp/schema.sql | psql -h '{{ zabbix_server_dbhost }}' \ - -U '{{ zabbix_server_dbuser }}' \ - -d '{{ zabbix_server_dbname }}' \ - -p '{{ zabbix_server_dbport }}' - touch /etc/zabbix/schema.done - rm -f /etc/schema.sql - args: - creates: /etc/zabbix/schema.done - executable: /bin/bash - warn: "{{ produce_warn | default(omit) }}" - environment: - PGPASSWORD: "{{ zabbix_server_dbpassword }}" - when: - - (zabbix_version is version('3.0', '<') and zabbix_database_sqlload) or (zabbix_repo == "epel" and zabbix_database_sqlload) - tags: - - zabbix-server - - database - -- name: "PostgreSQL | Importing images file" - shell: > - cd {{ datafiles_path }} && - psql -h '{{ zabbix_server_dbhost }}' - -U '{{ zabbix_server_dbuser }}' - -d '{{ zabbix_server_dbname }}' - -p '{{ zabbix_server_dbport }}' - -f images.sql && touch /etc/zabbix/images.done - args: - creates: /etc/zabbix/images.done - warn: "{{ produce_warn | default(omit) }}" - environment: - PGPASSWORD: "{{ zabbix_server_dbpassword }}" - when: (zabbix_version is version('3.0', '<') and zabbix_database_sqlload) or (zabbix_repo == "epel" and zabbix_database_sqlload) - tags: - - zabbix-server - - database - -- name: "PostgreSQL | Importing data file" - shell: > - cd {{ datafiles_path }} && - psql -h '{{ zabbix_server_dbhost }}' - -U '{{ zabbix_server_dbuser }}' - -d '{{ zabbix_server_dbname }}' - -p '{{ zabbix_server_dbport }}' - -f data.sql && touch /etc/zabbix/data.done - args: - creates: /etc/zabbix/data.done - warn: "{{ produce_warn | default(omit) }}" - environment: - PGPASSWORD: "{{ zabbix_server_dbpassword }}" - when: (zabbix_version is version('3.0', '<') and zabbix_database_sqlload) or (zabbix_repo == "epel" and zabbix_database_sqlload) + - zabbix_server_database_timescaledb tags: - - zabbix-server - database diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/scripts.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/scripts.yml index 418436128..b253f325a 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/scripts.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/scripts.yml @@ -1,20 +1,26 @@ --- - name: "Configure zabbix-server alertscripts" - template: + ansible.builtin.template: src: "{{ item.path }}" dest: "{{ zabbix_server_alertscriptspath }}/{{ item.name }}" - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" mode: 0755 with_items: "{{ zabbix_server_alertscripts }}" + become: true when: zabbix_server_alertscripts is defined + tags: + - config - name: "Configure zabbix-server externalscripts" - template: + ansible.builtin.template: src: "{{ item.path }}" dest: "{{ zabbix_server_externalscriptspath }}/{{ item.name }}" - owner: zabbix - group: zabbix + owner: "{{ zabbix_os_user }}" + group: "{{ zabbix_os_user }}" mode: 0755 with_items: "{{ zabbix_server_externalscripts }}" + become: true when: zabbix_server_externalscripts is defined + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/selinux.yml b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/selinux.yml index 38a8d85fe..fe203aed1 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/tasks/selinux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/tasks/selinux.yml @@ -1,27 +1,32 @@ --- - # straight to getenforce binary , workaround for missing python_selinux library -- name: "Get getenforce binary" - stat: +- name: "SELinux | Get getenforce binary" + ansible.builtin.stat: path: /usr/sbin/getenforce register: getenforce_bin become: true + tags: + - always -- name: "Collect getenforce output" - command: getenforce +- name: "SELinux | Collect getenforce output" + ansible.builtin.command: getenforce register: sestatus - when: 'getenforce_bin.stat.exists' + when: "getenforce_bin.stat.exists" changed_when: false become: true check_mode: false + tags: + - always -- name: "Set zabbix_selinux to true if getenforce returns Enforcing or Permissive" - set_fact: - zabbix_selinux: "{{ true }}" +- name: "Set zabbix_server_selinux to true if getenforce returns Enforcing or Permissive" + ansible.builtin.set_fact: + zabbix_server_selinux: "{{ true }}" when: 'getenforce_bin.stat.exists and ("Enforcing" in sestatus.stdout or "Permissive" in sestatus.stdout)' + tags: + - config - name: "SELinux | RedHat | Install related SELinux package" - yum: + ansible.builtin.yum: name: - libsemanage-python - policycoreutils @@ -38,10 +43,10 @@ - selinux_allow_zabbix_can_network - ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6" tags: - - zabbix-server + - install -- name: "SELinux | RedHat | Install related SELinux package on RHEL9 and RHEL8" - yum: +- name: "SELinux | RedHat | Install related SELinux package on RHEL8" + ansible.builtin.yum: name: - python3-libsemanage state: present @@ -54,9 +59,9 @@ when: - ansible_os_family == "RedHat" - selinux_allow_zabbix_can_network - - ansible_distribution_major_version|int >= 8 + - ansible_distribution_major_version == "8" tags: - - zabbix-server + - install - name: "SELinux | RedHat | Enable httpd_can_connect_zabbix SELinux boolean" ansible.posix.seboolean: @@ -67,7 +72,7 @@ when: - selinux_allow_zabbix_can_http tags: - - zabbix-server + - config - name: "SELinux | RedHat | Enable zabbix_can_network SELinux boolean" ansible.posix.seboolean: @@ -78,10 +83,10 @@ when: - selinux_allow_zabbix_can_network tags: - - zabbix-server + - config - name: "SELinux | RedHat | Install related SELinux package to fix issues" - yum: + ansible.builtin.yum: name: - policycoreutils-python state: present @@ -95,10 +100,10 @@ - ansible_os_family == "RedHat" - ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6" tags: - - zabbix-server + - install -- name: "SELinux | RedHat | Install related SELinux package on RHEL9 and RHEL8" - yum: +- name: "SELinux | RedHat | Install related SELinux package to fix issues on RHEL8" + ansible.builtin.yum: name: - policycoreutils - checkpolicy @@ -112,13 +117,15 @@ become: true when: - ansible_os_family == "RedHat" - - ansible_distribution_major_version|int >= 8 + - ansible_distribution_major_version == "8" tags: - - zabbix-server + - install - name: "SELinux | RedHat | Add SEmodule to fix SELinux issue: zabbix_server_alerter.sock" - script: + ansible.builtin.script: cmd: files/install_semodule.bsx args: creates: /etc/selinux/targeted/active/modules/400/zabbix_server_add/cil become: true + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/templates/zabbix_server.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_server/templates/zabbix_server.conf.j2 index 19c99aa33..489e9c9f5 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/templates/zabbix_server.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_server/templates/zabbix_server.conf.j2 @@ -4,261 +4,120 @@ # This configuration file is "minimalized", which means all the original comments # are removed. The full documentation for your Zabbix Server can be found here: -# https://www.zabbix.com/documentation/{{ zabbix_version }}/en/manual/appendix/config/zabbix_server +# https://www.zabbix.com/documentation/{{ zabbix_server_version }}/en/manual/appendix/config/zabbix_server -ListenPort={{ zabbix_server_listenport }} -{% if zabbix_server_sourceip is defined and zabbix_server_sourceip %} -SourceIP={{ zabbix_server_sourceip }} -{% endif %} -{% if zabbix_version is version('3.0', '>=') %} -LogType={{ zabbix_server_logtype }} -{% endif %} -LogFile={{ zabbix_server_logfile }} -LogFileSize={{ zabbix_server_logfilesize }} -DebugLevel={{ zabbix_server_debuglevel }} -{% if zabbix_version is version('3.4', '>=') %} -SocketDir={{ zabbix_server_socketdir }} -{% endif %} -PidFile={{ zabbix_server_pidfile }} -DBHost={{ zabbix_server_dbhost }} -DBName={{ zabbix_server_dbname }} -{% if zabbix_server_dbschema is defined and zabbix_server_dbschema %} -DBSchema={{ zabbix_server_dbschema }} -{% endif %} -DBUser={{ zabbix_server_dbuser }} -DBPassword={{ zabbix_server_dbpassword }} -{% if zabbix_server_dbsocket is defined and zabbix_server_dbsocket %} -DBSocket={{ zabbix_server_dbsocket }} -{% endif %} -{% if zabbix_server_dbport is defined and zabbix_server_dbport %} -DBPort={{ zabbix_server_dbport }} -{% endif %} -{% if zabbix_version is version('6.0', '>=') %} -AllowUnsupportedDBVersions={{ zabbix_server_allowunsupporteddbversions }} -{% endif %} -{% if zabbix_server_historystorageurl is defined and zabbix_server_historystorageurl %} -HistoryStorageURL={{ zabbix_server_historystorageurl }} -{% endif %} -{% if zabbix_version is version('3.4', '>=') %} -HistoryStorageTypes={{ zabbix_server_historystoragetypes }} -{% endif %} -{% if zabbix_version is version('4.0', '>=') %} -HistoryStorageDateIndex={{ zabbix_server_historystoragedateindex }} -{% endif %} -{% if zabbix_version is version('4.0', '>=') %} -{% if zabbix_server_exportdir is defined and zabbix_server_exportdir %} -ExportDir={{ zabbix_server_exportdir }} -{% endif %} -{% endif %} -{% if zabbix_version is version('4.0', '>=') %} -ExportFileSize={{ zabbix_server_exportfilesize }} -{% endif %} -StartPollers={{ zabbix_server_startpollers }} -StartIPMIPollers={{ zabbix_server_startipmipollers }} -{% if zabbix_version is version('4.2', '>=') %} -StartLLDProcessors={{ zabbix_server_startlldprocessors }} -{% endif %} -{% if zabbix_version is version('4.2', '>=') %} -StartPreprocessors={{ zabbix_server_startpreprocessors }} -{% endif %} -StartPollersUnreachable={{ zabbix_server_startpollersunreachable }} -{% if zabbix_version is version('6.4', '>=') %} -StartConnectors={{ zabbix_server_connectors }} -{% endif %} -{% if zabbix_version is version('6.2', '>=') %} -StartHistoryPollers={{ zabbix_server_starthistorypollers }} -{% endif %} -StartTrappers={{ zabbix_server_starttrappers }} -StartPingers={{ zabbix_server_startpingers }} -StartDiscoverers={{ zabbix_server_startdiscoverers }} -StartHTTPPollers={{ zabbix_server_starthttppollers }} -{% if zabbix_version is version('2.0', '>=') %} -StartTimers={{ zabbix_server_starttimers }} -{% endif %} -{% if zabbix_version is version('3.0', '>=') %} -StartEscalators={{ zabbix_server_startescalators }} -{% endif %} -{% if zabbix_server_javagateway is defined and zabbix_server_javagateway %} -JavaGateway={{ zabbix_server_javagateway }} -JavaGatewayPort={{ zabbix_server_javagatewayport }} -StartJavaPollers={{ zabbix_server_startjavapollers }} -{% endif %} -{% if zabbix_version is version('2.2', '>=') %} -StartVMwareCollectors={{ zabbix_server_startvmwarecollectors }} -VMwareFrequency={{ zabbix_server_vmwarefrequency }} -{% if zabbix_version is version('3.0', '>=') %} -VMwarePerfFrequency={{ zabbix_server_vmwareperffrequency }} -{% endif %} -VMwareCacheSize={{ zabbix_server_vmwarecachesize }} -{% endif %} -{% if zabbix_version is version('3.0', '>=') %} -VMwareTimeout={{ zabbix_server_vmwaretimeout }} -{% endif %} -SNMPTrapperFile={{ zabbix_server_snmptrapperfile }} -StartSNMPTrapper={{ zabbix_server_startsnmptrapper }} -{% if zabbix_server_listenip is defined and zabbix_server_listenip %} -ListenIP={{ zabbix_server_listenip }} -{% endif %} -HousekeepingFrequency={{ zabbix_server_housekeepingfrequency }} -MaxHousekeeperDelete={{ zabbix_server_maxhousekeeperdelete }} -{% if zabbix_version is version('3.2', '<=') %} -SenderFrequency={{ zabbix_server_senderfrequency }} -{% endif %} -{% if zabbix_server_cachesize is defined and zabbix_server_cachesize is not none %} -CacheSize={{ zabbix_server_cachesize }} -{% else %} -{% if zabbix_version is version('6.2', '<') %} -CacheSize=8M -{% else %} -CacheSize=32M -{% endif %} -{% endif %} -{% if zabbix_server_cacheupdatefrequency is defined and zabbix_server_cacheupdatefrequency is not none %} -CacheUpdateFrequency={{ zabbix_server_cacheupdatefrequency }} -{% else %} -{% if zabbix_version is version('6.4', '<') %} -CacheUpdateFrequency=60 -{% else %} -CacheUpdateFrequency=10 -{%endif %} -{%endif %} -StartDBSyncers={{ zabbix_server_startdbsyncers }} -HistoryCacheSize={{ zabbix_server_historycachesize }} -{% if zabbix_version is version('3.0', '>=') %} -HistoryIndexCacheSize={{ zabbix_server_historyindexcachesize }} -{% endif %} -TrendCacheSize={{ zabbix_server_trendcachesize }} -{% if zabbix_version is version('6.0', '>=') %} -TrendFunctionCacheSize={{ zabbix_server_trendfunctioncachesize }} -{% endif %} -{% if zabbix_version is version('3.0', '<') %} - ### option: historytextcachesize -HistoryTextCacheSize={{ zabbix_server_historytextcachesize }} -{% endif %} -{% if zabbix_version is version('2.2', '>=') %} -ValueCacheSize={{ zabbix_server_valuecachesize }} -{% endif %} -{% if zabbix_version is version('2.4', '<') %} -NodeNoEvents={{ zabbix_server_nodenoevents }} -NodeNoHistory={{ zabbix_server_nodenohistory }} -{% endif %} -Timeout={{ zabbix_server_timeout }} -TrapperTimeout={{ zabbix_server_trappertimeout }} -UnreachablePeriod={{ zabbix_server_unreachableperiod }} -UnavailableDelay={{ zabbix_server_unavailabledelay }} -UnreachableDelay={{ zabbix_server_unreachabledelay }} -AlertScriptsPath={{ zabbix_server_alertscriptspath }} -ExternalScripts={{ zabbix_server_externalscriptspath }} -FpingLocation={{ zabbix_server_fpinglocation }} -Fping6Location={{ zabbix_server_fping6location }} -{% if zabbix_server_sshkeylocation is defined and zabbix_server_sshkeylocation %} -SSHKeyLocation={{ zabbix_server_sshkeylocation }} -{% endif %} -LogSlowQueries={{ zabbix_server_logslowqueries }} -TmpDir={{ zabbix_server_tmpdir }} -StartProxyPollers={{ zabbix_server_startproxypollers }} -{% if zabbix_server_proxyconfigfrequency is defined and zabbix_server_proxyconfigfrequency is not none %} -ProxyConfigFrequency={{ zabbix_server_proxyconfigfrequency }} -{% else %} -{% if zabbix_version is version('6.2', '<') %} -ProxyConfigFrequency=3600 -{% elif zabbix_version is version('6.4', '<') %} -ProxyConfigFrequency=300 -{% else %} -ProxyConfigFrequency=10 -{% endif %} -{% endif %} -ProxyDataFrequency={{ zabbix_server_proxydatafrequency }} -{% if zabbix_version is version('2.2', '>=') %} -AllowRoot={{ zabbix_server_allowroot }} -{% endif %} -{% if zabbix_version is version('3.0', '>=') %} -User={{ zabbix_server_user }} -{% endif %} -Include={{ zabbix_server_include }} -{% if zabbix_version is version('3.0', '>=') %} -SSLCertLocation={{ zabbix_server_sslcertlocation }} -SSLKeyLocation={{ zabbix_server_sslkeylocation }} -{% if zabbix_server_sslcalocation is defined and zabbix_server_sslcalocation is not none %} -SSLCALocation={{ zabbix_server_sslcalocation }} -{% endif %} -{% endif %} -{% if zabbix_version is version('2.2', '>=') %} -LoadModulePath={{ zabbix_server_loadmodulepath }} -{% endif %} -{% if zabbix_server_loadmodule is defined and zabbix_server_loadmodule %} -LoadModule = {{ zabbix_server_loadmodule }} -{% endif %} -{% if zabbix_version is version('3.0', '>=') %} -{% if zabbix_server_tlscafile is defined and zabbix_server_tlscafile is not none %} -TLSCAFile={{ zabbix_server_tlscafile }} -{% endif %} -{% if zabbix_server_tlscrlfile is defined and zabbix_server_tlscrlfile is not none %} -TLSCRLFile={{ zabbix_server_tlscrlfile }} -{% endif %} -{% if zabbix_server_tlscertfile is defined and zabbix_server_tlscertfile is not none %} -TLSCertFile={{ zabbix_server_tlscertfile }} -{% endif %} -{% if zabbix_server_tlskeyfile is defined and zabbix_server_tlskeyfile is not none %} -TLSKeyFile={{ zabbix_server_tlskeyfile }} -{% endif %} -{% endif %} -{% if zabbix_server_dbtlsconnect is defined and zabbix_server_dbtlsconnect is not none %} -DBTLSConnect={{ zabbix_server_dbtlsconnect }} -{% endif %} -{% if zabbix_server_dbtlscafile is defined and zabbix_server_dbtlscafile is not none %} -DBTLSCAFile={{ zabbix_server_dbtlscafile }} -{% endif %} -{% if zabbix_server_dbtlscertfile is defined and zabbix_server_dbtlscertfile is not none %} -DBTLSCertFile={{ zabbix_server_dbtlscertfile }} -{% endif %} -{% if zabbix_server_dbtlskeyfile is defined and zabbix_server_dbtlskeyfile is not none %} -DBTLSKeyFile={{ zabbix_server_dbtlskeyfile }} -{% endif %} -{% if zabbix_server_dbtlscipher is defined and zabbix_server_dbtlscipher is not none %} -DBTLSCipher={{ zabbix_server_dbtlscipher }} -{% endif %} -{% if zabbix_server_dbtlscipher13 is defined and zabbix_server_dbtlscipher13 is not none %} -DBTLSCipher13={{ zabbix_server_dbtlscipher13 }} -{% endif %} -{% if zabbix_version is version('6.0', '>=') %} -{% if zabbix_server_vaulttoken is defined and zabbix_server_vaulttoken is not none %} -VaultToken={{ zabbix_server_vaulttoken }} -{% endif %} -{% if zabbix_server_vaulturl is defined and zabbix_server_vaulturl is not none %} -VaultURL={{ zabbix_server_vaulturl }} -{% endif %} -{% if zabbix_server_vaultdbpath is defined and zabbix_server_vaultdbpath is not none %} -VaultDBPath={{ zabbix_server_vaultdbpath }} -{% endif %} -{% if zabbix_server_vaulttlscertfile is defined and zabbix_server_vaulttlscertfile is not none %} -VaultTLSKeyFile={{ zabbix_server_vaulttlscertfile }} -{% endif %} -{% if zabbix_server_vaulttlskeyfile is defined and zabbix_server_vaulttlskeyfile is not none %} -VaultTLSCertFile={{ zabbix_server_vaulttlskeyfile }} -{% endif %} -{% if zabbix_server_startreportwriters is defined and zabbix_server_startreportwriters is not none %} -StartReportWriters={{ zabbix_server_startreportwriters }} -{% endif %} -{% if zabbix_server_webserviceurl is defined and zabbix_server_webserviceurl is not none %} -WebServiceURL={{ zabbix_server_webserviceurl }} -{% endif %} -{% if zabbix_server_servicemanagersyncfrequency is defined and zabbix_server_servicemanagersyncfrequency is not none %} -ServiceManagerSyncFrequency={{ zabbix_server_servicemanagersyncfrequency }} -{% endif %} -{% if zabbix_server_problemhousekeepingfrequency is defined and zabbix_server_problemhousekeepingfrequency is not none %} -ProblemHousekeepingFrequency={{ zabbix_server_problemhousekeepingfrequency }} -{% endif %} -{% if zabbix_version is version('6.2', '>=') %} -StartODBCPollers={{ zabbix_server_startodbcpollers }} -{% endif %} -{% if zabbix_server_listenbacklog is defined and zabbix_server_listenbacklog is not none %} -ListenBacklog={{ zabbix_server_listenbacklog }} -{% endif %} -{% if zabbix_server_hanodename is defined and zabbix_server_hanodename is not none %} -HANodeName={{ zabbix_server_hanodename }} -{% endif %} -{% if zabbix_server_nodeaddress is defined and zabbix_server_nodeaddress is not none %} -NodeAddress={{ zabbix_server_nodeaddress }} -{% endif %} -{% endif %} +{{ (zabbix_server_alertscriptspath is defined and zabbix_server_alertscriptspath is not none) | ternary('', '# ') }}AlertScriptsPath={{ zabbix_server_alertscriptspath | default('') }} +{{ (zabbix_server_allowroot is defined and zabbix_server_allowroot is not none) | ternary('', '# ') }}AllowRoot={{ zabbix_server_allowroot | default('') }} +{{ (zabbix_server_allowunsupporteddbversions is defined and zabbix_server_allowunsupporteddbversions is not none) | ternary('', '# ') }}AllowUnsupportedDBVersions={{ zabbix_server_allowunsupporteddbversions | default('') }} +{{ (zabbix_server_cachesize is defined and zabbix_server_cachesize is not none) | ternary('', '# ') }}CacheSize={{ zabbix_server_cachesize | default('') }} +{{ (zabbix_server_cacheupdatefrequency is defined and zabbix_server_cacheupdatefrequency is not none) | ternary('', '# ') }}CacheUpdateFrequency={{ zabbix_server_cacheupdatefrequency | default('') }} +{{ (zabbix_server_dbhost is defined and zabbix_server_dbhost is not none) | ternary('', '# ') }}DBHost={{ zabbix_server_dbhost | default('') }} +{{ (zabbix_server_dbname is defined and zabbix_server_dbname is not none) | ternary('', '# ') }}DBName={{ zabbix_server_dbname | default('') }} +{{ (zabbix_server_dbpassword is defined and zabbix_server_dbpassword is not none) | ternary('', '# ') }}DBPassword={{ zabbix_server_dbpassword | default('') }} +{{ (zabbix_server_dbport is defined and zabbix_server_dbport is not none) | ternary('', '# ') }}DBPort={{ zabbix_server_dbport | default('') }} +{{ (zabbix_server_dbschema is defined and zabbix_server_dbschema is not none) | ternary('', '# ') }}DBSchema={{ zabbix_server_dbschema | default('') }} +{{ (zabbix_server_dbsocket is defined and zabbix_server_dbsocket is not none) | ternary('', '# ') }}DBSocket={{ zabbix_server_dbsocket | default('') }} +{{ (zabbix_server_dbtlscafile is defined and zabbix_server_dbtlscafile is not none) | ternary('', '# ') }}DBTLSCAFile={{ zabbix_server_dbtlscafile | default('') }} +{{ (zabbix_server_dbtlscertfile is defined and zabbix_server_dbtlscertfile is not none) | ternary('', '# ') }}DBTLSCertFile={{ zabbix_server_dbtlscertfile | default('') }} +{{ (zabbix_server_dbtlscipher is defined and zabbix_server_dbtlscipher is not none) | ternary('', '# ') }}DBTLSCipher={{ zabbix_server_dbtlscipher | default('') }} +{{ (zabbix_server_dbtlscipher13 is defined and zabbix_server_dbtlscipher13 is not none) | ternary('', '# ') }}DBTLSCipher13={{ zabbix_server_dbtlscipher13 | default('') }} +{{ (zabbix_server_dbtlsconnect is defined and zabbix_server_dbtlsconnect is not none) | ternary('', '# ') }}DBTLSConnect={{ zabbix_server_dbtlsconnect | default('') }} +{{ (zabbix_server_dbtlskeyfile is defined and zabbix_server_dbtlskeyfile is not none) | ternary('', '# ') }}DBTLSKeyFile={{ zabbix_server_dbtlskeyfile | default('') }} +{{ (zabbix_server_dbuser is defined and zabbix_server_dbuser is not none) | ternary('', '# ') }}DBUser={{ zabbix_server_dbuser | default('') }} +{{ (zabbix_server_debuglevel is defined and zabbix_server_debuglevel is not none) | ternary('', '# ') }}DebugLevel={{ zabbix_server_debuglevel | default('') }} +{{ (zabbix_server_exportdir is defined and zabbix_server_exportdir is not none) | ternary('', '# ') }}ExportDir={{ zabbix_server_exportdir | default('') }} +{{ (zabbix_server_exportfilesize is defined and zabbix_server_exportfilesize is not none) | ternary('', '# ') }}ExportFileSize={{ zabbix_server_exportfilesize | default('') }} +{{ (zabbix_server_exporttype is defined and zabbix_server_exporttype is not none) | ternary('', '# ') }}ExportType={{ zabbix_server_exporttype | default('') }} +{{ (zabbix_server_externalscriptspath is defined and zabbix_server_externalscriptspath is not none) | ternary('', '# ') }}ExternalScripts={{ zabbix_server_externalscriptspath | default('') }} +{{ (zabbix_server_fping6location is defined and zabbix_server_fping6location is not none) | ternary('', '# ') }}Fping6Location={{ zabbix_server_fping6location | default('') }} +{{ (zabbix_server_fpinglocation is defined and zabbix_server_fpinglocation is not none) | ternary('', '# ') }}FpingLocation={{ zabbix_server_fpinglocation | default('') }} +{{ (zabbix_server_hanodename is defined and zabbix_server_hanodename is not none) | ternary('', '# ') }}HANodeName={{ zabbix_server_hanodename | default('') }} +{{ (zabbix_server_historycachesize is defined and zabbix_server_historycachesize is not none) | ternary('', '# ') }}HistoryCacheSize={{ zabbix_server_historycachesize | default('') }} +{{ (zabbix_server_historyindexcachesize is defined and zabbix_server_historyindexcachesize is not none) | ternary('', '# ') }}HistoryIndexCacheSize={{ zabbix_server_historyindexcachesize | default('') }} +{{ (zabbix_server_historystoragedateindex is defined and zabbix_server_historystoragedateindex is not none) | ternary('', '# ') }}HistoryStorageDateIndex={{ zabbix_server_historystoragedateindex | default('') }} +{{ (zabbix_server_historystoragetypes is defined and zabbix_server_historystoragetypes is not none) | ternary('', '# ') }}HistoryStorageTypes={{ zabbix_server_historystoragetypes | default('') }} +{{ (zabbix_server_historystorageurl is defined and zabbix_server_historystorageurl is not none) | ternary('', '# ') }}HistoryStorageURL={{ zabbix_server_historystorageurl | default('') }} +{{ (zabbix_server_housekeepingfrequency is defined and zabbix_server_housekeepingfrequency is not none) | ternary('', '# ') }}HousekeepingFrequency={{ zabbix_server_housekeepingfrequency | default('') }} +{{ (zabbix_server_include is defined and zabbix_server_include is not none) | ternary('', '# ') }}Include={{ zabbix_server_include | default('') }} +{{ (zabbix_server_javagateway is defined and zabbix_server_javagateway is not none) | ternary('', '# ') }}JavaGateway={{ zabbix_server_javagateway | default('') }} +{{ (zabbix_server_javagatewayport is defined and zabbix_server_javagatewayport is not none) | ternary('', '# ') }}JavaGatewayPort={{ zabbix_server_javagatewayport | default('') }} +{{ (zabbix_server_listenbacklog is defined and zabbix_server_listenbacklog is not none) | ternary('', '# ') }}ListenBacklog={{ zabbix_server_listenbacklog | default('') }} +{{ (zabbix_server_listenip is defined and zabbix_server_listenip is not none) | ternary('', '# ') }}ListenIP={{ zabbix_server_listenip | default('') }} +{{ (zabbix_server_listenport is defined and zabbix_server_listenport is not none) | ternary('', '# ') }}ListenPort={{ zabbix_server_listenport | default('') }} +{{ (zabbix_server_loadmodule is defined and zabbix_server_loadmodule is not none) | ternary('', '# ') }}LoadModule={{ zabbix_server_loadmodule | default('') }} +{{ (zabbix_server_loadmodulepath is defined and zabbix_server_loadmodulepath is not none) | ternary('', '# ') }}LoadModulePath={{ zabbix_server_loadmodulepath | default('') }} +{{ (zabbix_server_logfile is defined and zabbix_server_logfile is not none) | ternary('', '# ') }}LogFile={{ zabbix_server_logfile | default('') }} +{{ (zabbix_server_logfilesize is defined and zabbix_server_logfilesize is not none) | ternary('', '# ') }}LogFileSize={{ zabbix_server_logfilesize | default('') }} +{{ (zabbix_server_logslowqueries is defined and zabbix_server_logslowqueries is not none) | ternary('', '# ') }}LogSlowQueries={{ zabbix_server_logslowqueries | default('') }} +{{ (zabbix_server_logtype is defined and zabbix_server_logtype is not none) | ternary('', '# ') }}LogType={{ zabbix_server_logtype | default('') }} +{{ (zabbix_server_maxhousekeeperdelete is defined and zabbix_server_maxhousekeeperdelete is not none) | ternary('', '# ') }}MaxHousekeeperDelete={{ zabbix_server_maxhousekeeperdelete | default('') }} +{{ (zabbix_server_nodeaddress is defined and zabbix_server_nodeaddress is not none) | ternary('', '# ') }}NodeAddress={{ zabbix_server_nodeaddress | default('') }} +{{ (zabbix_server_pidfile is defined and zabbix_server_pidfile is not none) | ternary('', '# ') }}PidFile={{ zabbix_server_pidfile | default('') }} +{{ (zabbix_server_proxyconfigfrequency is defined and zabbix_server_proxyconfigfrequency is not none) | ternary('', '# ') }}ProxyConfigFrequency={{ zabbix_server_proxyconfigfrequency | default('') }} +{{ (zabbix_server_proxydatafrequency is defined and zabbix_server_proxydatafrequency is not none) | ternary('', '# ') }}ProxyDataFrequency={{ zabbix_server_proxydatafrequency | default('') }} +{{ (zabbix_server_snmptrapperfile is defined and zabbix_server_snmptrapperfile is not none) | ternary('', '# ') }}SNMPTrapperFile={{ zabbix_server_snmptrapperfile | default('') }} +{{ (zabbix_server_socketdir is defined and zabbix_server_socketdir is not none) | ternary('', '# ') }}SocketDir={{ zabbix_server_socketdir | default('') }} +{{ (zabbix_server_sourceip is defined and zabbix_server_sourceip is not none) | ternary('', '# ') }}SourceIP={{ zabbix_server_sourceip | default('') }} +{{ (zabbix_server_sshkeylocation is defined and zabbix_server_sshkeylocation is not none) | ternary('', '# ') }}SSHKeyLocation={{ zabbix_server_sshkeylocation | default('') }} +{{ (zabbix_server_sslcalocation is defined and zabbix_server_sslcalocation is not none) | ternary('', '# ') }}SSLCALocation={{ zabbix_server_sslcalocation | default('') }} +{{ (zabbix_server_sslcertlocation is defined and zabbix_server_sslcertlocation is not none) | ternary('', '# ') }}SSLCertLocation={{ zabbix_server_sslcertlocation | default('') }} +{{ (zabbix_server_sslkeylocation is defined and zabbix_server_sslkeylocation is not none) | ternary('', '# ') }}SSLKeyLocation={{ zabbix_server_sslkeylocation | default('') }} +{{ (zabbix_server_startalerters is defined and zabbix_server_startalerters is not none) | ternary('', '# ') }}StartAlerters={{ zabbix_server_startalerters | default('') }} +{{ (zabbix_server_startdbsyncers is defined and zabbix_server_startdbsyncers is not none) | ternary('', '# ') }}StartDBSyncers={{ zabbix_server_startdbsyncers | default('') }} +{{ (zabbix_server_startdiscoverers is defined and zabbix_server_startdiscoverers is not none) | ternary('', '# ') }}StartDiscoverers={{ zabbix_server_startdiscoverers | default('') }} +{{ (zabbix_server_startescalators is defined and zabbix_server_startescalators is not none) | ternary('', '# ') }}StartEscalators={{ zabbix_server_startescalators | default('') }} +{{ (zabbix_server_starthistorypollers is defined and zabbix_server_starthistorypollers is not none) | ternary('', '# ') }}StartHistoryPollers={{ zabbix_server_starthistorypollers | default('') }} +{{ (zabbix_server_starthttppollers is defined and zabbix_server_starthttppollers is not none) | ternary('', '# ') }}StartHTTPPollers={{ zabbix_server_starthttppollers | default('') }} +{{ (zabbix_server_startipmipollers is defined and zabbix_server_startipmipollers is not none) | ternary('', '# ') }}StartIPMIPollers={{ zabbix_server_startipmipollers | default('') }} +{{ (zabbix_server_startjavapollers is defined and zabbix_server_startjavapollers is not none) | ternary('', '# ') }}StartJavaPollers={{ zabbix_server_startjavapollers | default('') }} +{{ (zabbix_server_startlldprocessors is defined and zabbix_server_startlldprocessors is not none) | ternary('', '# ') }}StartLLDProcessors={{ zabbix_server_startlldprocessors | default('') }} +{{ (zabbix_server_startodbcpollers is defined and zabbix_server_startodbcpollers is not none) | ternary('', '# ', '# ') }}StartODBCPollers={{ zabbix_server_startodbcpollers | default('') }} +{{ (zabbix_server_startpingers is defined and zabbix_server_startpingers is not none) | ternary('', '# ') }}StartPingers={{ zabbix_server_startpingers | default('') }} +{{ (zabbix_server_startpollers is defined and zabbix_server_startpollers is not none) | ternary('', '# ') }}StartPollers={{ zabbix_server_startpollers | default('') }} +{{ (zabbix_server_startpollersunreachable is defined and zabbix_server_startpollersunreachable is not none) | ternary('', '# ') }}StartPollersUnreachable={{ zabbix_server_startpollersunreachable | default('') }} +{{ (zabbix_server_startpreprocessors is defined and zabbix_server_startpreprocessors is not none) | ternary('', '# ') }}StartPreprocessors={{ zabbix_server_startpreprocessors | default('') }} +{{ (zabbix_server_startproxypollers is defined and zabbix_server_startproxypollers is not none) | ternary('', '# ') }}StartProxyPollers={{ zabbix_server_startproxypollers | default('') }} +{{ (zabbix_server_startreportwriters is defined and zabbix_server_startreportwriters is not none) | ternary('', '# ') }}StartReportWriters={{ zabbix_server_startreportwriters | default('') }} +{{ (zabbix_server_startsnmptrapper is defined and zabbix_server_startsnmptrapper is not none) | ternary('', '# ') }}StartSNMPTrapper={{ zabbix_server_startsnmptrapper | default('') }} +{{ (zabbix_server_starttimers is defined and zabbix_server_starttimers is not none) | ternary('', '# ') }}StartTimers={{ zabbix_server_starttimers | default('') }} +{{ (zabbix_server_starttrappers is defined and zabbix_server_starttrappers is not none) | ternary('', '# ') }}StartTrappers={{ zabbix_server_starttrappers | default('') }} +{{ (zabbix_server_startvmwarecollectors is defined and zabbix_server_startvmwarecollectors is not none) | ternary('', '# ') }}StartVMwareCollectors={{ zabbix_server_startvmwarecollectors | default('') }} +{{ (zabbix_server_statsallowedip is defined and zabbix_server_statsallowedip is not none) | ternary('', '# ') }}StatsAllowedIP={{ zabbix_server_statsallowedip | default('') }} +{{ (zabbix_server_timeout is defined and zabbix_server_timeout is not none) | ternary('', '# ') }}Timeout={{ zabbix_server_timeout | default('') }} +{{ (zabbix_server_tlscafile is defined and zabbix_server_tlscafile is not none) | ternary('', '# ') }}TLSCAFile={{ zabbix_server_tlscafile | default('') }} +{{ (zabbix_server_tlscertfile is defined and zabbix_server_tlscertfile is not none) | ternary('', '# ') }}TLSCertFile={{ zabbix_server_tlscertfile | default('') }} +{{ (zabbix_server_tlscipherall is defined and zabbix_server_tlscipherall is not none) | ternary('', '# ') }}TLSCipherAll={{ zabbix_server_tlscipherall | default('') }} +{{ (zabbix_server_tlscipherall13 is defined and zabbix_server_tlscipherall13 is not none) | ternary('', '# ') }}TLSCipherAll13={{ zabbix_server_tlscipherall13 | default('') }} +{{ (zabbix_server_tlsciphercert is defined and zabbix_server_tlsciphercert is not none) | ternary('', '# ') }}TLSCipherCert={{ zabbix_server_tlsciphercert | default('') }} +{{ (zabbix_server_tlsciphercert13 is defined and zabbix_server_tlsciphercert13 is not none) | ternary('', '# ') }}TLSCipherCert13={{ zabbix_server_tlsciphercert13 | default('') }} +{{ (zabbix_server_tlscipherpsk is defined and zabbix_server_tlscipherpsk is not none) | ternary('', '# ') }}TLSCipherPSK={{ zabbix_server_tlscipherpsk | default('') }} +{{ (zabbix_server_tlscipherpsk13 is defined and zabbix_server_tlscipherpsk13 is not none) | ternary('', '# ') }}TLSCipherPSK13={{ zabbix_server_tlscipherpsk13 | default('') }} +{{ (zabbix_server_tlscrlfile is defined and zabbix_server_tlscrlfile is not none) | ternary('', '# ') }}TLSCRLFile={{ zabbix_server_tlscrlfile | default('') }} +{{ (zabbix_server_tlskeyfile is defined and zabbix_server_tlskeyfile is not none) | ternary('', '# ') }}TLSKeyFile={{ zabbix_server_tlskeyfile | default('') }} +{{ (zabbix_server_tmpdir is defined and zabbix_server_tmpdir is not none) | ternary('', '# ') }}TmpDir={{ zabbix_server_tmpdir | default('') }} +{{ (zabbix_server_trappertimeout is defined and zabbix_server_trappertimeout is not none) | ternary('', '# ') }}TrapperTimeout={{ zabbix_server_trappertimeout | default('') }} +{{ (zabbix_server_trendcachesize is defined and zabbix_server_trendcachesize is not none) | ternary('', '# ') }}TrendCacheSize={{ zabbix_server_trendcachesize | default('') }} +{{ (zabbix_server_trendfunctioncachesize is defined and zabbix_server_trendfunctioncachesize is not none) | ternary('', '# ') }}TrendFunctionCacheSize={{ zabbix_server_trendfunctioncachesize | default('') }} +{{ (zabbix_server_unavailabledelay is defined and zabbix_server_unavailabledelay is not none) | ternary('', '# ') }}UnavailableDelay={{ zabbix_server_unavailabledelay | default('') }} +{{ (zabbix_server_unreachabledelay is defined and zabbix_server_unreachabledelay is not none) | ternary('', '# ') }}UnreachableDelay={{ zabbix_server_unreachabledelay | default('') }} +{{ (zabbix_server_unreachableperiod is defined and zabbix_server_unreachableperiod is not none) | ternary('', '# ') }}UnreachablePeriod={{ zabbix_server_unreachableperiod | default('') }} +{{ (zabbix_server_user is defined and zabbix_server_user is not none) | ternary('', '# ') }}User={{ zabbix_server_user | default('') }} +{{ (zabbix_server_valuecachesize is defined and zabbix_server_valuecachesize is not none) | ternary('', '# ') }}ValueCacheSize={{ zabbix_server_valuecachesize | default('') }} +{% if zabbix_server_version is version('6.2', '>=') %} +{{ (zabbix_server_vault is defined and zabbix_server_vault is not none) | ternary('', '# ') }}Vault={{ zabbix_server_vault | default('') }} +{% endif %} +{% if zabbix_server_version is version('6.4', '>=') %} +{{ (zabbix_server_connectors is defined and zabbix_server_connectors is not none) | ternary('', '# ') }}StartConnectors={{ zabbix_server_connectors | default('') }} +{% endif %} +{{ (zabbix_server_vaultdbpath is defined and zabbix_server_vaultdbpath is not none) | ternary('', '# ') }}VaultDBPath={{ zabbix_server_vaultdbpath | default('') }} +{% if zabbix_server_version is version('6.2', '>=') %} +{{ (zabbix_server_vaulttlskeyfile is defined and zabbix_server_vaulttlskeyfile is not none) | ternary('', '# ') }}VaultTLSKeyFile={{ zabbix_server_vaulttlskeyfile | default('') }} +{{ (zabbix_server_vaulttlscertfile is defined and zabbix_server_vaulttlscertfile is not none) | ternary('', '# ') }}VaultTLSCertFile={{ zabbix_server_vaulttlscertfile | default('') }} +{% endif %} +{{ (zabbix_server_vaulttoken is defined and zabbix_server_vaulttoken is not none) | ternary('', '# ') }}VaultToken={{ zabbix_server_vaulttoken | default('') }} +{{ (zabbix_server_vaulturl is defined and zabbix_server_vaulturl is not none) | ternary('', '# ') }}VaultURL={{ zabbix_server_vaulturl | default('') }} +{{ (zabbix_server_vmwarecachesize is defined and zabbix_server_vmwarecachesize is not none) | ternary('', '# ') }}VMwareCacheSize={{ zabbix_server_vmwarecachesize | default('') }} +{{ (zabbix_server_vmwarefrequency is defined and zabbix_server_vmwarefrequency is not none) | ternary('', '# ') }}VMwareFrequency={{ zabbix_server_vmwarefrequency | default('') }} +{{ (zabbix_server_vmwareperffrequency is defined and zabbix_server_vmwareperffrequency is not none) | ternary('', '# ') }}VMwarePerfFrequency={{ zabbix_server_vmwareperffrequency | default('') }} +{{ (zabbix_server_vmwaretimeout is defined and zabbix_server_vmwaretimeout is not none) | ternary('', '# ') }}VMwareTimeout={{ zabbix_server_vmwaretimeout | default('') }} +{{ (zabbix_server_webserviceurl is defined and zabbix_server_webserviceurl is not none) | ternary('', '# ') }}WebServiceURL={{ zabbix_server_webserviceurl | default('') }} diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/vars/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_server/vars/Debian.yml index 1639e94b3..4074869e6 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/vars/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/vars/Debian.yml @@ -7,30 +7,29 @@ mysql_create_dir: "" zabbix_valid_server_versions: # Debian + "12": + - 6.4 + - 6.0 "11": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "10": - 6.0 - - 5.0 - - 4.0 - "9": - - 4.0 # Ubuntu "22": - 6.4 + - 6.2 - 6.0 "20": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "18": - 6.0 - - 5.0 - - 4.0 -zabbix_server_fpinglocation: /usr/bin/fping -zabbix_server_fping6location: /usr/bin/fping6 +debian_keyring_path: /etc/apt/keyrings/ +zabbix_gpg_key: "{{ debian_keyring_path }}/zabbix-official-repo.asc" +_zabbix_repo_deb_url: "http://repo.zabbix.com/zabbix/{{ zabbix_server_version }}" +_zabbix_server_fping6location: /usr/bin/fping6 +_zabbix_server_fpinglocation: /usr/bin/fping diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/vars/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_server/vars/RedHat.yml index 016eae514..c2e0f14f3 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_server/vars/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_server/vars/RedHat.yml @@ -5,18 +5,32 @@ apache_log: httpd mysql_create_dir: create/ +__epel_repo: + - epel + zabbix_valid_server_versions: "9": - 6.4 + - 6.2 - 6.0 "8": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 - "7": - - 5.0 - - 4.0 -zabbix_server_fpinglocation: /usr/sbin/fping -zabbix_server_fping6location: /usr/sbin/fping6 +pgsql_depenencies: + "9": + - python3-psycopg2 + "8": + - python3-psycopg2 + +mysql_client_pkgs: + "9": + - mysql + - python3-PyMySQL + "8": + - mysql + - python3-PyMySQL + +_zabbix_server_fping6location: /usr/sbin/fping6 +_zabbix_server_fpinglocation: /usr/sbin/fping diff --git a/ansible_collections/community/zabbix/roles/zabbix_server/vars/zabbix.yml b/ansible_collections/community/zabbix/roles/zabbix_server/vars/zabbix.yml deleted file mode 100644 index 7a642c9d6..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_server/vars/zabbix.yml +++ /dev/null @@ -1,261 +0,0 @@ ---- -sign_keys: - "64": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "62": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "60": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "54": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - jessie: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "52": - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - jessie: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "50": - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - jessie: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "44": - focal: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "42": - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "40": - focal: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "34": - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "32": - bionic: - sign_key: A14FE591 - sonya: - sign_key: 79EA5ED4 - serena: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - jessie: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "30": - bionic: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "24": - wheezy: - sign_key: 79EA5ED4 - jessie: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - "22": - squeeze: - sign_key: 79EA5ED4 - jessie: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - lucid: - sign_key: 79EA5ED4 - -suse: - "openSUSE Leap": - "42": - name: server:monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_Leap_{{ ansible_distribution_version }}/ - "openSUSE": - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_{{ ansible_distribution_version }} - "SLES": - "11": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_11_SP3/ - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_12_SP3/ diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/README.md b/ansible_collections/community/zabbix/roles/zabbix_web/README.md index cef5d62e7..5904f8288 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/README.md +++ b/ansible_collections/community/zabbix/roles/zabbix_web/README.md @@ -43,7 +43,7 @@ Please send Pull Requests or suggestions when you want to use this role for othe ## Ansible 2.10 and higher -With the release of Ansible 2.10, modules have been moved into collections. With the exception of ansible.builtin modules, this means additonal collections must be installed in order to use modules such as seboolean (now ansible.posix.seboolean). The following collections are now required: `ansible.posix`. The `community.general` collection is required when defining the `zabbix_web_htpasswd` variable (see variable section below). Installing the collections: +With the release of Ansible 2.10, modules have been moved into collections. With the exception of ansible.builtin modules, this means additonal collections must be installed in order to use modules such as seboolean (now ansible.posix.seboolean). The following collections are now required: `ansible.posix`. Installing the collections: ```sh ansible-galaxy collection install ansible.posix @@ -54,25 +54,16 @@ ansible-galaxy collection install community.general See the following list of supported Operating Systems with the Zabbix releases. -| Zabbix | 6.4 | 6.2 | 6.0 (LTS) | 5.4 | 5.2 | 5.0 (LTS) | 4.4 | 4.0 (LTS) | 3.0 (LTS) | -|---------------------|-----|-----|-----------|-----|-----|------------|-----|-----------|-----------| -| Red Hat Fam 9 | V | V | V | | | | | | | -| Red Hat Fam 8 | V | V | V | V | V | V | V | | | -| Red Hat Fam 7 | | V | V | V | V | V | V | V | V | -| Red Hat Fam 6 | | | | | V | V | | | V | -| Red Hat Fam 5 | | | | | V | V | | | V | -| Fedora | | | | | | | V | V | | -| Ubuntu 22.04 jammy | V | V | V | | | | | | | -| Ubuntu 20.04 focal | V | V | V | V | V | V | V | | | -| Ubuntu 18.04 bionic | | | V | V | V | V | V | V | | -| Ubuntu 16.04 xenial | | | | | V | V | V | V | | -| Ubuntu 14.04 trusty | | | | | V | V | V | V | V | -| Debian 10 buster | V | V | V | V | V | V | V | | | -| Debian 9 stretch | | | V | V | V | V | V | V | | -| Debian 8 jessie | | | | | V | V | V | V | V | -| Debian 7 wheezy | | | | | | | | V | V | -| macOS 10.15 | | | | | | | V | V | | -| macOS 10.14 | | | | | | | V | V | | +| Zabbix | 6.4 | 6.2 | 6.0 | +|---------------------|-----|-----|-----| +| Red Hat Fam 9 | V | V | V | +| Red Hat Fam 8 | V | V | V | +| Ubuntu 22.04 jammy | V | V | V | +| Ubuntu 20.04 focal | V | V | V | +| Ubuntu 18.04 bionic | | | V | +| Debian 12 bookworm | V | | V | +| Debian 11 bullseye | V | V | V | +| Debian 10 buster | | | V | # Installation @@ -93,107 +84,77 @@ The following is an overview of all available configuration defaults for this ro ### Overall Zabbix -* `zabbix_web_version`: This is the version of zabbix. Default: The highest supported version for the operating system. Can be overridden to 6.2, 6.0, 5.4, 5.2, 5.0, 4.4, 4.0, 3.4, 3.2, 3.0, 2.4, or 2.2. Previously the variable `zabbix_version` was used directly but it could cause [some inconvenience](https://github.com/dj-wasabi/ansible-zabbix-agent/pull/303). That variable is maintained by retrocompativility. +* `zabbix_web_version`: Optional. The latest available major.minor version of Zabbix will be installed on the host(s). If you want to use an older version, please specify this in the major.minor format. Example: `zabbix_web_version: 6.0`. * `zabbix_web_version_minor`: When you want to specify a minor version to be installed. RedHat only. Default set to: `*` (latest available) -* `zabbix_repo`: Default: `zabbix` - * `epel`: install agent from EPEL repo - * `zabbix`: (default) install agent from Zabbix repo - * `other`: install agent from pre-existing or other repo * `zabbix_repo_yum`: A list with Yum repository configuration. * `zabbix_repo_yum_schema`: Default: `https`. Option to change the web schema for the yum repository(http/https) -* `zabbix_repo_yum_disabled`: A string with repository names that should be disabled when installing Zabbix component specific packages. Is only used when `zabbix_repo_yum_enabled` contains 1 or more repositories. Default `*`. -* `zabbix_repo_yum_enabled`: A list with repository names that should be enabled when installing Zabbix component specific packages. - +* `zabbix_web_disable_repo`: A list of repos to disable during install. Default `epel`. * `zabbix_web_package_state`: Default: `present`. Can be overridden to `latest` to update packages when needed. -* `zabbix_web_centos_release`: Default: True. When the `centos-release-scl` repository needs to be enabled. This is required when using Zabbix 5.0 due to installation of a recent version of `PHP`. -* `zabbix_web_rhel_release`: Default: True. When the `scl-utils` repository needs to be enabled. This is required when using Zabbix 5.0 due to installation of a recent version of `PHP`. * `zabbix_web_doubleprecision`: Default: `False`. For upgraded installations, please read database [upgrade notes](https://www.zabbix.com/documentation/current/manual/installation/upgrade_notes_500) (Paragraph "Enabling extended range of numeric (float) values") before enabling this option. * `zabbix_web_conf_mode`: Default: `0644`. The "mode" for the Zabbix configuration file. +* `zabbix_repo_deb_url`: The URL to the Zabbix repository. Default `http://repo.zabbix.com/zabbix/{{ zabbix_web_version }}/{{ ansible_distribution.lower() }}` +* `zabbix_repo_deb_component`: The repository component for Debian installs. Default `main`. ### Zabbix Web specific * `zabbix_api_server_url`: This is the url on which the zabbix web interface is available. Default is zabbix.example.com, you should override it. For example, see "Example Playbook" +* `zabbix_web_http_server`: Which web server is in use. Valid values are 'apache' and 'nginx'. Default is `apache` * `zabbix_url_aliases`: A list with Aliases for the Apache Virtual Host configuration. * `zabbix_timezone`: Default: `Europe/Amsterdam`. This is the timezone. The Apache Virtual Host needs this parameter. -* `zabbix_vhost`: Default: `true`. When you don't want to create an Apache Virtual Host configuration, you can set it to False. +* `zabbix_web_create_vhost`: Default: `true`. When you don't want to create an Apache Virtual Host configuration, you can set it to False. +* `zabbix_web_create_php_fpm`: Configure php-fpm (Debian hosts only). Default is to use the same value as `zabbix_web_create_vhost`. * `zabbix_web_env`: (Optional) A Dictionary of PHP Environments settings. -* `zabbix_web_conf_web_user`: When provided, the user (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). -* `zabbix_web_conf_web_group`: When provided, the group (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). -* `zabbix_web_htpasswd`: (Optional) Allow HTTP authentication at the webserver level via a htpasswd file. -* `zabbix_web_htpasswd_file`: Default: `/etc/zabbix/web/htpasswd`. Allows the change the default path to the htpasswd file. -* `zabbix_web_htpasswd_users`: (Optional) Dictionary for creating users via `htpasswd_user` and passphrases via `htpasswd_pass` in htpasswd file. -* `zabbix_web_allowlist_ips`: (Optional) Allow web access at webserver level to a list of defined IPs or CIDR. +* `zabbix_web_user`: When provided, the user (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). +* `zabbix_web_group`: When provided, the group (which should already exist on the host) will be used for ownership for web/php related processes. (Default set to either `apache` (`www-data` for Debian) or `nginx`). * `zabbix_web_connect_ha_backend`: (Optional) Default: `false`. When set to `true` values for Zabbix server will not be written and frontend gets values from database to connect to active cluster node. Set `true` when operating Zabbix servers in a cluste (only >=6.0). * `zabbix_saml_idp_crt`: (Optional) The path to the certificate of the Identity Provider used for SAML authentication * `zabbix_saml_sp_crt`: (Optional) The path to the public certificate of Zabbix as Service Provider * `zabbix_saml_sp_key`: (Optional) The path to the private certificate of Zabbix as Service Provider -#### Apache configuration +#### Apache/Nginx Configuration -* `zabbix_apache_vhost_port`: The port on which Zabbix HTTP vhost is running. -* `zabbix_apache_vhost_tls_port`: The port on which Zabbix HTTPS vhost is running. -* `zabbix_apache_vhost_listen_ip`: On which interface the Apache Virtual Host is available. +* `zabbix_web_vhost_port`: The port on which Zabbix HTTP vhost is running. +* `zabbix_web_vhost_tls_port`: The port on which Zabbix HTTPS vhost is running. +* `zabbix_web_vhost_listen_ip`: On which interface the Apache Virtual Host is available. * `zabbix_apache_can_connect_ldap`: Default: `false`. Set SELinux boolean to allow httpd to connect to LDAP. -* `zabbix_php_install`: Default: `true`. True / False. Switch for extra install of packages for PHP, currently on for Debian/Ubuntu. -* `zabbix_web_max_execution_time`: -* `zabbix_web_memory_limit`: -* `zabbix_web_post_max_size`: -* `zabbix_web_upload_max_filesize`: +* `zabbix_web_max_execution_time`: PHP max execution time +* `zabbix_web_memory_limit`: PHP memory limit +* `zabbix_web_post_max_size`: PHP maximum post size +* `zabbix_web_upload_max_filesize`: PHP maximum file size * `zabbix_web_max_input_time`: -* `zabbix_apache_include_custom_fragment`: Default: `true`. Includes php_value vars max_execution_time, memory_limit, post_max_size, upload_max_filesize, max_input_time and date.timezone in vhost file.. place those in php-fpm configuration. -* `zabbix_apache_tls`: If the Apache vhost should be configured with TLS encryption or not. -* `zabbix_apache_redirect`: If a redirect should take place from HTTP to HTTPS -* `zabbix_apache_tls_crt`: The path to the TLS certificate file. -* `zabbix_apache_tls_key`: The path to the TLS key file. -* `zabbix_apache_tls_chain`: The path to the TLS certificate chain file. -* `zabbix_apache_SSLPassPhraseDialog`: Type of pass phrase dialog for encrypted private keys. -* `zabbix_apache_SSLSessionCache`: Type of the global/inter-process SSL Session Cache -* `zabbix_apache_SSLSessionCacheTimeout`: Number of seconds before an SSL session expires in the Session Cache -* `zabbix_apache_SSLCryptoDevice`: Enable use of a cryptographic hardware accelerator +* `zabbix_web_tls`: If the Apache vhost should be configured with TLS encryption or not. +* `zabbix_web_redirect`: If a redirect should take place from HTTP to HTTPS +* `zabbix_web_tls_crt`: The path to the TLS certificate file. +* `zabbix_web_tls_key`: The path to the TLS key file. +* `zabbix_web_tls_chain`: The path to the TLS certificate chain file. +* `zabbix_web_SSLPassPhraseDialog`: Type of pass phrase dialog for encrypted private keys. +* `zabbix_web_SSLSessionCache`: Type of the global/inter-process SSL Session Cache +* `zabbix_web_SSLSessionCacheTimeout`: Number of seconds before an SSL session expires in the Session Cache +* `zabbix_web_SSLCryptoDevice`: Enable use of a cryptographic hardware accelerator * `zabbix_apache_custom_includes`: Configure custom includes. Default: `[]` -When `zabbix_apache_tls_crt`, `zabbix_apache_tls_key` and/or `zabbix_apache_tls_chain` are used, make sure that these files exists before executing this role. The Zabbix-Web role will not install the mentioned files. +When `zabbix_web_tls_crt`, `zabbix_web_tls_key` and/or `zabbix_web_tls_chain` are used, make sure that these files exists before executing this role. The Zabbix-Web role will not install the mentioned files. See https://httpd.apache.org/docs/current/mod/mod_ssl.html for SSL* configuration options for Apache HTTPD. #### Nginx configuration -* `zabbix_nginx_vhost_port`: The port on which Zabbix HTTP vhost is running. -* `zabbix_nginx_vhost_tls_port`: The port on which Zabbix HTTPS vhost is running. -* `zabbix_nginx_tls`: If the Nginx vhost should be configured with TLS encryption or not. -* `zabbix_nginx_tls_crt`: The path to the TLS certificate file. -* `zabbix_nginx_tls_key`: The path to the TLS key file. -* `zabbix_nginx_tls_dhparam`: The path to the TLS DHParam file. -* `zabbix_nginx_tls_session_cache`: Type of the global/inter-process SSL Session Cache -* `zabbix_nginx_tls_session_timeout`: -* `zabbix_nginx_tls_session_tickets`: -* `zabbix_nginx_tls_protocols`: The TLS Protocols to accept. -* `zabbix_nginx_tls_ciphers`: The TLS Ciphers to be allowed. - -When `zabbix_nginx_tls_crt` and `zabbix_nginx_tls_key` are used, make sure that these files exists before executing this role. The Zabbix-Web role will not install the mentioned files. #### PHP-FPM The following properties are specific to Zabbix 5.0 and for the PHP(-FPM) configuration: -* `zabbix_php_version`: Either `7.3` or `7.4` (Based on the OS Family). When you want to override the PHP Version. * `zabbix_php_fpm_session`: The directory where sessions will be stored. If none are provided, defaults are used. * `zabbix_php_fpm_listen`: The path to a socket file or ipaddress:port combination on which PHP-FPM needs to listen. If none are provided, defaults are used. * `zabbix_php_fpm_conf_listen`: Default: `true`. If we want to configure the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. * `zabbix_php_fpm_conf_user`: The owner of the socket file (When `zabbix_php_fpm_listen` contains a patch to a socket file). -* `zabbix_php_fpm_conf_enable_user`: Default: `true`. If we want to configure the owner of the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. + * `zabbix_php_fpm_conf_group`: The group of the owner of the socket file (When `zabbix_php_fpm_listen` contains a patch to a socket file). -* `zabbix_php_fpm_conf_enable_group`: Default: `true`. If we want to configure the group of the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. -* `zabbix_php_fpm_conf_mode`: The mode for the socket file (When `zabbix_php_fpm_listen` contains a patch to a socket file). -* `zabbix_php_fpm_conf_enable_mode`: Default: `true`. If we want to configure the mode of the `zabbix_php_fpm_listen` in the PHP-FPM configuration file. -* `zabbix_php_fpm_dir_etc`: etc HOME root directory of PHP-FPM setup. -* `zabbix_php_fpm_dir_var`: Var HOME root directory of PHP-FPM setup. ### Zabbix Server * `zabbix_server_name`: The name of the Zabbix Server. * `zabbix_server_database`: The type of database used. Can be: mysql or pgsql -* `zabbix_server_database_long`: The type of database used, but long name. Can be: mysql or postgresql * `zabbix_server_hostname`: The hostname on which the zabbix-server is running. Default set to: {{ inventory_hostname }} * `zabbix_server_listenport`: On which port the Zabbix Server is available. Default: 10051 * `zabbix_server_dbhost`: The hostname on which the database is running. @@ -201,6 +162,7 @@ The following properties are specific to Zabbix 5.0 and for the PHP(-FPM) config * `zabbix_server_dbuser`: The database username which is used by the Zabbix Server. * `zabbix_server_dbpassword`: The database user password which is used by the Zabbix Server. * `zabbix_server_dbport`: The database port which is used by the Zabbix Server. +* `zabbix_server_dbencryption`: Use encryption with the database connection The following properties are related when using Elasticsearch for history storage: @@ -218,6 +180,17 @@ When the target host does not have access to the internet, but you do have a pro * `zabbix_http_proxy` * `zabbix_https_proxy` +## Tags + +The majority of tasks within this role are tagged as follows: + +* `install`: Tasks associated with the installation of software. +* `dependencies`: Installation tasks related to dependencies that aren't part of the core zabbix installation. +* `database`: Tasks associated with the installation or configuration of the database. +* `api`: Tasks associated with using the Zabbix API to connect and modify the Zabbix server. +* `config`: Tasks associated with the configuration of Zabbix or a supporting service. +* `service`: Tasks associated with managing a service. + # Example Playbook There are two ways of using the zabbix-web: @@ -237,12 +210,12 @@ When there is one host running both Zabbix Server and the Zabbix Web (Running My - role: geerlingguy.php - role: community.zabbix.zabbix_server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 - role: community.zabbix.zabbix_web zabbix_api_server_url: zabbix.mydomain.com zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 ``` @@ -256,7 +229,7 @@ This is a two host setup. On one host (Named: "zabbix-server") the Zabbix Server roles: - role: community.zabbix.zabbix_server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 - hosts: zabbix-web @@ -268,7 +241,7 @@ This is a two host setup. On one host (Named: "zabbix-server") the Zabbix Server zabbix_api_server_url: zabbix.mydomain.com zabbix_server_hostname: zabbix-server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 ``` @@ -289,13 +262,13 @@ zabbix.conf.php, for example to add LDAP CA certificates. To do this add a `zabb php_packages: - php - php-fpm - - php-acpu + - php-apcu - role: geerlingguy.apache-php-fpm - role: community.zabbix.zabbix_web zabbix_api_server_url: zabbix.mydomain.com zabbix_server_hostname: zabbix-server zabbix_server_database: mysql - zabbix_server_database_long: mysql + zabbix_db_type_long: mysql zabbix_server_dbport: 3306 zabbix_web_env: LDAPTLS_CACERT: /etc/ssl/certs/ourcert.pem diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/defaults/main.yml b/ansible_collections/community/zabbix/roles/zabbix_web/defaults/main.yml index 6e326461e..f37bb07da 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/defaults/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/defaults/main.yml @@ -1,79 +1,66 @@ --- # defaults file for zabbix-web -# zabbix_web_version: 6.0 -zabbix_web_version_minor: "*" -zabbix_version: "{{ zabbix_web_version }}" -zabbix_repo: zabbix +# zabbix_web_version: 6.4 zabbix_web_package_state: present -zabbix_web_centos_release: true -zabbix_web_rhel_release: true -zabbix_selinux: false zabbix_web_doubleprecision: false -zabbix_web_conf_mode: "0640" +zabbix_web_conf_mode: "0644" zabbix_web_connect_ha_backend: false - -zabbix_url: zabbix.example.com # Will be deprecated in 2.0.0 -zabbix_api_server_url: "{{ zabbix_url }}" -zabbix_websrv: apache -zabbix_websrv_servername: "{{ zabbix_api_server_url | regex_findall('(?:https?\\://)?([\\w\\-\\.]+)') | first }}" +zabbix_api_server_url: zabbix.example.com +zabbix_web_http_server: apache zabbix_url_aliases: [] -zabbix_web_htpasswd: false -zabbix_web_htpasswd_file: /etc/zabbix/web/htpasswd -zabbix_timezone: Europe/Amsterdam -zabbix_vhost: true +zabbix_web_create_vhost: true +zabbix_web_create_php_fpm: "{{ zabbix_web_create_vhost }}" -zabbix_php_install: true -zabbix_php_frontend_deprecated: false -zabbix_php_fpm: false -zabbix_php_fpm_dir_etc: /etc/opt/rh/rh-php72/ -zabbix_php_fpm_dir_var: /var/opt/rh/rh-php72/ -zabbix_php_fpm_conf_listen: true -zabbix_php_fpm_conf_enable_user: true -zabbix_php_fpm_conf_enable_group: true -zabbix_php_fpm_conf_mode: "0664" -zabbix_php_fpm_conf_enable_mode: true -zabbix_php_install_state: present +zabbix_server_name: "{{ inventory_hostname }}" +zabbix_server_hostname: "{{ inventory_hostname }}" +zabbix_server_listenport: 10051 -zabbix_apache_vhost_port: 80 -zabbix_apache_vhost_tls_port: 443 -zabbix_apache_vhost_listen_ip: "*" -zabbix_apache_tls: false -zabbix_apache_redirect: false -zabbix_apache_tls_crt: /etc/pki/server.crt -zabbix_apache_tls_key: /etc/pki/server.key -zabbix_apache_tls_chain: -zabbix_apache_can_connect_ldap: false -zabbix_apache_include_custom_fragment: true -zabbix_apache_SSLPassPhraseDialog: exec:/usr/libexec/httpd-ssl-pass-dialog -zabbix_apache_SSLSessionCache: shmcb:/run/httpd/sslcache(512000) -zabbix_apache_SSLSessionCacheTimeout: 300 -zabbix_apache_SSLCryptoDevice: builtin +zabbix_web_vhost_port: 80 +zabbix_web_vhost_tls_port: 443 +zabbix_web_vhost_listen_ip: "*" +zabbix_web_tls: false +zabbix_timezone: Europe/Amsterdam +zabbix_php_fpm_conf_listen: true +# zabbix_web_tls_crt: /etc/pki/server.crt +# zabbix_web_tls_key: /etc/pki/server.key +# zabbix_web_tls_chain: +# zabbix_web_SSLPassPhraseDialog: exec:/usr/libexec/httpd-ssl-pass-dialog +# zabbix_web_SSLSessionCache: shmcb:/run/httpd/sslcache(512000) +# zabbix_web_SSLSessionCacheTimeout: 300 +# zabbix_web_SSLCryptoDevice: builtin +# zabbix_web_max_execution_time: 300 +# zabbix_web_memory_limit: 128M +# zabbix_web_post_max_size: 16M +# zabbix_web_upload_max_filesize: 2M +# zabbix_web_max_input_time: 300 +# zabbix_web_max_input_vars: 10000 zabbix_apache_custom_includes: [] -zabbix_nginx_vhost_port: 80 -zabbix_nginx_vhost_tls_port: 443 -zabbix_nginx_tls: false -zabbix_nginx_redirect: false -zabbix_nginx_tls_session_timeout: 1d -zabbix_nginx_tls_session_cache: shared:MySSL:10m -zabbix_nginx_tls_session_tickets: !!str off -zabbix_nginx_tls_protocols: TLSv1.2 -zabbix_nginx_tls_ciphers: ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384 - -zabbix_letsencrypt: false -zabbix_letsencrypt_webroot_path: /var/www/letsencrypt -zabbix_letsencrypt_webroot_mode: 0755 +# Database +zabbix_server_database: pgsql +zabbix_server_dbhost: localhost +zabbix_server_dbname: zabbix-server +zabbix_server_dbuser: zabbix-server +zabbix_server_dbpassword: zabbix-server +zabbix_server_dbport: 5432 +zabbix_server_dbencryption: false +zabbix_server_dbverifyhost: false +zabbix_server_dbschema: +# Yum/APT Variables +zabbix_web_apt_priority: +zabbix_web_version_minor: "*" zabbix_repo_yum_gpgcheck: 0 zabbix_repo_yum_schema: https -zabbix_repo_yum_disabled: "*" -zabbix_repo_yum_enabled: [] +zabbix_repo_deb_component: main +zabbix_web_disable_repo: + - epel zabbix_repo_yum: - name: zabbix description: Zabbix Official Repository - $basearch - baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/" - gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" + baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_web_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/" + gpgcheck: "{{ zabbix_repo_yum_gpgcheck | default('0') }}" mode: "0644" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX state: present @@ -81,41 +68,10 @@ zabbix_repo_yum: description: Zabbix Official Repository non-supported - $basearch baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/non-supported/rhel/{{ ansible_distribution_major_version }}/$basearch/" mode: "0644" - gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" + gpgcheck: "{{ zabbix_repo_yum_gpgcheck | default('0') }}" gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX state: present -zabbix_5_repo_yum: - - name: zabbix-frontend - description: Zabbix Official Repository - $basearch - baseurl: "{{ zabbix_repo_yum_schema }}://repo.zabbix.com/zabbix/{{ zabbix_version | regex_search('^[0-9]+.[0-9]+') }}/rhel/{{ ansible_distribution_major_version }}/$basearch/frontend/" - mode: "0644" - gpgcheck: "{{ zabbix_repo_yum_gpgcheck }}" - gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX - state: present - -zabbix_web_max_execution_time: 300 -zabbix_web_memory_limit: 128M -zabbix_web_post_max_size: 16M -zabbix_web_upload_max_filesize: 2M -zabbix_web_max_input_time: 300 -zabbix_web_max_input_vars: 10000 - -# Database -zabbix_server_database: pgsql -zabbix_server_database_long: postgresql -zabbix_server_name: "{{ inventory_hostname }}" -zabbix_server_hostname: "{{ inventory_hostname }}" -zabbix_server_listenport: 10051 -zabbix_server_dbhost: localhost -zabbix_server_dbname: zabbix-server -zabbix_server_dbuser: zabbix-server -zabbix_server_dbpassword: zabbix-server -zabbix_server_dbport: 5432 -zabbix_server_dbencryption: false -zabbix_server_dbverifyhost: false -zabbix_server_dbschema: - # Elasticsearch # zabbix_server_history_url: # - "'uint' => 'http://localhost:9200'" @@ -130,15 +86,13 @@ zabbix_server_history_types: - "uint" - "dbl" -selinux_allow_zabbix_can_network: false -_zabbix_web_apache_php_addition: false +zabbix_selinux: false +# selinux_allow_zabbix_can_network: false +# zabbix_apache_can_connect_ldap: false # SAML certificates # zabbix_saml_idp_crt: # zabbix_saml_sp_crt: # zabbix_saml_sp_key: -# When the `geerlingguys apache role` is not provided, we have some defaults. -apache_ssl_cipher_suite: ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384 -apache_ssl_protocol: all -SSLv3 -TLSv1 -TLSv1.1 -apache_vhosts_version: "2.4" +# zabbix_web_ssl_cipher_suite: ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/handlers/main.yml b/ansible_collections/community/zabbix/roles/zabbix_web/handlers/main.yml index 0d0974632..e97787b12 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/handlers/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/handlers/main.yml @@ -1,53 +1,43 @@ --- - - name: restart apache - service: + ansible.builtin.service: name: "{{ _apache_service }}" state: restarted enabled: true become: true when: - - zabbix_websrv == 'apache' + - zabbix_web_http_server == 'apache' - name: test nginx config listen: restart nginx - command: nginx -t + ansible.builtin.command: nginx -t register: zabbix_nginx_cfg_check notify: restart nginx tested become: true when: - - zabbix_websrv == 'nginx' + - zabbix_web_http_server == 'nginx' - name: restart nginx tested - service: + ansible.builtin.service: name: nginx state: restarted enabled: true become: true when: - - zabbix_websrv == 'nginx' + - zabbix_web_http_server == 'nginx' - zabbix_nginx_cfg_check.rc == 0 -- name: restart redhat-php-fpm - service: - name: "{{ 'rh-php72-php-fpm' if zabbix_php_fpm else 'php-fpm' }}" - state: restarted - enabled: true - become: true - when: - - zabbix_version is version('5.0', '>=') - - name: restart php-fpm-version - service: - name: php{{ zabbix_php_version }}-fpm + ansible.builtin.service: + name: php{{ zabbix_web_php_installed_version }}-fpm state: restarted enabled: true become: true when: - - zabbix_version is version('5.0', '>=') + - zabbix_web_version is version('5.0', '>=') - name: "clean repo files from proxy creds" - shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true + ansible.builtin.shell: ls /etc/yum.repos.d/zabbix* && sed -i 's/^proxy =.*//' /etc/yum.repos.d/zabbix* || true become: true when: - ansible_os_family == 'RedHat' diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/Debian.yml index 8a27b841c..ae1c7de26 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/Debian.yml @@ -1,63 +1,149 @@ --- +- name: "Debian | Set PHP Dependencies" + ansible.builtin.set_fact: + zabbix_web_php_dependencies: "{{ _apache_php_dependencies if zabbix_web_http_server == 'apache' else _nginx_php_dependencies }}" + tags: + - config -- name: "Include Zabbix gpg ids" - include_vars: zabbix.yml +- name: "Debian | Set some variables" + ansible.builtin.set_fact: + zabbix_short_version: "{{ zabbix_web_version | regex_replace('\\.', '') }}" + zabbix_underscore_version: "{{ zabbix_web_version | regex_replace('\\.', '_') }}" + zabbix_python_prefix: "python{% if ansible_python_version is version('3', '>=') %}3{% endif %}" + tags: + - always -- name: "Set short version name" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" +- name: "Debian | Update ansible_lsb fact" + ansible.builtin.setup: + gather_subset: + - lsb -- name: "Debian | Install gpg key" - apt_key: - id: "{{ sign_keys[zabbix_short_version][ansible_distribution_release]['sign_key'] }}" - url: http://repo.zabbix.com/zabbix-official-repo.key +- name: "Debian | Installing lsb-release" + ansible.builtin.apt: + pkg: lsb-release + update_cache: true + cache_valid_time: 3600 + force: true + state: present + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + become: true + tags: + - install + +- name: "Debian | Repo URL" + ansible.builtin.set_fact: + zabbix_repo_deb_url: "{{ _zabbix_repo_deb_url }}/{{ ansible_lsb.id.lower() }}{{ '-arm64' if ansible_machine == 'aarch64' and ansible_lsb.id == 'debian' else ''}}" when: - - zabbix_repo == "zabbix" + - zabbix_repo_deb_url is undefined + tags: + - always + +- name: "Debian | Install PHP Dependencies" + ansible.builtin.apt: + pkg: "{{ zabbix_web_php_dependencies }}" + state: "present" + update_cache: true + cache_valid_time: 0 + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_web_php_dependencies_install + until: zabbix_web_php_dependencies_install is succeeded become: true tags: - - zabbix-web - - init - - config + - install + - dependencies -- name: "Debian | Installing repository {{ ansible_distribution }}" - apt_repository: - repo: "{{ item }} http://repo.zabbix.com/zabbix/{{ zabbix_version }}/{{ ansible_distribution.lower() }}/ {{ ansible_distribution_release }} main" - state: present +- name: "Debian | Install PgSQL Dependencies" + ansible.builtin.apt: + pkg: "php{{ zabbix_web_php_installed_version }}-pgsql" + state: "present" + update_cache: true + cache_valid_time: 0 + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_web_php_dependencies_install + until: zabbix_web_php_dependencies_install is succeeded + become: true + when: zabbix_server_database == 'pgsql' + tags: + - install + - dependencies + - database + +# In releases older than Debian 12 and Ubuntu 22.04, /etc/apt/keyrings does not exist by default. +# It SHOULD be created with permissions 0755 if it is needed and does not already exist. +# See: https://wiki.debian.org/DebianRepository/UseThirdParty +- name: "Debian | Create /etc/apt/keyrings/ on older versions" + ansible.builtin.file: + path: /etc/apt/keyrings/ + state: directory + mode: "0755" become: true when: - - zabbix_repo == "zabbix" - - ansible_machine != "aarch64" - with_items: - - deb-src - - deb + - (ansible_distribution == "Ubuntu" and ansible_distribution_major_version < "22") or + (ansible_distribution == "Debian" and ansible_distribution_major_version < "12") + +- name: "Debian | Download gpg key" + ansible.builtin.get_url: + url: http://repo.zabbix.com/zabbix-official-repo.key + dest: "{{ zabbix_gpg_key }}" + mode: "0644" + force: true + become: true tags: - - zabbix-web - - init - - config + - install - name: "Debian | Installing repository {{ ansible_distribution }}" - apt_repository: - repo: "{{ item }} http://repo.zabbix.com/zabbix/{{ zabbix_version }}/{{ ansible_distribution.lower() }}-arm64/ {{ ansible_distribution_release }} main" - state: present + ansible.builtin.copy: + dest: /etc/apt/sources.list.d/zabbix.sources + owner: root + group: root + mode: 0644 + content: | + Types: deb deb-src + Enabled: yes + URIs: {{ zabbix_repo_deb_url }} + Suites: {{ ansible_distribution_release }} + Components: {{ zabbix_repo_deb_component }} + Architectures: {{ 'amd64' if ansible_machine != 'aarch64' else 'arm64'}} + Signed-By: {{ zabbix_gpg_key }} become: true + tags: + - install + +- name: "Debian | Create /etc/apt/preferences.d/" + ansible.builtin.file: + path: /etc/apt/preferences.d/ + state: directory + mode: "0755" when: - - zabbix_repo == "zabbix" - - ansible_machine == "aarch64" - with_items: - - deb-src - - deb + - zabbix_web_apt_priority | int + become: true tags: - - zabbix-web - - init - - config + - install -- name: "Debian | Install PHP apart from zabbix-frontend-php deps" - include_tasks: "php_Debian.yml" - when: zabbix_php_install +- name: "Debian | Configuring the weight for APT" + ansible.builtin.copy: + dest: "/etc/apt/preferences.d/zabbix_server-{{ zabbix_proxy_database }}" + content: | + Package: zabbix_server-{{ zabbix_proxy_database }} + Pin: origin repo.zabbix.com + Pin-Priority: {{ zabbix_web_apt_priority }} + owner: root + mode: "0644" + when: + - zabbix_web_apt_priority | int + become: true + tags: + - install - name: "Debian | Install zabbix-web" - apt: - pkg: "zabbix-frontend-php{{ '-deprecated' if zabbix_php_frontend_deprecated else '' }}" + ansible.builtin.apt: + pkg: "zabbix-frontend-php" state: "{{ zabbix_web_package_state }}" update_cache: true cache_valid_time: 0 @@ -68,41 +154,13 @@ until: zabbix_web_package_install is succeeded become: true tags: - - zabbix-web - - init - - config + - install - name: "Debian | Link graphfont.ttf (workaround ZBX-10467)" - file: - src: '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' - path: '/usr/share/zabbix/fonts/graphfont.ttf' + ansible.builtin.file: + src: "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf" + path: "/usr/share/zabbix/fonts/graphfont.ttf" state: link - tags: - - zabbix-web - - init - - config - -- name: "Debian | Install PHP" - template: - src: php-fpm.conf.j2 - dest: "{{ zabbix_php_fpm_dir }}/zabbix.conf" - owner: "{{ _apache_user }}" - group: "{{ _apache_group }}" - mode: 0644 become: true - when: - - zabbix_vhost - notify: - - restart php-fpm-version - -- name: "Including Apache Configuration" - include_tasks: apache_Debian.yml - vars: - zabbix_apache_servername: "{{ zabbix_websrv_servername }}" - when: - - zabbix_websrv == 'apache' - -- name: "Configure SELinux when enabled" - include_tasks: selinux.yml - when: - - zabbix_selinux | bool + tags: + - install diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/RedHat.yml index bcd4dd666..30871017e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/RedHat.yml @@ -1,183 +1,59 @@ ---- -# Tasks specific for RedHat systems +- name: "RedHat | Setting Short PHP Version" + ansible.builtin.set_fact: + zabbix_web_php_installed_version: "{{ zabbix_web_php_installed_version | regex_replace('\\.', '') }}" + tags: + - always - name: "RedHat | Install basic repo file" - yum_repository: + ansible.builtin.yum_repository: name: "{{ item.name }}" - description: "{{ item.description }}" + description: "{{ item.description | default(omit) }}" baseurl: "{{ item.baseurl }}" - gpgcheck: "{{ item.gpgcheck }}" - gpgkey: "{{ item.gpgkey }}" + gpgcheck: "{{ item.gpgcheck | default(omit) }}" + gpgkey: "{{ item.gpgkey | default(omit) }}" mode: "{{ item.mode | default('0644') }}" - priority: "{{ item.priority | default('98') }}" + priority: "{{ item.priority | default('99') }}" state: "{{ item.state | default('present') }}" proxy: "{{ zabbix_http_proxy | default(omit) }}" with_items: "{{ zabbix_repo_yum }}" register: yum_repo_installed become: true - when: - zabbix_repo == "zabbix" - notify: - - "clean repo files from proxy creds" - tags: - - zabbix-web - -- name: "RedHat | Install basic repo file (Zabbix 5.x)" - yum_repository: - name: "{{ item.name }}" - description: "{{ item.description }}" - baseurl: "{{ item.baseurl }}" - gpgcheck: "{{ item.gpgcheck }}" - gpgkey: "{{ item.gpgkey }}" - mode: "{{ item.mode | default('0644') }}" - priority: "{{ item.priority | default('98') }}" - state: "{{ item.state | default('present') }}" - proxy: "{{ zabbix_http_proxy | default(omit) }}" - with_items: "{{ zabbix_5_repo_yum }}" - become: true - when: - - zabbix_repo == "zabbix" - - zabbix_version is version('5.0', '>=') - - ansible_distribution_major_version != '8' - - ansible_distribution_major_version != '9' notify: - "clean repo files from proxy creds" tags: - - zabbix-web - -- name: "RedHat | Install zabbix-web dependency (Zabbix 5.x) (CentOS)" - yum: - pkg: - - centos-release-scl - state: "{{ zabbix_web_package_state }}" - update_cache: true - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_web_dependency_package_install - until: zabbix_web_dependency_package_install is succeeded - become: true - when: - - zabbix_version is version('5.0', '>=') - - zabbix_web_centos_release - - ansible_distribution_major_version != '9' - - ansible_distribution_major_version != '8' - - ansible_distribution == "CentOS" - tags: - - zabbix-web - -- name: "RedHat | Install zabbix-web dependency (Zabbix 5.x) (RHEL)" - yum: - pkg: - - scl-utils - - scl-utils-build - state: "{{ zabbix_web_package_state }}" - update_cache: true - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" - environment: - http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" - https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" - register: zabbix_web_dependency_package_install - until: zabbix_web_dependency_package_install is succeeded - become: true - when: - - zabbix_version is version('5.0', '>=') - - zabbix_web_centos_release - - ansible_distribution_major_version != '9' - - ansible_distribution_major_version != '8' - - ansible_distribution == "RedHat" - tags: - - zabbix-web + - install -- name: "RedHat | Install zabbix-web (Zabbix 5.x)" - yum: - pkg: - - zabbix-apache-conf-scl-{{ zabbix_web_version }}.{{ zabbix_web_version_minor }} +- name: "RedHat | Install zabbix-web-{{ zabbix_server_database }}" + ansible.builtin.yum: + name: + - "zabbix-web-{{ zabbix_server_database }}" state: "{{ zabbix_web_package_state }}" update_cache: true - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_web_disable_repo | default(omit) }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" register: zabbix_web_package_install until: zabbix_web_package_install is succeeded become: true - when: - - zabbix_version is version('5.0', '>=') - - ansible_distribution_major_version != '9' - - ansible_distribution_major_version != '8' - - zabbix_websrv == 'apache' tags: - - zabbix-web + - install -- name: "RedHat | Install zabbix-web-{{ zabbix_server_database }}" - yum: - pkg: zabbix-web-{{ zabbix_server_database }}{{ '-scl' if zabbix_version is version('5.0', '>=') and ansible_distribution_major_version|int < 8 else '' }}-{{ zabbix_web_version }}.{{ zabbix_web_version_minor }} +- name: "RedHat | Install zabbix-web-configuration" + ansible.builtin.yum: + name: + - "zabbix-{{ zabbix_web_http_server }}-conf" state: "{{ zabbix_web_package_state }}" update_cache: true - disablerepo: "{{ '*' if (zabbix_repo_yum_enabled | length>0) else omit }}" - enablerepo: "{{ zabbix_repo_yum_enabled if zabbix_repo_yum_enabled is iterable and (zabbix_repo_yum_enabled | length>0) else omit }}" + disablerepo: "{{ zabbix_web_disable_repo | default(omit) }}" environment: http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" register: zabbix_web_package_install until: zabbix_web_package_install is succeeded become: true - tags: - - zabbix-web - -- name: RedHat 9 | Install PHP" - package: - name: php - state: "{{ zabbix_php_install_state }}" when: - - zabbix_version is version('6.0', '>=') + - zabbix_web_version is version('6.0', '!=') - ansible_distribution_major_version == '9' - - zabbix_vhost - -- name: "RedHat | Install PHP" - template: - src: php-fpm.conf.j2 - dest: "{{ zabbix_php_fpm_dir }}/zabbix.conf" - owner: "{{ zabbix_web_conf_web_user }}" - group: "{{ zabbix_web_conf_web_group }}" - mode: 0644 - become: true - when: - - zabbix_vhost - notify: - - restart redhat-php-fpm - -- include_tasks: apache_RedHat.yml - vars: - zabbix_apache_servername: "{{ zabbix_websrv_servername }}" - when: - - zabbix_websrv == 'apache' - -- name: "RedHat | Install Nginx vhost" - template: - src: nginx_vhost.conf.j2 - dest: /etc/nginx/conf.d/zabbix.conf - owner: root - group: root - mode: 0644 - when: - - zabbix_vhost - - zabbix_websrv == 'nginx' - become: true - notify: - - restart nginx tags: - - zabbix-web - - init - - config - - nginx - -- name: "Configure SELinux when enabled" - include_tasks: selinux.yml - when: - - zabbix_selinux | bool + - install diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/access.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/access.yml deleted file mode 100644 index f02a6ebe4..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/access.yml +++ /dev/null @@ -1,32 +0,0 @@ ---- -- name: "htpasswd | check Python version to set prefix variable" - set_fact: - zabbix_python_prefix: "python{% if ansible_python_version is version_compare('3', '>=') %}3{% endif %}" - when: - - zabbix_web_htpasswd is defined - - zabbix_web_htpasswd - - zabbix_web_htpasswd_users is defined - -- name: "htpasswd | install passlib for Python interpreter" - package: - name: "{{ zabbix_python_prefix }}-passlib" - state: present - when: - - zabbix_web_htpasswd is defined - - zabbix_web_htpasswd - - zabbix_web_htpasswd_users is defined - -- name: "htpasswd | manage HTTP authentication controls" - community.general.htpasswd: - path: "{{ zabbix_web_htpasswd_file }}" - name: "{{ item.value.htpasswd_user }}" - password: "{{ item.value.htpasswd_pass }}" - group: www-data - state: present - loop_control: - label: "{{ item.value.htpasswd_user }}" - with_dict: "{{ zabbix_web_htpasswd_users }}" - when: - - zabbix_web_htpasswd is defined - - zabbix_web_htpasswd - - zabbix_web_htpasswd_users is defined diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache.yml index f33b9b765..7e55fe3e9 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache.yml @@ -1,6 +1,47 @@ --- +- name: Setting Web Server Facts + ansible.builtin.set_fact: + zabbix_web_user: "{{ zabbix_web_user if zabbix_web_user is defined else _apache_user }}" + zabbix_web_group: "{{ zabbix_web_group if zabbix_web_group is defined else _apache_group }}" + zabbix_web_vhost_location: "{{ zabbix_web_vhost_location if zabbix_web_vhost_location is defined else _apache_vhost_location }}" + tags: + - always + +- name: "Apache | Installing Zabbix Apache Conf" + block: + - name: "Debian | Install zabbix-apache-conf" + ansible.builtin.apt: + pkg: "zabbix-apache-conf" + state: "{{ zabbix_web_package_state }}" + update_cache: true + cache_valid_time: 0 + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_apache_conf_install + until: zabbix_apache_conf_install is succeeded + become: true + when: ansible_os_family == "Debian" + + - name: "RedHat | Install zabbix-apache-conf" + ansible.builtin.yum: + name: + - "zabbix-apache-conf-{{ zabbix_web_version }}.{{ zabbix_web_version_minor }}" + state: "{{ zabbix_web_package_state }}" + update_cache: true + disablerepo: "{{ zabbix_agent_disable_repo | default(omit) }}" + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_apache_conf_install + until: zabbix_apache_conf_install is succeeded + become: true + when: ansible_os_family == "RedHat" + tags: + - install + - name: "Apache | Get Apache version" - shell: | + ansible.builtin.shell: | PATH=/usr/sbin:$PATH set -o pipefail apachectl -v | grep 'version' | awk -F '/' '{ print $2 }'| awk '{ print $1 }' | cut -c 1-3 @@ -10,26 +51,37 @@ args: executable: /bin/bash tags: - - zabbix-web + - config - name: "Apache | Set correct apache_version" - set_fact: + ansible.builtin.set_fact: apache_version: "{{ apachectl_version.stdout }}" tags: - - zabbix-web + - config -- name: "Set some" - set_fact: - _zabbix_web_apache_php_addition: true - when: - - zabbix_version is version('4.4', '<=') +- name: "Apache | Install apache vhost" + ansible.builtin.template: + src: apache_vhost.conf.j2 + dest: "{{ zabbix_web_vhost_location }}" + owner: "{{ zabbix_web_user }}" + group: "{{ zabbix_web_group }}" + mode: 0644 + when: zabbix_web_create_vhost + become: true + notify: + - restart apache tags: - - zabbix-web + - config -- name: "Set some" - set_fact: - _zabbix_web_apache_php_addition: true - when: - - ansible_os_family == "Debian" +- name: "Apache | Enable Site (Debian Only)" + ansible.builtin.file: + src: "{{ zabbix_web_vhost_location }}" + dest: /etc/apache2/sites-enabled/zabbix.conf + state: link + owner: "{{ zabbix_web_user }}" + group: "{{ zabbix_web_group }}" + mode: 0644 + become: true + when: ansible_os_family == "Debian" and zabbix_web_create_vhost tags: - - zabbix-web + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache_Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache_Debian.yml deleted file mode 100644 index 732feaea9..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache_Debian.yml +++ /dev/null @@ -1,54 +0,0 @@ ---- - -- name: "Debian | Install legacy PHP integration for Apache" - apt: - state: present - update_cache: true - cache_valid_time: 3600 - name: - - libapache2-mod-php - become: true - -- name: "Debian | install apache vhost" - template: - src: apache_vhost.conf.j2 - dest: /etc/apache2/sites-available/zabbix.conf - owner: "{{ zabbix_web_conf_web_user }}" - group: "{{ zabbix_web_conf_web_group }}" - mode: 0644 - when: zabbix_vhost - become: true - notify: - - restart apache - tags: - - zabbix-web - - init - - config - - apache - -- name: "Debian | Remove provided zabbix.conf files" - file: - path: "{{ item }}" - state: absent - when: zabbix_vhost - become: true - with_items: - - /etc/apache2/conf-available/zabbix.conf - - /etc/apache2/conf-enabled/zabbix.conf - -- name: "Debian | enable apache vhost" - file: - src: /etc/apache2/sites-available/zabbix.conf - dest: /etc/apache2/sites-enabled/zabbix.conf - owner: "{{ zabbix_web_conf_web_user }}" - group: "{{ zabbix_web_conf_web_group }}" - state: link - when: zabbix_vhost - become: true - notify: - - restart apache - tags: - - zabbix-server - - init - - config - - apache diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache_RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache_RedHat.yml deleted file mode 100644 index 3a271331d..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/apache_RedHat.yml +++ /dev/null @@ -1,17 +0,0 @@ ---- - -- include_tasks: apache.yml - -- name: "RedHat | Install apache vhost" - template: - src: apache_vhost.conf.j2 - dest: /etc/httpd/conf.d/zabbix.conf - owner: "{{ zabbix_web_conf_web_user }}" - group: "{{ zabbix_web_conf_web_group }}" - mode: 0644 - when: zabbix_vhost - become: true - notify: - - restart apache - tags: - - zabbix-server diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/main.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/main.yml index fad607b1d..b82d8486b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/main.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/main.yml @@ -1,103 +1,97 @@ --- -# tasks file for wdijkerman.zabbix-web - - name: "Include OS-specific variables" - include_vars: "{{ ansible_os_family }}.yml" + ansible.builtin.include_vars: "{{ ansible_os_family }}.yml" tags: - always - name: Determine Latest Supported Zabbix Version - set_fact: - zabbix_web_version: "{{ zabbix_valid_web_versions[ansible_distribution_major_version][0] | default(6.0) }}" + ansible.builtin.set_fact: + zabbix_web_version: "{{ zabbix_valid_web_versions[ansible_distribution_major_version][0] | default(6.4) }}" when: zabbix_web_version is not defined - -- name: "Include distribution and version-specific vars" - include_vars: "{{ item }}" - with_first_found: - - files: - - "{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml" - - "{{ ansible_os_family }}-{{ ansible_distribution_major_version }}.yml" tags: - always -- name: "Set some versions" - set_fact: - zabbix_short_version: "{{ zabbix_version | regex_replace('\\.', '') }}" - zabbix_php_version: "{{ zabbix_php_version if zabbix_php_version is defined else _zabbix_php_version }}" - _zabbix_php_package_prefix: "" +- name: Set More Variables + ansible.builtin.set_fact: + zabbix_valid_version: "{{ zabbix_web_version|float in zabbix_valid_web_versions[ansible_distribution_major_version] }}" + zabbix_db_type_long: "{{ 'postgresql' if zabbix_server_database == 'pgsql' else 'mysql' }}" tags: - always -- name: "Set default PHP-FPM variables" - set_fact: - zabbix_php_fpm_dir: "{{ zabbix_php_fpm_dir if zabbix_php_fpm_dir is defined else _php_fpm_dir }}" - zabbix_php_fpm_session: "{{ zabbix_php_fpm_session if zabbix_php_fpm_session is defined else _php_fpm_session }}" - zabbix_php_fpm_listen: "{{ zabbix_php_fpm_listen if zabbix_php_fpm_listen is defined else _php_fpm_listen }}" - when: - - not zabbix_php_fpm - -- name: "Set default PHP-FPM variables specific RH provided" - set_fact: - zabbix_php_fpm_dir: "{{ zabbix_php_fpm_dir if zabbix_php_fpm_dir is defined else _php_fpm_dir }}" - zabbix_php_fpm_session: "{{ zabbix_php_fpm_session if zabbix_php_fpm_session is defined else _zabbix_php_fpm_session }}" - zabbix_php_fpm_listen: "{{ zabbix_php_fpm_listen if zabbix_php_fpm_listen is defined else _zabbix_php_fpm_listen }}" - when: - - zabbix_php_fpm - - ansible_os_family == "RedHat" - -- name: "Set websrv specific variables (Apache)" - set_fact: - zabbix_web_conf_web_user: "{{ zabbix_web_conf_web_user if zabbix_web_conf_web_user is defined else _apache_user }}" - zabbix_web_conf_web_group: "{{ zabbix_web_conf_web_group if zabbix_web_conf_web_group is defined else _apache_group }}" - when: - - zabbix_websrv == 'apache' +- name: Stopping Install of Invalid Version + ansible.builtin.fail: + msg: Zabbix version {{ zabbix_web_version }} is not supported on {{ ansible_distribution }} {{ ansible_distribution_major_version }} + when: not zabbix_valid_version + tags: + - always -- include_tasks: nginx.yml - when: - - zabbix_websrv == 'nginx' +- name: Determine PHP Version + ansible.builtin.shell: php --version | head -1 | awk '{ print $2 }' | awk -F '.' '{print $1"."$2}' + register: _zabbix_web_php_installed_version + changed_when: false + tags: + - config + - install -- name: "Install the correct repository" - include_tasks: "RedHat.yml" - when: ansible_os_family == "RedHat" +- name: Set PHP Version + ansible.builtin.set_fact: + zabbix_web_php_installed_version: "{{ _zabbix_web_php_installed_version.stdout }}" tags: - - zabbix-web + - config + - install -- name: "Install the correct repository" - include_tasks: "Debian.yml" - when: ansible_os_family == "Debian" +- name: Set PHP Variables + ansible.builtin.set_fact: + zabbix_php_fpm_listen: "{{ zabbix_php_fpm_listen if zabbix_php_fpm_listen is defined else _zabbix_php_fpm_listen }}" + zabbix_php_fpm_dir: "{{ zabbix_php_fpm_dir if zabbix_php_fpm_dir is defined else _php_fpm_dir }}" + zabbix_php_fpm_session: "{{ zabbix_php_fpm_session if zabbix_php_fpm_session is defined else _php_fpm_session }}" tags: - - zabbix-web + - config + - install + +- name: Include OS Specific Tasks + ansible.builtin.include_tasks: "{{ ansible_os_family }}.yml" + +- name: "Install the web server specific tasks" + ansible.builtin.include_tasks: "{{ zabbix_web_http_server }}.yml" - name: "Create zabbix-web directory" - file: + ansible.builtin.file: path: /etc/zabbix/web - owner: "{{ zabbix_web_conf_web_user }}" - group: "{{ zabbix_web_conf_web_group }}" + owner: "{{ zabbix_web_user }}" + group: "{{ zabbix_web_group }}" state: directory mode: 0755 + become: true tags: - - zabbix-web - - init + - install - config - name: "Configure zabbix-web" - template: + ansible.builtin.template: src: zabbix.conf.php.j2 dest: /etc/zabbix/web/zabbix.conf.php - owner: "{{ zabbix_web_conf_web_user }}" - group: "{{ zabbix_web_conf_web_group }}" + owner: "{{ zabbix_web_user }}" + group: "{{ zabbix_web_group }}" mode: "{{ zabbix_web_conf_mode }}" + become: true notify: - - restart apache + - "restart {{ zabbix_web_http_server }}" tags: - - zabbix-web - - init - config -- include_tasks: access.yml +- name: "Debian | Install PHP" + ansible.builtin.template: + src: php-fpm.conf.j2 + dest: "{{ zabbix_php_fpm_dir }}/zabbix.conf" + owner: "{{ zabbix_web_user }}" + group: "{{ zabbix_web_group }}" + mode: 0644 + become: true when: - - zabbix_web_htpasswd + - zabbix_web_create_php_fpm + - ansible_os_family == "Debian" + notify: + - restart php-fpm-version tags: - - zabbix-web - - init - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/nginx.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/nginx.yml index 9e4ec41f1..1f50263ca 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/nginx.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/nginx.yml @@ -1,153 +1,59 @@ --- - name: "Nginx | Set websrv specific variables" - set_fact: - zabbix_web_conf_web_user: "{{ zabbix_web_conf_web_user if zabbix_web_conf_web_user is defined else _nginx_user }}" - zabbix_web_conf_web_group: "{{ zabbix_web_conf_web_group if zabbix_web_conf_web_group is defined else _nginx_group }}" - zabbix_nginx_config_path: "{{ zabbix_nginx_config_path if zabbix_nginx_config_path is defined else _nginx_config_path }}" + ansible.builtin.set_fact: + zabbix_web_user: "{{ zabbix_web_user if zabbix_web_user is defined else _nginx_user }}" + zabbix_web_group: "{{ zabbix_web_group if zabbix_web_group is defined else _nginx_group }}" + zabbix_web_vhost_location: "{{ zabbix_web_vhost_location if zabbix_web_vhost_location is defined else _nginx_vhost_location }}" zabbix_nginx_log_path: "{{ zabbix_nginx_log_path if zabbix_nginx_log_path is defined else _nginx_log_path }}" zabbix_nginx_service: "{{ zabbix_nginx_service if zabbix_nginx_service is defined else _nginx_service }}" - zabbix_nginx_tls_crt: "{{ zabbix_nginx_tls_crt if zabbix_nginx_tls_crt is defined else _nginx_tls_crt }}" - zabbix_nginx_tls_key: "{{ zabbix_nginx_tls_key if zabbix_nginx_tls_key is defined else _nginx_tls_key }}" - zabbix_nginx_tls_dhparam: "{{ zabbix_nginx_tls_dhparam if zabbix_nginx_tls_dhparam is defined else _nginx_tls_dhparam }}" - zabbix_apache_service: "{{ zabbix_apache_service if zabbix_apache_service is defined else _apache_service }}" - -- name: "Nginx | Check Apache service if same ports" - command: systemctl status "{{ zabbix_apache_service }}" - failed_when: false - register: zabbix_apache_service_check - changed_when: zabbix_apache_service_check.rc == 0 - check_mode: false - when: - - zabbix_apache_vhost_port == zabbix_nginx_vhost_port - - zabbix_apache_vhost_tls_port == zabbix_nginx_vhost_tls_port - -- name: "Nginx | Stop Apache running on same ports" - service: - name: "{{ zabbix_apache_service }}" - state: stopped - enabled: false tags: - - zabbix-web - when: - - zabbix_apache_vhost_port == zabbix_nginx_vhost_port - - zabbix_apache_vhost_tls_port == zabbix_nginx_vhost_tls_port - - zabbix_apache_service_check.rc == 0 - -- name: "Nginx | Debian | Install Nginx and ssl-cert packages" - # README don't go for HTTP2 with nginx-full yet due to: - # https://support.zabbix.com/browse/ZBXNEXT-4670 - apt: - state: present - name: - - nginx-light - - ssl-cert - when: ansible_os_family == "Debian" - -- name: "Nginx | RedHat | Install Nginx packages" - yum: - state: present - name: - - nginx - when: ansible_os_family == "RedHat" - -- name: "Nginx | Start and enable service" - service: - name: "{{ zabbix_nginx_service }}" - state: started - enabled: true - -- name: "Nginx | Install OpenSSL package for DH parameters" - package: - name: openssl - state: present - -- name: "Nginx | Generate SSL DH parameters" - command: "openssl dhparam -out {{ zabbix_nginx_tls_dhparam }} {{ zabbix_nginx_tls_dhparam_bits | default('2048') }}" - args: - creates: "{{ zabbix_nginx_tls_dhparam }}" - -- name: "Let's Encrypt | check for certificate created by certbot" - stat: - path: "/etc/letsencrypt/live/{{ zabbix_websrv_servername }}/fullchain.pem" - register: zabbix_letsencrypt_cert - failed_when: false - when: zabbix_letsencrypt - -- name: "Let's Encrypt | Create directory for certbot webroot if not exist" - file: - path: "{{ zabbix_letsencrypt_webroot_path }}" - mode: "{{ zabbix_letsencrypt_webroot_mode }}" - state: directory - when: - - zabbix_letsencrypt - become: true + - config + - install + +- name: "Nginx | Installing Zabbix Nginx Conf" + block: + - name: "Debian | Install zabbix-nginx-conf" + ansible.builtin.apt: + pkg: "zabbix-nginx-conf" + state: "{{ zabbix_web_package_state }}" + update_cache: true + cache_valid_time: 0 + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_apache_conf_install + until: zabbix_apache_conf_install is succeeded + become: true + when: ansible_os_family == "Debian" + + - name: "RedHat | Install zabbix-nginx-conf" + ansible.builtin.yum: + name: + - "zabbix-nginx-conf" + state: "{{ zabbix_web_package_state }}" + update_cache: true + disablerepo: "{{ zabbix_agent_disable_repo | default(omit) }}" + environment: + http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}" + https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}" + register: zabbix_apache_conf_install + until: zabbix_apache_conf_install is succeeded + become: true + when: ansible_os_family == "RedHat" + tags: + - install - name: "Nginx | Install vhost in conf.d" - template: + ansible.builtin.template: src: nginx_vhost.conf.j2 - dest: "{{ zabbix_nginx_config_path }}/zabbix.conf" - owner: root - group: root + dest: "{{ zabbix_web_vhost_location }}" + owner: "{{ zabbix_web_user }}" + group: "{{ zabbix_web_group }}" mode: 0644 when: - - zabbix_vhost - become: true - notify: - - restart nginx - -- name: "Let's Encrypt | Check if zabbix_websrv_servername is resolvable" - set_fact: - zabbix_websrv_servername_ip: "{{ lookup('dig', 'qtype=A', zabbix_websrv_servername) }}" - changed_when: zabbix_websrv_servername_ip != ansible_default_ipv4.address - register: zabbix_letsencrypt_resolve - when: zabbix_letsencrypt - -- name: "Let's Encrypt | check if certbot CLI is present" - shell: "certbot --version" - register: zabbix_cerbot_check - changed_when: zabbix_cerbot_check.rc != 0 - check_mode: false - when: zabbix_letsencrypt - -- name: "Let's Encrypt | flash all handlers before certbot" - meta: flush_handlers - when: - - zabbix_letsencrypt - - zabbix_letsencrypt_resolve is not changed - - zabbix_cerbot_check.rc == 0 - -- name: "Let's Encrypt | generate certs with certbot CLI" - command: > - certbot --non-interactive certonly --expand - -a webroot --webroot-path={{ zabbix_letsencrypt_webroot_path }} - --email {{ zabbix_letsencrypt_account_email }} --agree-tos - --cert-name {{ zabbix_websrv_servername }} - -d {{ zabbix_websrv_servername }} - args: - creates: "/etc/letsencrypt/live/{{ zabbix_websrv_servername }}/fullchain.pem" - when: - - zabbix_letsencrypt - - zabbix_letsencrypt_resolve is not changed - - zabbix_cerbot_check.rc == 0 - -- name: "Let's Encrypt | Check for certificate created by certbot" - stat: - path: "/etc/letsencrypt/live/{{ zabbix_websrv_servername }}/fullchain.pem" - register: zabbix_letsencrypt_cert - failed_when: false - when: zabbix_letsencrypt - -- name: "Let's Encrypt | Reinstall Nginx vhost" - template: - src: nginx_vhost.conf.j2 - dest: /etc/nginx/conf.d/zabbix.conf - owner: root - group: root - mode: 0644 - when: - - zabbix_letsencrypt - - zabbix_letsencrypt_resolve is not changed - - zabbix_cerbot_check.rc == 0 + - zabbix_web_create_vhost become: true notify: - restart nginx + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/php_Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/php_Debian.yml deleted file mode 100644 index 6a2f329b6..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/php_Debian.yml +++ /dev/null @@ -1,43 +0,0 @@ ---- - -- include_tasks: apache.yml - when: - - zabbix_websrv == 'apache' - -# This obviously needs to have some improvements.. :) - -- name: "Debian | Determine php prefix for packages installations (legacy php5)" - set_fact: - _zabbix_php_package_prefix: 5 - when: - - ansible_distribution == 'Ubuntu' and ansible_distribution_version is version_compare('16.04', '<') - or ansible_distribution == 'Debian' and ansible_distribution_version is version_compare('9', '<') - -- name: "Debian | Determine php prefix for packages installations (Current distros)" - set_fact: - _zabbix_php_package_prefix: "{{ zabbix_php_version }}" - when: - - ansible_distribution == 'Ubuntu' and ansible_distribution_version is version_compare('16.04', '>=') or - ansible_distribution == 'Debian' and ansible_distribution_version is version_compare('9', '>=') - - zabbix_version is version_compare('5.0', '>=') - - not _zabbix_web_apache_php_addition - -- name: "Debian | Install php packages" - apt: - state: present - update_cache: true - cache_valid_time: 3600 - name: - - php{{ _zabbix_php_package_prefix }}-{{ zabbix_server_database }} - - php{{ _zabbix_php_package_prefix }}-bcmath - - php{{ _zabbix_php_package_prefix }}-mbstring - - php{{ _zabbix_php_package_prefix }}-ldap - - php{{ _zabbix_php_package_prefix }}-xml - - php{{ _zabbix_php_package_prefix }}-gd - - php{{ _zabbix_php_package_prefix }}-fpm - register: zabbix_web_php_dependency_install - until: zabbix_web_php_dependency_install is succeeded - become: true - tags: - - zabbix-web - - init diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/selinux.yml b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/selinux.yml index df8936eb1..56e2ae05e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/tasks/selinux.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/tasks/selinux.yml @@ -1,7 +1,6 @@ --- - - name: "SELinux | RedHat | Install related SELinux package" - yum: + ansible.builtin.yum: name: - libsemanage-python state: present @@ -16,10 +15,10 @@ - selinux_allow_zabbix_can_network - ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6" tags: - - zabbix-web + - install - name: "SELinux | RedHat | Install related SELinux package on RHEL9 and RHEL8" - yum: + ansible.builtin.yum: name: - python3-libsemanage state: present @@ -34,7 +33,7 @@ - selinux_allow_zabbix_can_network - ansible_distribution_major_version|int >= 8 tags: - - zabbix-web + - install - name: "SELinux | RedHat | Enable zabbix_can_network SELinux boolean" ansible.posix.seboolean: @@ -46,7 +45,7 @@ - ansible_os_family == "RedHat" - selinux_allow_zabbix_can_network tags: - - zabbix-web + - config - name: "SELinux | Allow httpd to connect to db (SELinux)" ansible.posix.seboolean: @@ -57,7 +56,8 @@ when: - ansible_selinux.status == "enabled" - selinux_allow_zabbix_can_network - tags: selinux + tags: + - config - name: "SELinux | Allow httpd to connect to zabbix (SELinux)" ansible.posix.seboolean: @@ -68,7 +68,8 @@ when: - ansible_selinux.status == "enabled" - selinux_allow_zabbix_can_network - tags: selinux + tags: + - config - name: "SELinux | Allow httpd to connect to ldap (SELinux)" ansible.posix.seboolean: @@ -79,4 +80,5 @@ when: - ansible_selinux.status == "enabled" - zabbix_apache_can_connect_ldap | bool - tags: selinux + tags: + - config diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/templates/apache_vhost.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_web/templates/apache_vhost.conf.j2 index 4149c43fa..334861d9b 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/templates/apache_vhost.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_web/templates/apache_vhost.conf.j2 @@ -1,5 +1,5 @@ -<VirtualHost {{ zabbix_apache_vhost_listen_ip }}:{{ zabbix_apache_vhost_port }}> - ServerName {{ zabbix_apache_servername }} +<VirtualHost {{ zabbix_web_vhost_listen_ip }}:{{ zabbix_web_vhost_port }}> + ServerName {{ zabbix_api_server_url }} {% for alias in zabbix_url_aliases %} ServerAlias {{ alias }} {% endfor %} @@ -13,7 +13,7 @@ {% endfor %} {% endif %} -{% if zabbix_apache_redirect and zabbix_apache_tls %} +{% if zabbix_web_redirect|default(false) and zabbix_web_tls|default(false) %} RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] @@ -57,50 +57,27 @@ {% endfor %} ## Logging - ErrorLog "/var/log/{{ _apache_log }}/{{ zabbix_apache_servername }}_error.log" + ErrorLog "/var/log/{{ _apache_log }}/{{ zabbix_api_server_url }}_error.log" ServerSignature Off - CustomLog "/var/log/{{ _apache_log }}/{{ zabbix_apache_servername }}_access.log" combined + CustomLog "/var/log/{{ _apache_log }}/{{ zabbix_api_server_url }}_access.log" combined ## Rewrite rules RewriteEngine On RewriteRule ^$ /index.php [L] - -{% if _zabbix_web_apache_php_addition | default(false) %} -{% if zabbix_apache_include_custom_fragment | default(true) %} - ## Custom fragment - {% if zabbix_php_fpm %} - ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/usr/share/zabbix/$1 - ProxyTimeout 1800 - {% else %} - php_value max_execution_time {{ zabbix_web_max_execution_time | default('300') }} - php_value memory_limit {{ zabbix_web_memory_limit | default('128M') }} - php_value post_max_size {{ zabbix_web_post_max_size | default('16M') }} - php_value upload_max_filesize {{ zabbix_web_upload_max_filesize | default('2M') }} - php_value max_input_time {{ zabbix_web_max_input_time | default('300') }} - - {% if zabbix_version is version('5.0', '>=') %} - php_value max_input_vars {{ zabbix_web_max_input_vars | default('10000') }} - {% endif %} - - # Set correct timezone. - php_value date.timezone {{ zabbix_timezone }} - {% endif %} -{% endif %} -{% endif %} </VirtualHost> {# Set up TLS vhosts #} -{% if zabbix_apache_tls and zabbix_apache_vhost_tls_port %} +{% if zabbix_web_tls and zabbix_web_vhost_tls_port %} -SSLPassPhraseDialog {{ zabbix_apache_SSLPassPhraseDialog }} -SSLSessionCache {{ zabbix_apache_SSLSessionCache }} -SSLSessionCacheTimeout {{ zabbix_apache_SSLSessionCacheTimeout }} +{{ (zabbix_web_SSLPassPhraseDialog is defined and zabbix_web_SSLPassPhraseDialog is not none) | ternary('', '# ') }}SSLPassPhraseDialog {{ zabbix_web_SSLPassPhraseDialog | default('') }} +{{ (zabbix_web_SSLSessionCache is defined and zabbix_web_SSLSessionCache is not none) | ternary('', '# ') }}SSLSessionCache {{ zabbix_web_SSLSessionCache | default('') }} +{{ (zabbix_web_SSLSessionCacheTimeout is defined and zabbix_web_SSLSessionCacheTimeout is not none) | ternary('', '# ') }}SSLSessionCacheTimeout {{ zabbix_web_SSLSessionCacheTimeout | default('') }} +{{ (zabbix_web_SSLCryptoDevice is defined and zabbix_web_SSLCryptoDevice is not none) | ternary('', '# ') }}SSLCryptoDevice {{ zabbix_web_SSLCryptoDevice | default('') }} SSLRandomSeed startup file:/dev/urandom 256 SSLRandomSeed connect builtin -SSLCryptoDevice {{ zabbix_apache_SSLCryptoDevice }} -<VirtualHost _default_:{{ zabbix_apache_vhost_tls_port }}> - ServerName {{ zabbix_apache_servername }} +<VirtualHost {{ zabbix_web_vhost_listen_ip }}:{{ zabbix_web_vhost_tls_port }}> + ServerName {{ zabbix_api_server_url }} {% for alias in zabbix_url_aliases %} ServerAlias {{ alias }} {% endfor %} @@ -115,17 +92,14 @@ SSLCryptoDevice {{ zabbix_apache_SSLCryptoDevice }} {% endif %} SSLEngine on - SSLCipherSuite {{ apache_ssl_cipher_suite }} - SSLProtocol {{ apache_ssl_protocol }} - SSLHonorCipherOrder On -{% if apache_vhosts_version == "2.4" %} + {{ (zabbix_web_ssl_cipher_suite is defined and zabbix_web_ssl_cipher_suite is not none) | ternary('', '# ') }}SSLCipherSuite {{ zabbix_web_ssl_cipher_suite | default('') }} + {{ (zabbix_web_ssl_cipher_suite is defined and zabbix_web_ssl_cipher_suite is not none) | ternary('', '# ') }}SSLHonorCipherOrder On +{% if apache_version|string() == '2.4' %} SSLCompression off {% endif %} - SSLCertificateFile {{ zabbix_apache_tls_crt }} - SSLCertificateKeyFile {{ zabbix_apache_tls_key }} -{% if zabbix_apache_tls_chain %} - SSLCertificateChainFile {{ zabbix_apache_tls_chain }} -{% endif %} + SSLCertificateFile {{ zabbix_web_tls_crt }} + SSLCertificateKeyFile {{ zabbix_web_tls_key }} + {{ (zabbix_web_tls_chain is defined and zabbix_web_tls_chain is not none) | ternary('', '# ') }}SSLCertificateChainFile {{ zabbix_web_tls_chain | default('') }} {% set directory_paths = ['/usr/share/zabbix/conf', '/usr/share/zabbix/app', '/usr/share/zabbix/include', '/usr/share/zabbix/include/classes'] %} @@ -165,35 +139,13 @@ SSLCryptoDevice {{ zabbix_apache_SSLCryptoDevice }} {% endfor %} ## Logging - ErrorLog "/var/log/{{ _apache_log }}/{{ zabbix_apache_servername }}_tls_error.log" + ErrorLog "/var/log/{{ _apache_log }}/{{ zabbix_api_server_url }}_tls_error.log" ServerSignature Off - CustomLog "/var/log/{{ _apache_log }}/{{ zabbix_apache_servername }}_tls_access.log" combined + CustomLog "/var/log/{{ _apache_log }}/{{ zabbix_api_server_url }}_tls_access.log" combined ## Rewrite rules RewriteEngine On RewriteRule ^$ /index.php [L] -{% if _zabbix_web_apache_php_addition | default(false) %} -{% if zabbix_apache_include_custom_fragment | default(true) %} - ## Custom fragment - {% if zabbix_php_fpm %} - ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/usr/share/zabbix/$1 - ProxyTimeout 1800 - {% else %} - php_value max_execution_time {{ zabbix_web_max_execution_time | default('300') }} - php_value memory_limit {{ zabbix_web_memory_limit | default('128M') }} - php_value post_max_size {{ zabbix_web_post_max_size | default('16M') }} - php_value upload_max_filesize {{ zabbix_web_upload_max_filesize | default('2M') }} - php_value max_input_time {{ zabbix_web_max_input_time | default('300') }} - - {% if zabbix_version is version('5.0', '>=') %} - php_value max_input_vars {{ zabbix_web_max_input_vars | default('10000') }} - {% endif %} - - # Set correct timezone. - php_value date.timezone {{ zabbix_timezone }} - {% endif %} -{% endif %} -{% endif %} </VirtualHost> {% endif %} diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/templates/nginx_vhost.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_web/templates/nginx_vhost.conf.j2 index 49671984c..7854b83ce 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/templates/nginx_vhost.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_web/templates/nginx_vhost.conf.j2 @@ -1,61 +1,78 @@ # Nginx configuration for Zabbix Web server { -{% if not zabbix_nginx_tls %} - listen {{ zabbix_nginx_vhost_port }}; -{% else %} -{% if zabbix_letsencrypt %} - listen 80; + listen {{ zabbix_web_vhost_port }}; server_tokens off; - server_name {{ zabbix_websrv_servername }} {% for alias in zabbix_url_aliases -%}{{ alias -}} {% endfor %}; - location ^~ /.well-known/acme-challenge { - root {{ zabbix_letsencrypt_webroot_path | default('/var/www/letsencrypt') }}; - # disables IP restrictions and HTTP auth - allow all; - default_type text/plain; - try_files $uri =404; + server_name {{ zabbix_api_server_url }} {% for alias in zabbix_url_aliases -%}{{ alias -}} {% endfor %}; + + {% if zabbix_web_redirect|default(false) and zabbix_web_tls|default(false) %} + return 301 https://{{ zabbix_api_server_url }}$request_uri; + {% else %} + root /usr/share/zabbix; + + index index.php; + + location = /favicon.ico { + log_not_found off; } - location / { return 301 https://$host:{{ zabbix_nginx_vhost_tls_port }}$request_uri; } -} -server { -{% endif %} - listen {{ zabbix_nginx_vhost_tls_port }} ssl; -{% if zabbix_letsencrypt and zabbix_letsencrypt_cert.stat.exists %} - ssl_certificate /etc/letsencrypt/live/{{ zabbix_websrv_servername }}/fullchain.pem; - ssl_certificate_key /etc/letsencrypt/live/{{ zabbix_websrv_servername }}/privkey.pem; -{% else %} - ssl_certificate {{ zabbix_nginx_tls_crt }}; - ssl_certificate_key {{ zabbix_nginx_tls_key }}; -{% endif %} - ssl_session_timeout {{ zabbix_nginx_tls_session_timeout }}; - ssl_session_cache {{ zabbix_nginx_tls_session_cache }}; - ssl_session_tickets {{ zabbix_nginx_tls_session_tickets }}; - ssl_dhparam {{ zabbix_nginx_tls_dhparam }}; + location / { + try_files $uri $uri/ =404; + } - ssl_protocols {{ zabbix_nginx_tls_protocols }}; - ssl_ciphers {{ zabbix_nginx_tls_ciphers }}; - ssl_prefer_server_ciphers off; + location /assets { + access_log off; + expires 10d; + } -{% endif %} - server_tokens off; - server_name {{ zabbix_websrv_servername }} {% for alias in zabbix_url_aliases -%}{{ alias -}} {% endfor %}; + location ~ /\.ht { + deny all; + } -{% if zabbix_web_allowlist_ips is defined and zabbix_web_allowlist_ips %} - # Allow list IPs via zabbix_web_allowlist_ips - satisfy any; -{% for ip in zabbix_web_allowlist_ips | ansible.netcommon.ipaddr %} - allow {{ ip }}; -{% endfor %} - deny all; + location ~ /(api\/|conf[^\.]|include|locale) { + deny all; + return 404; + } -{% endif %} -{% if zabbix_web_htpasswd is defined and zabbix_web_htpasswd %} - # HTTP authentication via zabbix_web_htpasswd - auth_basic "Restricted"; - auth_basic_user_file {{ zabbix_web_htpasswd_file }}; + location ~ [^/]\.php(/|$) { + fastcgi_pass unix:{{ zabbix_php_fpm_listen }}; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_index index.php; -{% endif %} + fastcgi_param DOCUMENT_ROOT /usr/share/zabbix; + fastcgi_param SCRIPT_FILENAME /usr/share/zabbix$fastcgi_script_name; + fastcgi_param PATH_TRANSLATED /usr/share/zabbix$fastcgi_script_name; + + include fastcgi_params; + fastcgi_param QUERY_STRING $query_string; + fastcgi_param REQUEST_METHOD $request_method; + fastcgi_param CONTENT_TYPE $content_type; + fastcgi_param CONTENT_LENGTH $content_length; + + fastcgi_intercept_errors on; + fastcgi_ignore_client_abort off; + fastcgi_connect_timeout 60; + fastcgi_send_timeout 180; + fastcgi_read_timeout 180; + fastcgi_buffer_size 128k; + fastcgi_buffers 4 256k; + fastcgi_busy_buffers_size 256k; + fastcgi_temp_file_write_size 256k; + } + {% endif %} +} + +{% if zabbix_web_tls|default(false) %} +server { + listen {{ zabbix_web_vhost_tls_port }} ssl; + server_tokens off; + server_name {{ zabbix_api_server_url }} {% for alias in zabbix_url_aliases -%}{{ alias -}} {% endfor %}; + + ssl_certificate {{ zabbix_web_tls_crt }}; + ssl_certificate_key {{ zabbix_web_tls_key }}; + {{ (zabbix_web_ssl_cipher_suite is defined and zabbix_web_ssl_cipher_suite is not none) | ternary('', '# ') }}ssl_ciphers {{ zabbix_web_ssl_cipher_suite | default('') }} + {{ (zabbix_web_SSLSessionCache is defined and zabbix_web_SSLSessionCache is not none) | ternary('', '# ') }}ssl_session_cache {{ zabbix_web_SSLSessionCache | default('') }} + {{ (zabbix_web_SSLSessionCacheTimeout is defined and zabbix_web_SSLSessionCacheTimeout is not none) | ternary('', '# ') }}ssl_session_timeout {{ zabbix_web_SSLSessionCacheTimeout | default('') }} root /usr/share/zabbix; index index.php; @@ -108,3 +125,4 @@ server { fastcgi_temp_file_write_size 256k; } } +{% endif %} diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/templates/php-fpm.conf.j2 b/ansible_collections/community/zabbix/roles/zabbix_web/templates/php-fpm.conf.j2 index bf2faef7a..e6b02cc9e 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/templates/php-fpm.conf.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_web/templates/php-fpm.conf.j2 @@ -1,20 +1,14 @@ [zabbix] -user = {{ zabbix_php_fpm_conf_user if zabbix_php_fpm_conf_user is defined else zabbix_web_conf_web_user }} -group = {{ zabbix_php_fpm_conf_group if zabbix_php_fpm_conf_group is defined else zabbix_web_conf_web_group }} +user = {{ zabbix_php_fpm_conf_user if zabbix_php_fpm_conf_user is defined else zabbix_web_user }} +group = {{ zabbix_php_fpm_conf_group if zabbix_php_fpm_conf_group is defined else zabbix_web_group }} listen = {{ zabbix_php_fpm_listen }} {% if zabbix_php_fpm_conf_listen and ansible_os_family != 'Debian' %} -listen.acl_users = {{ zabbix_php_fpm_conf_user if zabbix_php_fpm_conf_user is defined else zabbix_web_conf_web_user }} -{% endif %} -{% if zabbix_php_fpm_conf_enable_user is defined %} -listen.owner = {{ zabbix_php_fpm_conf_user if zabbix_php_fpm_conf_user is defined else zabbix_web_conf_web_user }} -{% endif %} -{% if zabbix_php_fpm_conf_enable_group %} -listen.group = {{ _nginx_group if zabbix_websrv=='nginx' else _apache_group }} -{% endif %} -{% if zabbix_php_fpm_conf_enable_mode %} -listen.mode = {{ zabbix_php_fpm_conf_mode }} +listen.acl_users = {{ zabbix_php_fpm_conf_user if zabbix_php_fpm_conf_user is defined else zabbix_web_user }} {% endif %} +listen.owner = {{ zabbix_php_fpm_conf_user if zabbix_php_fpm_conf_user is defined else zabbix_web_user }} +listen.group = {{ _nginx_group if zabbix_web_http_server=='nginx' else _apache_group }} +listen.mode = 0644 listen.allowed_clients = 127.0.0.1 pm = dynamic diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/templates/zabbix.conf.php.j2 b/ansible_collections/community/zabbix/roles/zabbix_web/templates/zabbix.conf.php.j2 index 880ed36f0..79ff73b15 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/templates/zabbix.conf.php.j2 +++ b/ansible_collections/community/zabbix/roles/zabbix_web/templates/zabbix.conf.php.j2 @@ -6,7 +6,7 @@ global $DB, $HISTORY; global $DB; {% endif %} -$DB['TYPE'] = '{{ zabbix_server_database_long | upper() }}'; +$DB['TYPE'] = '{{ zabbix_db_type_long | upper() }}'; $DB['SERVER'] = '{{ zabbix_server_dbhost }}'; $DB['PORT'] = '{{ zabbix_server_dbport }}'; $DB['DATABASE'] = '{{ zabbix_server_dbname }}'; diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-10.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-10.yml deleted file mode 100644 index 8ed439680..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-10.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 7.2 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-11.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-11.yml deleted file mode 100644 index 9d28ef9e3..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-11.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 7.4 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-8.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-8.yml deleted file mode 100644 index b4537abdf..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-8.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 7.3 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-9.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-9.yml deleted file mode 100644 index 9d28ef9e3..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian-9.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 7.4 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian.yml index 9840e6505..7b60c70bd 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Debian.yml @@ -3,16 +3,20 @@ _apache_user: www-data _apache_group: www-data _apache_log: apache2 _apache_service: apache2 +_apache_vhost_location: /etc/apache2/sites-available/zabbix.conf -_php_fpm_dir: /etc/php/{{ _zabbix_php_version }}/fpm/pool.d +_php_fpm_dir: /etc/php/{{ zabbix_web_php_installed_version }}/fpm/pool.d _php_fpm_session: /tmp -_php_fpm_listen: /run/php/zabbix.sock +_zabbix_php_fpm_listen: /run/php/zabbix.sock _zabbix_php_fpm_mode: "0666" _zabbix_php_fpm_allowed_clients: 127.0.0.1 +_apache_php_dependencies: libapache2-mod-php{{ zabbix_web_php_installed_version }} +_nginx_php_dependencies: [] + _nginx_user: www-data _nginx_group: www-data -_nginx_config_path: /etc/nginx/conf.d +_nginx_vhost_location: /etc/nginx/conf.d/zabbix.conf _nginx_log_path: /var/log/nginx _nginx_service: nginx _nginx_tls_crt: /etc/ssl/certs/ssl-cert-snakeoil.pem @@ -21,27 +25,27 @@ _nginx_tls_dhparam: /etc/ssl/private/dhparams.pem zabbix_valid_web_versions: # Debian + "12": + - 6.4 + - 6.0 "11": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "10": - 6.0 - - 5.0 - - 4.0 - "9": - - 4.0 # Ubuntu "22": - 6.4 + - 6.2 - 6.0 "20": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 "18": - 6.0 - - 5.0 - - 4.0 + +debian_keyring_path: /etc/apt/keyrings/ +zabbix_gpg_key: "{{ debian_keyring_path }}/zabbix-official-repo.asc" +_zabbix_repo_deb_url: "http://repo.zabbix.com/zabbix/{{ zabbix_web_version }}" diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-7.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-7.yml deleted file mode 100644 index 5109c4793..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-7.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- -_php_fpm_dir: /etc/opt/rh/rh-php72/php-fpm.d/ -_php_fpm_session: /var/lib/php/session -_php_fpm_listen: "/run/php-fpm/zabbix.sock" - -_zabbix_php_version: 7.2 -_zabbix_php_fpm_session: /var/opt/rh/rh-php72/lib/php/session/ -_zabbix_php_fpm_listen: /var/opt/rh/rh-php72/run/php-fpm/zabbix.sock diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-8.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-8.yml deleted file mode 100644 index 72022a460..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-8.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- -_php_fpm_dir: /etc/php-fpm.d -_php_fpm_session: /var/lib/php/session -_php_fpm_listen: "/run/php-fpm/zabbix.sock" - -_zabbix_php_version: 7.4 -_zabbix_php_fpm_session: /var/opt/rh/rh-php72/lib/php/session/ -_zabbix_php_fpm_listen: /var/opt/rh/rh-php72/run/php-fpm/zabbix.sock diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-9.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-9.yml deleted file mode 100644 index bfcca82d3..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat-9.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- -_php_fpm_dir: /etc/php-fpm.d -_php_fpm_session: /var/lib/php/session -_php_fpm_listen: "/run/php-fpm/zabbix.sock" - -_zabbix_php_version: 8.0 -_zabbix_php_fpm_session: /var/lib/php/session -_zabbix_php_fpm_listen: /run/php-fpm/zabbix.sock diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat.yml index 89a950683..785c18c99 100644 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat.yml +++ b/ansible_collections/community/zabbix/roles/zabbix_web/vars/RedHat.yml @@ -3,29 +3,41 @@ _apache_user: apache _apache_group: apache _apache_log: httpd _apache_service: httpd +_apache_vhost_location: /etc/httpd/conf.d/zabbix.conf _php_fpm_dir: /etc/php-fpm.d -_php_fpm_session: /var/opt/rh/rh-php72/lib/php/session/ -_php_fpm_listen: /run/php-fpm/zabbix.sock +_php_fpm_session: /var/lib/php/session +_zabbix_php_fpm_listen: /run/php-fpm/zabbix.sock _nginx_user: nginx _nginx_group: nginx -_nginx_config_path: /etc/nginx/conf.d +_nginx_vhost_location: /etc/nginx/conf.d/zabbix.conf _nginx_log_path: /var/log/nginx _nginx_service: nginx -_nginx_tls_crt: /etc/pki/server.crt -_nginx_tls_key: /etc/pki/server.key -_nginx_tls_dhparam: /etc/pki/dhparam-server.pem + +__epel_repo: + - epel zabbix_valid_web_versions: "9": - 6.4 + - 6.2 - 6.0 "8": - 6.4 + - 6.2 - 6.0 - - 5.0 - - 4.0 - "7": - - 5.0 - - 4.0 + +zabbix_web_php_dependencies: + - "php-gd" + - "php-bcmath" + - "php-xml" + - "php-mbstring" + - "php-ldap" + - "php-{{ 'pgsql' if zabbix_server_database == 'pgsql' else 'mysqlnd' }}" + +zabbix_selinux_dependencies: + "9": + - python3-libsemanage + "8": + - python3-libsemanage diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-18.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-18.yml deleted file mode 100644 index 8ed439680..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-18.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 7.2 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-20.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-20.yml deleted file mode 100644 index 9d28ef9e3..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-20.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 7.4 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-22.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-22.yml deleted file mode 100644 index 39525f373..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/Ubuntu-22.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- - -_zabbix_php_version: 8.1 diff --git a/ansible_collections/community/zabbix/roles/zabbix_web/vars/zabbix.yml b/ansible_collections/community/zabbix/roles/zabbix_web/vars/zabbix.yml deleted file mode 100644 index 6de493b2e..000000000 --- a/ansible_collections/community/zabbix/roles/zabbix_web/vars/zabbix.yml +++ /dev/null @@ -1,258 +0,0 @@ ---- -sign_keys: - "64": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "62": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "60": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - jammy: - sign_key: E709712C - "54": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "52": - # bullseye: not available upstream - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "50": - bullseye: - sign_key: E709712C - buster: - sign_key: E709712C - jessie: - sign_key: E709712C - stretch: - sign_key: E709712C - focal: - sign_key: E709712C - bionic: - sign_key: E709712C - xenial: - sign_key: E709712C - trusty: - sign_key: E709712C - tricia: - sign_key: E709712C - "44": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "42": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - eoan: - sign_key: A14FE591 - cosmic: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "40": - bullseye: - sign_key: A14FE591 - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - focal: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "34": - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: A14FE591 - bionic: - sign_key: A14FE591 - sonya: - sign_key: A14FE591 - serena: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "32": - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - sonya: - sign_key: 79EA5ED4 - serena: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "30": - buster: - sign_key: A14FE591 - jessie: - sign_key: 79EA5ED4 - stretch: - sign_key: A14FE591 - wheezy: - sign_key: 79EA5ED4 - bionic: - sign_key: A14FE591 - trusty: - sign_key: 79EA5ED4 - xenial: - sign_key: E709712C - "24": - jessie: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - "22": - squeeze: - sign_key: 79EA5ED4 - wheezy: - sign_key: 79EA5ED4 - precise: - sign_key: 79EA5ED4 - trusty: - sign_key: 79EA5ED4 - lucid: - sign_key: 79EA5ED4 - -suse: - "openSUSE Leap": - "42": - name: server:monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_Leap_{{ ansible_distribution_version }}/ - "openSUSE": - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/openSUSE_{{ ansible_distribution_version }} - "SLES": - "11": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_11_SP3/ - "12": - name: server_monitoring - url: http://download.opensuse.org/repositories/server:/monitoring/SLE_12_SP3/ diff --git a/ansible_collections/community/zabbix/scripts/inventory/zabbix.ini b/ansible_collections/community/zabbix/scripts/inventory/zabbix.ini index ead19b62d..0d6bcab8d 100644 --- a/ansible_collections/community/zabbix/scripts/inventory/zabbix.ini +++ b/ansible_collections/community/zabbix/scripts/inventory/zabbix.ini @@ -7,14 +7,20 @@ server = http://zabbix.example.com/zabbix # Login -username = admin +username = Admin password = zabbix +# Authentication token, if empty then username/password used to authenticate +auth_token = + # Verify the server's SSL certificate validate_certs = True +# Time to wait for API response +tiemout = 30 + # Read zabbix inventory per host read_host_inventory = True # Set ansible_ssh_host based on first interface settings -use_host_interface = True
\ No newline at end of file +use_host_interface = True diff --git a/ansible_collections/community/zabbix/scripts/inventory/zabbix.py b/ansible_collections/community/zabbix/scripts/inventory/zabbix.py index 767012848..29ac11b93 100644 --- a/ansible_collections/community/zabbix/scripts/inventory/zabbix.py +++ b/ansible_collections/community/zabbix/scripts/inventory/zabbix.py @@ -38,134 +38,209 @@ from __future__ import print_function import os import sys import argparse -from ansible.module_utils.six.moves import configparser - -try: - from zabbix_api import ZabbixAPI -except Exception: - print("Error: Zabbix API library must be installed: pip install zabbix-api.", - file=sys.stderr) - sys.exit(1) - import json +import atexit +from ansible.module_utils.six.moves import configparser +from ansible.module_utils.compat.version import LooseVersion +from ansible.module_utils.urls import Request +from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError class ZabbixInventory(object): def read_settings(self): config = configparser.ConfigParser() - conf_path = './zabbix.ini' + conf_path = "./zabbix.ini" if not os.path.exists(conf_path): - conf_path = os.path.dirname(os.path.realpath(__file__)) + '/zabbix.ini' + conf_path = os.path.dirname(os.path.realpath(__file__)) + "/zabbix.ini" if os.path.exists(conf_path): config.read(conf_path) # server - if config.has_option('zabbix', 'server'): - self.zabbix_server = config.get('zabbix', 'server') + if config.has_option("zabbix", "server"): + self.zabbix_server = config.get("zabbix", "server") # login - if config.has_option('zabbix', 'username'): - self.zabbix_username = config.get('zabbix', 'username') - if config.has_option('zabbix', 'password'): - self.zabbix_password = config.get('zabbix', 'password') + if config.has_option("zabbix", "username"): + self.zabbix_username = config.get("zabbix", "username") + if config.has_option("zabbix", "password"): + self.zabbix_password = config.get("zabbix", "password") + if config.has_option("zabbix", "auth_token"): + self.auth_token = config.get("zabbix", "auth_token") # ssl certs - if config.has_option('zabbix', 'validate_certs'): - if config.get('zabbix', 'validate_certs') in ['false', 'False', False]: + if config.has_option("zabbix", "validate_certs"): + if config.get("zabbix", "validate_certs") in ["false", "False", False]: self.validate_certs = False + # timeout + if config.has_option("zabbix", "timeout"): + self.timeout = config.get("zabbix", "timeout") # host inventory - if config.has_option('zabbix', 'read_host_inventory'): - if config.get('zabbix', 'read_host_inventory') in ['true', 'True', True]: + if config.has_option("zabbix", "read_host_inventory"): + if config.get("zabbix", "read_host_inventory") in ["true", "True", True]: self.read_host_inventory = True # host interface - if config.has_option('zabbix', 'use_host_interface'): - if config.get('zabbix', 'use_host_interface') in ['false', 'False', False]: + if config.has_option("zabbix", "use_host_interface"): + if config.get("zabbix", "use_host_interface") in ["false", "False", False]: self.use_host_interface = False def read_cli(self): parser = argparse.ArgumentParser() - parser.add_argument('--host') - parser.add_argument('--list', action='store_true') + parser.add_argument("--host") + parser.add_argument("--list", action="store_true") self.options = parser.parse_args() def hoststub(self): return { - 'hosts': [] + "hosts": [] + } + + def api_request(self, method, params=None): + server_url = self.zabbix_server + validate_certs = self.validate_certs + timeout = self.timeout + + headers = {"Content-Type": "application/json-rpc"} + payload = { + "jsonrpc": "2.0", + "method": method, + "id": "1" } + if params is None: + payload["params"] = {} + else: + payload["params"] = params - def get_host(self, api, name): - api_query = {'output': 'extend', 'selectGroups': 'extend', "filter": {"host": [name]}} + if self.auth != "": + if (LooseVersion(self.zabbix_version) >= LooseVersion("6.4")): + headers["Authorization"] = "Bearer " + self.auth + else: + payload["auth"] = self.auth + + api_url = server_url + "/api_jsonrpc.php" + req = Request( + headers=headers, + timeout=timeout, + validate_certs=validate_certs + ) + try: + response = req.post(api_url, data=json.dumps(payload)) + except ValueError: + print("Error: Something went wrong with JSON loading.", file=sys.stderr) + sys.exit(1) + except (URLError, HTTPError) as error: + print(error, file=sys.stderr) + + return response + + def get_version(self): + response = self.api_request( + "apiinfo.version" + ) + res = json.load(response) + self.zabbix_version = res["result"] + + def login_zabbix(self): + auth_token = self.auth_token + if auth_token: + self.auth = auth_token + return + + atexit.register(self.logout_zabbix) + + login_user = self.zabbix_username + login_password = self.zabbix_password + response = self.api_request( + "user.login", + { + "username": login_user, + "password": login_password + } + ) + res = json.load(response) + self.auth = res["result"] + + def logout_zabbix(self): + self.api_request( + "user.logout", + [] + ) + + def get_host(self, name): + api_query = {"output": "extend", "selectGroups": "extend", "filter": {"host": [name]}} if self.use_host_interface: - api_query['selectInterfaces'] = ['useip', 'ip', 'dns'] + api_query["selectInterfaces"] = ["useip", "ip", "dns"] if self.read_host_inventory: - api_query['selectInventory'] = "extend" + api_query["selectInventory"] = "extend" - data = {'ansible_ssh_host': name} + data = {"ansible_ssh_host": name} if self.use_host_interface or self.read_host_inventory: - try: - hosts_data = api.host.get(api_query)[0] - # check if zabbix api returned a interfaces element - if 'interfaces' in hosts_data: + response = self.api_request("host.get", api_query) + response_obj = json.load(response) + if len(response_obj['result']) > 0: + host_data = response_obj['result'][0] + # check if zabbix api returned interfaces element + if "interfaces" in host_data: # check for a interfaces list that contains at least interface - if len(hosts_data['interfaces']) >= 1: + if len(host_data["interfaces"]) >= 1: # use first interface only - if hosts_data['interfaces'][0]['useip'] == 0: - data['ansible_ssh_host'] = hosts_data['interfaces'][0]['dns'] + if host_data["interfaces"][0]["useip"] == '0': + data["ansible_ssh_host"] = host_data["interfaces"][0]["dns"] else: - data['ansible_ssh_host'] = hosts_data['interfaces'][0]['ip'] - if ('inventory' in hosts_data) and (hosts_data['inventory']): - data.update(hosts_data['inventory']) - except IndexError: - # Host not found in zabbix - pass + data["ansible_ssh_host"] = host_data["interfaces"][0]["ip"] + if ("inventory" in host_data) and (host_data["inventory"]): + data.update(host_data["inventory"]) return data - def get_list(self, api): - api_query = {'output': 'extend', 'selectGroups': 'extend'} + def get_list(self): + api_query = {"output": "extend", "selectGroups": "extend"} if self.use_host_interface: - api_query['selectInterfaces'] = ['useip', 'ip', 'dns'] + api_query["selectInterfaces"] = ["useip", "ip", "dns"] if self.read_host_inventory: - api_query['selectInventory'] = "extend" - - hosts_data = api.host.get(api_query) - data = {'_meta': {'hostvars': {}}} + api_query["selectInventory"] = "extend" + response = self.api_request("host.get", api_query) + hosts_data = json.load(response)["result"] + data = {"_meta": {"hostvars": {}}} data[self.defaultgroup] = self.hoststub() for host in hosts_data: - hostname = host['name'] + hostname = host["name"] hostvars = dict() - data[self.defaultgroup]['hosts'].append(hostname) + data[self.defaultgroup]["hosts"].append(hostname) - for group in host['groups']: - groupname = group['name'] + for group in host["groups"]: + groupname = group["name"] if groupname not in data: data[groupname] = self.hoststub() - data[groupname]['hosts'].append(hostname) + data[groupname]["hosts"].append(hostname) # check if zabbix api returned a interfaces element - if 'interfaces' in host: + if "interfaces" in host: # check for a interfaces list that contains at least interface - if len(host['interfaces']) >= 1: + if len(host["interfaces"]) >= 1: # use first interface only - if host['interfaces'][0]['useip'] == 0: - hostvars['ansible_ssh_host'] = host['interfaces'][0]['dns'] + if host["interfaces"][0]["useip"] == 0: + hostvars["ansible_ssh_host"] = host["interfaces"][0]["dns"] else: - hostvars['ansible_ssh_host'] = host['interfaces'][0]['ip'] - if ('inventory' in host) and (host['inventory']): - hostvars.update(host['inventory']) - data['_meta']['hostvars'][hostname] = hostvars + hostvars["ansible_ssh_host"] = host["interfaces"][0]["ip"] + if ("inventory" in host) and (host["inventory"]): + hostvars.update(host["inventory"]) + data["_meta"]["hostvars"][hostname] = hostvars return data def __init__(self): - self.defaultgroup = 'group_all' + self.defaultgroup = "group_all" self.zabbix_server = None self.zabbix_username = None self.zabbix_password = None + self.auth_token = None + self.auth = "" self.validate_certs = True + self.timeout = 30 self.read_host_inventory = False self.use_host_interface = True + self.zabbix_version = "" self.meta = {} @@ -174,20 +249,20 @@ class ZabbixInventory(object): if self.zabbix_server and self.zabbix_username: try: - api = ZabbixAPI(server=self.zabbix_server, validate_certs=self.validate_certs) - api.login(user=self.zabbix_username, password=self.zabbix_password) + self.get_version() + self.login_zabbix() # zabbix_api tries to exit if it cannot parse what the zabbix server returned # so we have to use SystemExit here except (Exception, SystemExit) as e: - print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr) + print("Error: got the exception '%s'. Check your zabbix.ini." % e, file=sys.stderr) sys.exit(1) if self.options.host: - data = self.get_host(api, self.options.host) + data = self.get_host(self.options.host) print(json.dumps(data, indent=2)) elif self.options.list: - data = self.get_list(api) + data = self.get_list() print(json.dumps(data, indent=2)) else: diff --git a/ansible_collections/community/zabbix/tests/integration/targets/setup_zabbix/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/setup_zabbix/tasks/main.yml index ba4c30311..fd7f6a700 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/setup_zabbix/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/setup_zabbix/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: get zabbix version - uri: + ansible.builtin.uri: url: "{{ zabbix_api_server_url }}/api_jsonrpc.php" method: POST body: @@ -16,7 +16,7 @@ register: zabbix_version_result - name: set zabbix_version variable - set_fact: + ansible.builtin.set_fact: zabbix_version: >- {{ [0,1] | map('extract', zabbix_version_result.json.result.split('.')) @@ -27,7 +27,7 @@ ansible_connection: httpapi # ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 ansible_host: 127.0.0.1 - ansible_zabbix_url_path: '' + ansible_zabbix_url_path: "" ansible_httpapi_port: 8080 ansible_httpapi_use_ssl: false ansible_httpapi_validate_certs: false @@ -36,7 +36,7 @@ - debug: var=zabbix_version - name: check login to zabbix for Zabbix < 6.4 - uri: + ansible.builtin.uri: url: "{{ zabbix_api_server_url }}/api_jsonrpc.php" method: POST body: @@ -55,7 +55,7 @@ when: zabbix_version is version('6.4', '<') - name: check login to zabbix for Zabbix >= 6.4 - uri: + ansible.builtin.uri: url: "{{ zabbix_api_server_url }}/api_jsonrpc.php" method: POST body: diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_action/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_action/tasks/main.yml index 6893dfd56..446f7cd3b 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_action/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_action/tasks/main.yml @@ -1,13 +1,6 @@ --- -- name: test - do not run tests for Zabbix 3.0 - meta: end_play - when: zabbix_version is version('3.0', '=') - - name: test - prepare example template for zabbix_action module - zabbix_template: - server_url: "{{ zabbix_api_server_url }} " - login_user: "{{ zabbix_api_login_user }}" - login_password: "{{ zabbix_api_login_pass }}" + community.zabbix.zabbix_template: template_name: ExampleTemplateForActionModule template_groups: - Templates @@ -15,10 +8,7 @@ register: zbxaction_prep_template - name: test - prepare example mediatype for zabbix_action module - zabbix_mediatype: - server_url: "{{ zabbix_api_server_url }} " - login_user: "{{ zabbix_api_login_user }}" - login_password: "{{ zabbix_api_login_pass }}" + community.zabbix.zabbix_mediatype: name: ExampleMediaTypeForActionModule smtp_email: zabbix@example.com type: email @@ -32,223 +22,139 @@ status: enabled name: ExampleTriggerAction event_source: trigger + notify_if_canceled: true esc_period: 60 conditions: - type: trigger_severity - operator: '>=' + operator: ">=" value: Information operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin block: - - name: test - create new action - zabbix_action: - register: zbxaction_new + - name: test - create new action + community.zabbix.zabbix_action: + register: zbxaction_new - - assert: - that: zbxaction_new.changed is sameas True + - ansible.builtin.assert: + that: zbxaction_new.changed is sameas True - - name: test - create new action (again) - zabbix_action: - register: zbxaction_new + - name: test - create new action (again) + community.zabbix.zabbix_action: + register: zbxaction_new - - assert: - that: zbxaction_new.changed is sameas False + - ansible.builtin.assert: + that: zbxaction_new.changed is sameas False - - when: zabbix_version is version('3.4', '>=') - block: - name: test - update action with esc_period as string - zabbix_action: + community.zabbix.zabbix_action: esc_period: 2m register: zbxaction_escperiod_str - - assert: + - ansible.builtin.assert: that: zbxaction_escperiod_str.changed is sameas True - name: test - update action with esc_period as string (again) - zabbix_action: + community.zabbix.zabbix_action: esc_period: 2m register: zbxaction_escperiod_str - - assert: + - ansible.builtin.assert: that: zbxaction_escperiod_str.changed is sameas False - name: test - update action with esc_period as macro - zabbix_action: - esc_period: '{$MYMACRO}' + community.zabbix.zabbix_action: + esc_period: "{$MYMACRO}" register: zbxaction_escperiod_macro - - assert: + - ansible.builtin.assert: that: zbxaction_escperiod_macro.changed is sameas True - name: test - update action with esc_period as macro (again) - zabbix_action: - esc_period: '{$MYMACRO}' + community.zabbix.zabbix_action: + esc_period: "{$MYMACRO}" register: zbxaction_escperiod_macro - - assert: + - ansible.builtin.assert: that: zbxaction_escperiod_macro.changed is sameas False - - name: test - update action with esc_period - zabbix_action: - esc_period: 120 - register: zbxaction_escperiod - - - assert: - that: zbxaction_escperiod.changed is sameas True - - - name: test - update action with esc_period (again) - zabbix_action: - esc_period: 120 - register: zbxaction_escperiod - - - assert: - that: zbxaction_escperiod.changed is sameas False - - - name: test - update action with pause_in_maintenance - zabbix_action: - esc_period: 120 - pause_in_maintenance: false - register: zbxaction_maintpause - - - assert: - that: zbxaction_maintpause.changed is sameas True - - - name: test - update action with pause_in_maintenance (again) - zabbix_action: - esc_period: 120 - pause_in_maintenance: false - register: zbxaction_maintpause - - - assert: - that: zbxaction_maintpause.changed is sameas False - - - name: test - reset action to default - zabbix_action: - register: zbxaction_reset - - - assert: - that: zbxaction_reset.changed is sameas True - - - when: zabbix_version is version('5.0', '<') - block: - - name: test - update action with default_subject and default_message - zabbix_action: - default_subject: Example default subject - default_message: Example default message - register: zbxaction_def_msgsubj - - - assert: - that: zbxaction_def_msgsubj.changed is sameas True - - - name: test - update action with default_subject and default_message (again) - zabbix_action: - default_subject: Example default subject - default_message: Example default message - register: zbxaction_def_msgsubj - - - assert: - that: zbxaction_def_msgsubj.changed is sameas False - - - when: - - zabbix_version is version('3.2', '>=') - - zabbix_version is version('5.0', '<') - block: - - name: test - update action with recovery_default_subject and recovery_default_message - zabbix_action: - default_subject: Example default subject - default_message: Example default message - recovery_default_subject: Example recovery subject - recovery_default_message: Example recovery message - register: zbxaction_rec_msgsubj - - - assert: - that: zbxaction_rec_msgsubj.changed is sameas True - - - name: test - update action with recovery_default_subject and recovery_default_message (again) - zabbix_action: - default_subject: Example default subject - default_message: Example default message - recovery_default_subject: Example recovery subject - recovery_default_message: Example recovery message - register: zbxaction_rec_msgsubj - - - assert: - that: zbxaction_rec_msgsubj.changed is sameas False - - - when: - - zabbix_version is version('3.4', '>=') - - zabbix_version is version('5.0', '<') - block: - - name: test - update action with acknowledge_default_subject and acknowledge_default_message - zabbix_action: - default_subject: Example default subject - default_message: Example default message - recovery_default_subject: Example recovery subject - recovery_default_message: Example recovery message - acknowledge_default_subject: Example acknowledge subject - acknowledge_default_message: Example acknowledge message - register: zbxaction_ack_msgsubj - - - assert: - that: zbxaction_ack_msgsubj.changed is sameas True - - - name: test - update action with acknowledge_default_subject and acknowledge_default_message (again) - zabbix_action: - default_subject: Example default subject - default_message: Example default message - recovery_default_subject: Example recovery subject - recovery_default_message: Example recovery message - acknowledge_default_subject: Example acknowledge subject - acknowledge_default_message: Example acknowledge message - register: zbxaction_ack_msgsubj - - - assert: - that: zbxaction_ack_msgsubj.changed is sameas False + - name: test - update action with esc_period + community.zabbix.zabbix_action: + esc_period: 120 + register: zbxaction_escperiod + + - ansible.builtin.assert: + that: zbxaction_escperiod.changed is sameas True + + - name: test - update action with esc_period (again) + community.zabbix.zabbix_action: + esc_period: 120 + register: zbxaction_escperiod + + - ansible.builtin.assert: + that: zbxaction_escperiod.changed is sameas False + + - name: test - update action with pause_in_maintenance + community.zabbix.zabbix_action: + esc_period: 120 + pause_in_maintenance: false + register: zbxaction_maintpause + + - ansible.builtin.assert: + that: zbxaction_maintpause.changed is sameas True + + - name: test - update action with pause_in_maintenance (again) + community.zabbix.zabbix_action: + esc_period: 120 + pause_in_maintenance: false + register: zbxaction_maintpause + + - ansible.builtin.assert: + that: zbxaction_maintpause.changed is sameas False - name: test - reset action to default - zabbix_action: + community.zabbix.zabbix_action: register: zbxaction_reset - - assert: + - ansible.builtin.assert: that: zbxaction_reset.changed is sameas True - - name: test - disable action - zabbix_action: - status: disabled - register: zbxaction_disable + - name: test - disable action + community.zabbix.zabbix_action: + status: disabled + register: zbxaction_disable - - assert: - that: zbxaction_disable.changed is sameas True + - ansible.builtin.assert: + that: zbxaction_disable.changed is sameas True - - name: test - disable action (again) - zabbix_action: - status: disabled - register: zbxaction_disable + - name: test - disable action (again) + community.zabbix.zabbix_action: + status: disabled + register: zbxaction_disable - - assert: - that: zbxaction_disable.changed is sameas False + - ansible.builtin.assert: + that: zbxaction_disable.changed is sameas False - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete - - assert: - that: zbxaction_delete.changed is sameas True + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True - - name: test - delete action (again) - zabbix_action: - state: absent - register: zbxaction_delete + - name: test - delete action (again) + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete - - assert: - that: zbxaction_delete.changed is sameas False + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas False - name: test - trigger actions with conditions module_defaults: @@ -257,244 +163,245 @@ status: enabled name: ExampleTriggerActionConditions event_source: trigger + notify_if_canceled: true esc_period: 60 operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin block: - - name: test - create new action with multiple conditions - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - - type: trigger_severity - operator: '>=' - value: Average - - type: event_tag_value - value: MyTag - operator: '=' - value2: MyTagValue - - type: time_period - operator: not in - value: 6-7,00:00-24:00 - register: zbxaction_conditions - - - assert: - that: zbxaction_conditions.changed is sameas True - - - name: test - create new action with multiple conditions (again) - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - - type: trigger_severity - operator: '>=' - value: Average - - type: event_tag_value - value: MyTag - operator: '=' - value2: MyTagValue - - type: time_period - operator: not in - value: 6-7,00:00-24:00 - register: zbxaction_conditions - - - assert: - that: zbxaction_conditions.changed is sameas False - - - name: test - create new action with multiple conditions (reorder) - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - - type: event_tag_value - value: MyTag - operator: '=' - value2: MyTagValue - - type: trigger_severity - operator: '>=' - value: Average - - type: time_period - operator: not in - value: 6-7,00:00-24:00 - register: zbxaction_conditions_reorder - - - assert: - that: zbxaction_conditions_reorder.changed is sameas False - - - name: test - update action with multiple conditions by removing one condition - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - - type: event_tag_value - value: MyTag - operator: '=' - value2: MyTagValue - - type: trigger_severity - operator: '>=' - value: Average - register: zbxaction_conditions_delone - - - assert: - that: zbxaction_conditions_delone.changed is sameas True - - - name: test - update action with multiple conditions by changing operators - zabbix_action: - conditions: - - type: host_group - operator: '<>' - value: Linux servers - - type: event_tag_value - value: MyTag - operator: '<>' - value2: MyTagValue - - type: trigger_severity - operator: '<=' - value: Average - register: zbxaction_conditions_operators - - - assert: - that: zbxaction_conditions_operators.changed is sameas True - - - name: test - update action with multiple conditions with operator aliases - zabbix_action: - conditions: - - type: host_group - operator: does not equal - value: Linux servers - - type: event_tag_value - value: MyTag - operator: contains - value2: MyTagValue - - type: trigger_severity - operator: is less than or equals - value: Average - register: zbxaction_conditions_operator_aliases - - - assert: - that: zbxaction_conditions_operator_aliases.changed is sameas True - - - name: test - update action with multiple conditions and evaltype - zabbix_action: - conditions: - - type: host_group - operator: '<>' - value: Linux servers - - type: event_tag_value - value: MyTag - operator: '<>' - value2: MyTagValue - - type: trigger_severity - operator: '<=' - value: Average - eval_type: and - register: zbxaction_conditions_eval - - - assert: - that: zbxaction_conditions_eval.changed is sameas True - - - name: test - update action with multiple conditions and evaltype (again) - zabbix_action: - conditions: - - type: host_group - operator: '<>' - value: Linux servers - - type: event_tag_value - value: MyTag - operator: '<>' - value2: MyTagValue - - type: trigger_severity - operator: '<=' - value: Average - eval_type: and - register: zbxaction_conditions_eval - - - assert: - that: zbxaction_conditions_eval.changed is sameas False - - - name: test - update action with reduced conditions and formula - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - formulaid: A - - type: trigger_severity - operator: '>=' - value: Average - formulaid: B - - type: event_tag_value - value: MyTag - operator: '<>' - value2: MyTagValue - formulaid: C - formula: A and (B or C) - register: zbxaction_conditions_formula - - - assert: - that: zbxaction_conditions_formula.changed is sameas True - - - name: test - update formula used in action with reduced conditions - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - formulaid: A - - type: trigger_severity - operator: '>=' - value: Average - formulaid: B - - type: event_tag_value - value: MyTag - operator: '<>' - value2: MyTagValue - formulaid: C - formula: (A or B) or C - register: zbxaction_conditions_formula - - - assert: - that: zbxaction_conditions_formula.changed is sameas True - - - name: test - update formula used in action with reduced conditions (again) - zabbix_action: - conditions: - - type: host_group - operator: '=' - value: Linux servers - formulaid: A - - type: trigger_severity - operator: '>=' - value: Average - formulaid: B - - type: event_tag_value - value: MyTag - operator: '<>' - value2: MyTagValue - formulaid: C - formula: (A or B) or C - register: zbxaction_conditions_formula - - - assert: - that: zbxaction_conditions_formula.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True + - name: test - create new action with multiple conditions + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + - type: trigger_severity + operator: ">=" + value: Average + - type: event_tag_value + value: MyTag + operator: "=" + value2: MyTagValue + - type: time_period + operator: not in + value: 6-7,00:00-24:00 + register: zbxaction_conditions + + - ansible.builtin.assert: + that: zbxaction_conditions.changed is sameas True + + - name: test - create new action with multiple conditions (again) + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + - type: trigger_severity + operator: ">=" + value: Average + - type: event_tag_value + value: MyTag + operator: "=" + value2: MyTagValue + - type: time_period + operator: not in + value: 6-7,00:00-24:00 + register: zbxaction_conditions + + - ansible.builtin.assert: + that: zbxaction_conditions.changed is sameas False + + - name: test - create new action with multiple conditions (reorder) + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + - type: event_tag_value + value: MyTag + operator: "=" + value2: MyTagValue + - type: trigger_severity + operator: ">=" + value: Average + - type: time_period + operator: not in + value: 6-7,00:00-24:00 + register: zbxaction_conditions_reorder + + - ansible.builtin.assert: + that: zbxaction_conditions_reorder.changed is sameas False + + - name: test - update action with multiple conditions by removing one condition + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + - type: event_tag_value + value: MyTag + operator: "=" + value2: MyTagValue + - type: trigger_severity + operator: ">=" + value: Average + register: zbxaction_conditions_delone + + - ansible.builtin.assert: + that: zbxaction_conditions_delone.changed is sameas True + + - name: test - update action with multiple conditions by changing operators + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "<>" + value: Linux servers + - type: event_tag_value + value: MyTag + operator: "<>" + value2: MyTagValue + - type: trigger_severity + operator: "<=" + value: Average + register: zbxaction_conditions_operators + + - ansible.builtin.assert: + that: zbxaction_conditions_operators.changed is sameas True + + - name: test - update action with multiple conditions with operator aliases + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: does not equal + value: Linux servers + - type: event_tag_value + value: MyTag + operator: contains + value2: MyTagValue + - type: trigger_severity + operator: is less than or equals + value: Average + register: zbxaction_conditions_operator_aliases + + - ansible.builtin.assert: + that: zbxaction_conditions_operator_aliases.changed is sameas True + + - name: test - update action with multiple conditions and evaltype + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "<>" + value: Linux servers + - type: event_tag_value + value: MyTag + operator: "<>" + value2: MyTagValue + - type: trigger_severity + operator: "<=" + value: Average + eval_type: and + register: zbxaction_conditions_eval + + - ansible.builtin.assert: + that: zbxaction_conditions_eval.changed is sameas True + + - name: test - update action with multiple conditions and evaltype (again) + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "<>" + value: Linux servers + - type: event_tag_value + value: MyTag + operator: "<>" + value2: MyTagValue + - type: trigger_severity + operator: "<=" + value: Average + eval_type: and + register: zbxaction_conditions_eval + + - ansible.builtin.assert: + that: zbxaction_conditions_eval.changed is sameas False + + - name: test - update action with reduced conditions and formula + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + formulaid: A + - type: trigger_severity + operator: ">=" + value: Average + formulaid: B + - type: event_tag_value + value: MyTag + operator: "<>" + value2: MyTagValue + formulaid: C + formula: A and (B or C) + register: zbxaction_conditions_formula + + - ansible.builtin.assert: + that: zbxaction_conditions_formula.changed is sameas True + + - name: test - update formula used in action with reduced conditions + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + formulaid: A + - type: trigger_severity + operator: ">=" + value: Average + formulaid: B + - type: event_tag_value + value: MyTag + operator: "<>" + value2: MyTagValue + formulaid: C + formula: (A or B) or C + register: zbxaction_conditions_formula + + - ansible.builtin.assert: + that: zbxaction_conditions_formula.changed is sameas True + + - name: test - update formula used in action with reduced conditions (again) + community.zabbix.zabbix_action: + conditions: + - type: host_group + operator: "=" + value: Linux servers + formulaid: A + - type: trigger_severity + operator: ">=" + value: Average + formulaid: B + - type: event_tag_value + value: MyTag + operator: "<>" + value2: MyTagValue + formulaid: C + formula: (A or B) or C + register: zbxaction_conditions_formula + + - ansible.builtin.assert: + that: zbxaction_conditions_formula.changed is sameas False + + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete + + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True - name: test - trigger actions with message operations module_defaults: @@ -503,234 +410,139 @@ status: enabled name: ExampleTriggerActionOperations event_source: trigger + notify_if_canceled: true esc_period: 60 conditions: - type: trigger_severity - operator: '>=' + operator: ">=" value: Average block: - - name: test - create new action with send_message operations - zabbix_action: - operations: - - type: send_message - send_to_users: - - Admin - subject: test_subject - message: test_message - media_type: ExampleMediaTypeForActionModule - operation_condition: not_acknowledged - esc_step_from: 1 - esc_step_to: 2 - - type: send_message - send_to_users: - - Admin - subject: test_subject - message: test_message - media_type: SMS - operation_condition: not_acknowledged - esc_step_from: 2 - esc_step_to: 0 - esc_period: 300 - register: zbxaction_ops - - - assert: - that: zbxaction_ops.changed is sameas True - - - name: test - create new action with send_message operations (again) - zabbix_action: - operations: - - type: send_message - send_to_users: - - Admin - subject: test_subject - message: test_message - media_type: ExampleMediaTypeForActionModule - operation_condition: not_acknowledged - esc_step_from: 1 - esc_step_to: 2 - - type: send_message - send_to_users: - - Admin - subject: test_subject - message: test_message - media_type: SMS - operation_condition: not_acknowledged - esc_step_from: 2 - esc_step_to: 0 - esc_period: 300 - register: zbxaction_ops - - - assert: - that: zbxaction_ops.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True - - - name: test - create new action with escalation steps 1-1 - zabbix_action: - operations: - - type: send_message - send_to_users: - - Admin - media_type: ExampleMediaTypeForActionModule - esc_step_from: 1 - esc_step_to: 1 - register: zbxaction_esc11 + - name: test - create new action with send_message operations + community.zabbix.zabbix_action: + operations: + - type: send_message + send_to_users: + - Admin + subject: test_subject + op_message: test_message + media_type: ExampleMediaTypeForActionModule + operation_condition: not_acknowledged + esc_step_from: 1 + esc_step_to: 2 + - type: send_message + send_to_users: + - Admin + subject: test_subject + op_message: test_message + media_type: SMS + operation_condition: not_acknowledged + esc_step_from: 2 + esc_step_to: 0 + esc_period: 300 + register: zbxaction_ops + + - ansible.builtin.assert: + that: zbxaction_ops.changed is sameas True + + - name: test - create new action with send_message operations (again) + community.zabbix.zabbix_action: + operations: + - type: send_message + send_to_users: + - Admin + subject: test_subject + op_message: test_message + media_type: ExampleMediaTypeForActionModule + operation_condition: not_acknowledged + esc_step_from: 1 + esc_step_to: 2 + - type: send_message + send_to_users: + - Admin + subject: test_subject + op_message: test_message + media_type: SMS + operation_condition: not_acknowledged + esc_step_from: 2 + esc_step_to: 0 + esc_period: 300 + register: zbxaction_ops + + - ansible.builtin.assert: + that: zbxaction_ops.changed is sameas False + + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete + + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True + + - name: test - create new action with escalation steps 1-1 + community.zabbix.zabbix_action: + operations: + - type: send_message + send_to_users: + - Admin + media_type: ExampleMediaTypeForActionModule + esc_step_from: 1 + esc_step_to: 1 + register: zbxaction_esc11 - - assert: - that: zbxaction_esc11.changed is sameas True + - ansible.builtin.assert: + that: zbxaction_esc11.changed is sameas True - - name: test - create new action with escalation steps 1-1 (again) - zabbix_action: - operations: - - type: send_message - send_to_users: - - Admin - media_type: ExampleMediaTypeForActionModule - esc_step_from: 1 - esc_step_to: 1 - register: zbxaction_esc11_again + - name: test - create new action with escalation steps 1-1 (again) + community.zabbix.zabbix_action: + operations: + - type: send_message + send_to_users: + - Admin + media_type: ExampleMediaTypeForActionModule + esc_step_from: 1 + esc_step_to: 1 + register: zbxaction_esc11_again - - assert: - that: zbxaction_esc11_again.changed is sameas False + - ansible.builtin.assert: + that: zbxaction_esc11_again.changed is sameas False + - name: test - update action with escalation steps 2-2 + community.zabbix.zabbix_action: + operations: + - type: send_message + send_to_users: + - Admin + media_type: ExampleMediaTypeForActionModule + esc_step_from: 2 + esc_step_to: 2 + register: zbxaction_esc22 - - name: test - update action with escalation steps 2-2 - zabbix_action: - operations: - - type: send_message - send_to_users: - - Admin - media_type: ExampleMediaTypeForActionModule - esc_step_from: 2 - esc_step_to: 2 - register: zbxaction_esc22 + - ansible.builtin.assert: + that: zbxaction_esc22.changed is sameas True - - assert: - that: zbxaction_esc22.changed is sameas True + - name: test - create new action with escalation steps 2-2 (again) + community.zabbix.zabbix_action: + operations: + - type: send_message + send_to_users: + - Admin + media_type: ExampleMediaTypeForActionModule + esc_step_from: 2 + esc_step_to: 2 + register: zbxaction_esc22_again - - name: test - create new action with escalation steps 2-2 (again) - zabbix_action: - operations: - - type: send_message - send_to_users: - - Admin - media_type: ExampleMediaTypeForActionModule - esc_step_from: 2 - esc_step_to: 2 - register: zbxaction_esc22_again - - - assert: - that: zbxaction_esc11_again.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True -- name: test - trigger actions with remote_script operations with < Zabbix 6.0 - when: zabbix_version is version('6.0', '<') - module_defaults: - community.zabbix.zabbix_action: - state: present - status: enabled - name: ExampleTriggerActionOperations - event_source: trigger - esc_period: 60 - conditions: - - type: trigger_severity - operator: '>=' - value: Average + - ansible.builtin.assert: + that: zbxaction_esc11_again.changed is sameas False - block: - - name: test - create new action with remote_command operations - zabbix_action: - operations: - - type: remote_command - command_type: custom_script - command: /usr/local/bin/do_something.sh - execute_on: agent - run_on_hosts: 0 - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: password - username: root - password: zabbix - - type: remote_command - command_type: global_script - script_name: Ping - run_on_hosts: 0 - register: zbxaction_rmtcmd - - - assert: - that: zbxaction_rmtcmd.changed is sameas True - - - name: test - create new action with remote_command operations (again) - zabbix_action: - operations: - - type: remote_command - command_type: custom_script - command: /usr/local/bin/do_something.sh - execute_on: agent - run_on_hosts: 0 - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: password - username: root - password: zabbix - - type: remote_command - command_type: global_script - script_name: Ping - run_on_hosts: 0 - register: zbxaction_rmtcmd - - - assert: - that: zbxaction_rmtcmd.changed is sameas False - - - name: test - update ssh remote_command auth in action with remote_command operations - zabbix_action: - operations: - - type: remote_command - command_type: custom_script - command: /usr/local/bin/do_something.sh - execute_on: agent - run_on_hosts: 0 - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: public_key - username: root - ssh_privatekey_file: /etc/zabbix/.ssh/id_test - ssh_publickey_file: /etc/zabbix/.ssh/id_test.pub - - type: remote_command - command_type: global_script - script_name: Ping - run_on_hosts: 0 - register: zbxaction_rmtcmd - - - assert: - that: zbxaction_rmtcmd.changed is sameas True - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete + + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True - name: test - discovery actions module_defaults: @@ -742,153 +554,153 @@ esc_period: 60 block: - - name: test - create new discovery action - zabbix_action: - conditions: - - type: host_IP - operator: '=' - value: '192.168.0.1-127' - - type: discovery_object - operator: '=' - value: host - - type: discovery_status - operator: '=' - value: 'discovered' - - type: uptime_or_downtime_duration - operator: '>=' - value: 1800 - operations: - - type: add_host - - type: add_to_host_group - host_groups: - - Linux servers - - type: link_to_template - templates: - - ExampleTemplateForActionModule - - type: enable_host - - type: set_host_inventory_mode - inventory: automatic - register: zbxaction_discovery - - - assert: - that: zbxaction_discovery.changed is sameas True - - - name: test - create new discovery action (again) - zabbix_action: - conditions: - - type: host_IP - operator: '=' - value: '192.168.0.1-127' - - type: discovery_object - operator: '=' - value: host - - type: discovery_status - operator: '=' - value: 'discovered' - - type: uptime_or_downtime_duration - operator: '>=' - value: 1800 - operations: - - type: add_host - - type: add_to_host_group - host_groups: - - Linux servers - - type: link_to_template - templates: - - ExampleTemplateForActionModule - - type: enable_host - - type: set_host_inventory_mode - inventory: automatic - register: zbxaction_discovery - - - assert: - that: zbxaction_discovery.changed is sameas False - - - name: test - update discovery action conditions and operations - zabbix_action: - conditions: - - type: host_IP - operator: '=' - value: '192.168.1.1-127' - - type: discovery_object - operator: '=' - value: host - - type: discovery_status - operator: '=' - value: 'discovered' - - type: uptime_or_downtime_duration - operator: '>=' - value: 2200 - operations: - - type: add_host - - type: add_to_host_group - host_groups: - - Linux servers - - Discovered hosts - - type: link_to_template - templates: - - ExampleTemplateForActionModule - - type: enable_host - - type: send_message - send_to_users: - - Admin - subject: test_subject - message: test_message - media_type: ExampleMediaTypeForActionModule - operation_condition: not_acknowledged - esc_step_from: 1 - esc_step_to: 2 - register: zbxaction_discovery_update - - - assert: - that: zbxaction_discovery_update.changed is sameas True - - - name: test - update discovery action conditions and operations (again) - zabbix_action: - conditions: - - type: host_IP - operator: '=' - value: '192.168.1.1-127' - - type: discovery_object - operator: '=' - value: host - - type: discovery_status - operator: '=' - value: 'discovered' - - type: uptime_or_downtime_duration - operator: '>=' - value: 2200 - operations: - - type: add_host - - type: add_to_host_group - host_groups: - - Linux servers - - Discovered hosts - - type: link_to_template - templates: - - ExampleTemplateForActionModule - - type: enable_host - - type: send_message - send_to_users: - - Admin - subject: test_subject - message: test_message - media_type: ExampleMediaTypeForActionModule - operation_condition: not_acknowledged - esc_step_from: 1 - esc_step_to: 2 - register: zbxaction_discovery_update + - name: test - create new discovery action + community.zabbix.zabbix_action: + conditions: + - type: host_IP + operator: "=" + value: "192.168.0.1-127" + - type: discovery_object + operator: "=" + value: host + - type: discovery_status + operator: "=" + value: "discovered" + - type: uptime_or_downtime_duration + operator: ">=" + value: 1800 + operations: + - type: add_host + - type: add_to_host_group + host_groups: + - Linux servers + - type: link_to_template + templates: + - ExampleTemplateForActionModule + - type: enable_host + - type: set_host_inventory_mode + inventory: automatic + register: zbxaction_discovery + + - ansible.builtin.assert: + that: zbxaction_discovery.changed is sameas True + + - name: test - create new discovery action (again) + community.zabbix.zabbix_action: + conditions: + - type: host_IP + operator: "=" + value: "192.168.0.1-127" + - type: discovery_object + operator: "=" + value: host + - type: discovery_status + operator: "=" + value: "discovered" + - type: uptime_or_downtime_duration + operator: ">=" + value: 1800 + operations: + - type: add_host + - type: add_to_host_group + host_groups: + - Linux servers + - type: link_to_template + templates: + - ExampleTemplateForActionModule + - type: enable_host + - type: set_host_inventory_mode + inventory: automatic + register: zbxaction_discovery + + - ansible.builtin.assert: + that: zbxaction_discovery.changed is sameas False + + - name: test - update discovery action conditions and operations + community.zabbix.zabbix_action: + conditions: + - type: host_IP + operator: "=" + value: "192.168.1.1-127" + - type: discovery_object + operator: "=" + value: host + - type: discovery_status + operator: "=" + value: "discovered" + - type: uptime_or_downtime_duration + operator: ">=" + value: 2200 + operations: + - type: add_host + - type: add_to_host_group + host_groups: + - Linux servers + - Discovered hosts + - type: link_to_template + templates: + - ExampleTemplateForActionModule + - type: enable_host + - type: send_message + send_to_users: + - Admin + subject: test_subject + op_message: test_message + media_type: ExampleMediaTypeForActionModule + operation_condition: not_acknowledged + esc_step_from: 1 + esc_step_to: 2 + register: zbxaction_discovery_update + + - ansible.builtin.assert: + that: zbxaction_discovery_update.changed is sameas True + + - name: test - update discovery action conditions and operations (again) + community.zabbix.zabbix_action: + conditions: + - type: host_IP + operator: "=" + value: "192.168.1.1-127" + - type: discovery_object + operator: "=" + value: host + - type: discovery_status + operator: "=" + value: "discovered" + - type: uptime_or_downtime_duration + operator: ">=" + value: 2200 + operations: + - type: add_host + - type: add_to_host_group + host_groups: + - Linux servers + - Discovered hosts + - type: link_to_template + templates: + - ExampleTemplateForActionModule + - type: enable_host + - type: send_message + send_to_users: + - Admin + subject: test_subject + op_message: test_message + media_type: ExampleMediaTypeForActionModule + operation_condition: not_acknowledged + esc_step_from: 1 + esc_step_to: 2 + register: zbxaction_discovery_update - - assert: - that: zbxaction_discovery_update.changed is sameas False + - ansible.builtin.assert: + that: zbxaction_discovery_update.changed is sameas False - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete - - assert: - that: zbxaction_delete.changed is sameas True + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True - name: test - auto registration actions module_defaults: @@ -900,83 +712,83 @@ esc_period: 60 block: - - name: test - create new auto registration action - zabbix_action: - conditions: - - type: host_name - operator: like - value: zabbix - - type: host_metadata - operator: not like - value: somemetadata - operations: - - type: add_host - register: zbxaction_autoreg - - - assert: - that: zbxaction_autoreg.changed is sameas True - - - name: test - create new auto registration action (again) - zabbix_action: - conditions: - - type: host_name - operator: like - value: zabbix - - type: host_metadata - operator: not like - value: somemetadata - operations: - - type: add_host - register: zbxaction_autoreg - - - assert: - that: zbxaction_autoreg.changed is sameas False - - - name: test - update auto registration action - zabbix_action: - conditions: - - type: host_name - operator: like - value: zabbix - - type: host_metadata - operator: not like - value: somemetadata - - type: host_metadata - operator: like - value: somemetadata2 - operations: - - type: add_host - register: zbxaction_autoreg_update - - - assert: - that: zbxaction_autoreg_update.changed is sameas True - - - name: test - update auto registration action (again) - zabbix_action: - conditions: - - type: host_name - operator: like - value: zabbix - - type: host_metadata - operator: not like - value: somemetadata - - type: host_metadata - operator: like - value: somemetadata2 - operations: - - type: add_host - register: zbxaction_autoreg_update - - - assert: - that: zbxaction_autoreg_update.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True + - name: test - create new auto registration action + community.zabbix.zabbix_action: + conditions: + - type: host_name + operator: like + value: zabbix + - type: host_metadata + operator: not like + value: somemetadata + operations: + - type: add_host + register: zbxaction_autoreg + + - ansible.builtin.assert: + that: zbxaction_autoreg.changed is sameas True + + - name: test - create new auto registration action (again) + community.zabbix.zabbix_action: + conditions: + - type: host_name + operator: like + value: zabbix + - type: host_metadata + operator: not like + value: somemetadata + operations: + - type: add_host + register: zbxaction_autoreg + + - ansible.builtin.assert: + that: zbxaction_autoreg.changed is sameas False + + - name: test - update auto registration action + community.zabbix.zabbix_action: + conditions: + - type: host_name + operator: like + value: zabbix + - type: host_metadata + operator: not like + value: somemetadata + - type: host_metadata + operator: like + value: somemetadata2 + operations: + - type: add_host + register: zbxaction_autoreg_update + + - ansible.builtin.assert: + that: zbxaction_autoreg_update.changed is sameas True + + - name: test - update auto registration action (again) + community.zabbix.zabbix_action: + conditions: + - type: host_name + operator: like + value: zabbix + - type: host_metadata + operator: not like + value: somemetadata + - type: host_metadata + operator: like + value: somemetadata2 + operations: + - type: add_host + register: zbxaction_autoreg_update + + - ansible.builtin.assert: + that: zbxaction_autoreg_update.changed is sameas False + + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete + + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True - name: test - internal actions module_defaults: @@ -991,387 +803,224 @@ send_to_users: - Admin subject: test_subject - message: test_message - media_type: ExampleMediaTypeForActionModule - - block: - - name: test - create new internal action - zabbix_action: - conditions: - - type: host_template - operator: '=' - value: ExampleTemplateForActionModule - - type: event_type - operator: '=' - value: item in not supported state - register: zbxaction_internal - - - assert: - that: zbxaction_internal.changed is sameas True - - - name: test - create new internal action (again) - zabbix_action: - conditions: - - type: host_template - operator: '=' - value: ExampleTemplateForActionModule - - type: event_type - operator: '=' - value: item in not supported state - register: zbxaction_internal - - - assert: - that: zbxaction_internal.changed is sameas False - - - name: test - update internal action conditions - zabbix_action: - conditions: - - type: host_template - operator: '=' - value: ExampleTemplateForActionModule - - type: event_type - operator: '=' - value: item in not supported state - - type: event_type - operator: '=' - value: trigger in unknown state - register: zbxaction_internal_update - - - assert: - that: zbxaction_internal_update.changed is sameas True - - - name: test - update internal action conditions (again) - zabbix_action: - conditions: - - type: host_template - operator: '=' - value: ExampleTemplateForActionModule - - type: event_type - operator: '=' - value: item in not supported state - - type: event_type - operator: '=' - value: trigger in unknown state - register: zbxaction_internal_update - - - assert: - that: zbxaction_internal_update.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True - -- name: test - actions with recovery and acknowledge operations with < Zabbix 6.0 - when: - - zabbix_version is version('3.4', '>=') - - zabbix_version is version('6.0', '<') - module_defaults: - community.zabbix.zabbix_action: - state: present - status: enabled - name: ExampleTriggerActionRecAckOps - event_source: trigger - esc_period: 60 - conditions: - - type: trigger_severity - operator: '>=' - value: Information - operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage + op_message: test_message media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin block: - - name: test - create new action with recovery and acknowledge operations - zabbix_action: - recovery_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: remote_command - command_type: custom_script - command: /usr/local/bin/do_something.sh - execute_on: agent - run_on_hosts: 0 - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: password - username: root - password: zabbix - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - acknowledge_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: public_key - username: root - ssh_privatekey_file: /etc/zabbix/.ssh/id_test - ssh_publickey_file: /etc/zabbix/.ssh/id_test.pub - - type: remote_command - command_type: global_script - script_name: Ping - run_on_hosts: 0 - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - media_type: ExampleMediaTypeForActionModule - register: zbxaction_recack_new - - - assert: - that: zbxaction_recack_new.changed is sameas True - - - name: test - create new action with recovery and acknowledge operations (again) - zabbix_action: - recovery_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: remote_command - command_type: custom_script - command: /usr/local/bin/do_something.sh - execute_on: agent - run_on_hosts: 0 - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: password - username: root - password: zabbix - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - acknowledge_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: remote_command - command_type: ssh - command: /usr/local/bin/do_something.sh - run_on_hosts: 0 - ssh_auth_type: public_key - username: root - ssh_privatekey_file: /etc/zabbix/.ssh/id_test - ssh_publickey_file: /etc/zabbix/.ssh/id_test.pub - - type: remote_command - command_type: global_script - script_name: Ping - run_on_hosts: 0 - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - media_type: ExampleMediaTypeForActionModule - register: zbxaction_recack_new - - - assert: - that: zbxaction_recack_new.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True - -- name: test - actions with recovery and acknowledge operations with >= Zabbx 6.0 - when: - - zabbix_version is version('6.0', '>=') - module_defaults: + - name: test - create new internal action + community.zabbix.zabbix_action: + conditions: + - type: host_template + operator: "=" + value: ExampleTemplateForActionModule + - type: event_type + operator: "=" + value: item in not supported state + register: zbxaction_internal + + - ansible.builtin.assert: + that: zbxaction_internal.changed is sameas True + + - name: test - create new internal action (again) + community.zabbix.zabbix_action: + conditions: + - type: host_template + operator: "=" + value: ExampleTemplateForActionModule + - type: event_type + operator: "=" + value: item in not supported state + register: zbxaction_internal + + - ansible.builtin.assert: + that: zbxaction_internal.changed is sameas False + + - name: test - update internal action conditions + community.zabbix.zabbix_action: + conditions: + - type: host_template + operator: "=" + value: ExampleTemplateForActionModule + - type: event_type + operator: "=" + value: item in not supported state + - type: event_type + operator: "=" + value: trigger in unknown state + register: zbxaction_internal_update + + - ansible.builtin.assert: + that: zbxaction_internal_update.changed is sameas True + + - name: test - update internal action conditions (again) + community.zabbix.zabbix_action: + conditions: + - type: host_template + operator: "=" + value: ExampleTemplateForActionModule + - type: event_type + operator: "=" + value: item in not supported state + - type: event_type + operator: "=" + value: trigger in unknown state + register: zbxaction_internal_update + + - ansible.builtin.assert: + that: zbxaction_internal_update.changed is sameas False + + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete + + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True + +- module_defaults: community.zabbix.zabbix_action: state: present status: enabled name: ExampleTriggerActionRecAckOps event_source: trigger + notify_if_canceled: true esc_period: 60 conditions: - type: trigger_severity - operator: '>=' + operator: ">=" value: Information operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin block: - - name: test - create new action with recovery and acknowledge operations - zabbix_action: - recovery_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - acknowledge_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - media_type: ExampleMediaTypeForActionModule - register: zbxaction_recack_new - - - assert: - that: zbxaction_recack_new.changed is sameas True - - - name: test - create new action with recovery and acknowledge operations (again) - zabbix_action: - recovery_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - acknowledge_operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - - type: notify_all_involved - subject: RecoverySubject - message: RecoveryMessage - media_type: ExampleMediaTypeForActionModule - register: zbxaction_recack_new - - - assert: - that: zbxaction_recack_new.changed is sameas False - - - when: zabbix_version is version('6.4', '>=') - block: - - name: test - update action with pause_symptoms off - zabbix_action: + - name: test - create new action with recovery and acknowledge operations + community.zabbix.zabbix_action: recovery_operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin - type: notify_all_involved subject: RecoverySubject - message: RecoveryMessage + op_message: RecoveryMessage acknowledge_operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin - type: notify_all_involved subject: RecoverySubject - message: RecoveryMessage + op_message: RecoveryMessage media_type: ExampleMediaTypeForActionModule - pause_symptoms: False - register: zbxaction_pause_symptoms + register: zbxaction_recack_new - - assert: - that: zbxaction_pause_symptoms.changed is sameas True + - ansible.builtin.assert: + that: zbxaction_recack_new.changed is sameas True - - name: test - update action with pause_symptoms off (again) - zabbix_action: + - name: test - create new action with recovery and acknowledge operations (again) + community.zabbix.zabbix_action: recovery_operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin - type: notify_all_involved subject: RecoverySubject - message: RecoveryMessage + op_message: RecoveryMessage acknowledge_operations: - type: send_message subject: ExampleSubject - message: ExampleMessage + op_message: ExampleMessage media_type: ExampleMediaTypeForActionModule send_to_users: - Admin - type: notify_all_involved subject: RecoverySubject - message: RecoveryMessage + op_message: RecoveryMessage media_type: ExampleMediaTypeForActionModule - pause_symptoms: False - register: zbxaction_pause_symptoms - - - assert: - that: zbxaction_pause_symptoms.changed is sameas False - - - name: test - delete action - zabbix_action: - state: absent - register: zbxaction_delete - - - assert: - that: zbxaction_delete.changed is sameas True - -- name: test - Output error message when user sets application to conditions with >= Zabbix 5.4 - community.zabbix.zabbix_action: - name: ExampleApplicationAction - event_source: trigger - esc_period: 60 - conditions: - - type: application - operator: like - value: AnsibleTest - operations: - - type: send_message - subject: ExampleSubject - message: ExampleMessage - media_type: ExampleMediaTypeForActionModule - send_to_users: - - Admin - ignore_errors: true - register: zbxaction_application - -- assert: - that: - - zbxaction_application.failed is sameas True - - zbxaction_application.msg == "'application' is disabled for condition type since 5.4 version." - when: zabbix_version is version('5.4', '>=') + register: zbxaction_recack_new + + - ansible.builtin.assert: + that: zbxaction_recack_new.changed is sameas False + + - when: zabbix_version is version('6.4', '>=') + block: + - name: test - update action with pause_symptoms off + community.zabbix.zabbix_action: + recovery_operations: + - type: send_message + subject: ExampleSubject + op_message: ExampleMessage + media_type: ExampleMediaTypeForActionModule + send_to_users: + - Admin + - type: notify_all_involved + subject: RecoverySubject + op_message: RecoveryMessage + acknowledge_operations: + - type: send_message + subject: ExampleSubject + op_message: ExampleMessage + media_type: ExampleMediaTypeForActionModule + send_to_users: + - Admin + - type: notify_all_involved + subject: RecoverySubject + op_message: RecoveryMessage + media_type: ExampleMediaTypeForActionModule + pause_symptoms: False + register: zbxaction_pause_symptoms + + - ansible.builtin.assert: + that: zbxaction_pause_symptoms.changed is sameas True + + - name: test - update action with pause_symptoms off (again) + community.zabbix.zabbix_action: + recovery_operations: + - type: send_message + subject: ExampleSubject + op_message: ExampleMessage + media_type: ExampleMediaTypeForActionModule + send_to_users: + - Admin + - type: notify_all_involved + subject: RecoverySubject + op_message: RecoveryMessage + acknowledge_operations: + - type: send_message + subject: ExampleSubject + op_message: ExampleMessage + media_type: ExampleMediaTypeForActionModule + send_to_users: + - Admin + - type: notify_all_involved + subject: RecoverySubject + op_message: RecoveryMessage + media_type: ExampleMediaTypeForActionModule + pause_symptoms: False + register: zbxaction_pause_symptoms + + - ansible.builtin.assert: + that: zbxaction_pause_symptoms.changed is sameas False + + - name: test - delete action + community.zabbix.zabbix_action: + state: absent + register: zbxaction_delete + + - ansible.builtin.assert: + that: zbxaction_delete.changed is sameas True - name: delete ExampleApplicationAction action community.zabbix.zabbix_action: @@ -1379,14 +1028,13 @@ state: absent - name: test - cleanup example template for zabbix_action module - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleTemplateForActionModule - timeout: 20 state: absent register: zbxaction_prep_template - name: test - cleanup example mediatype for zabbix_action module - zabbix_mediatype: + community.zabbix.zabbix_mediatype: name: ExampleMediaTypeForActionModule type: email state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_screen/meta/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_api_info/meta/main.yml index acdb704c8..acdb704c8 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_screen/meta/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_api_info/meta/main.yml diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_api_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_api_info/tasks/main.yml new file mode 100644 index 000000000..cb28929a4 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_api_info/tasks/main.yml @@ -0,0 +1,9 @@ +--- +- name: Retrieve API information + community.zabbix.zabbix_api_info: + register: zbxapiinfo_get + +- ansible.builtin.assert: + that: + - zbxapiinfo_get.failed is sameas False + - zbxapiinfo_get.api.version is version(zabbix_version, '>=') diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/main.yml index f6364f35a..37b1d2c9a 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/main.yml @@ -1,10 +1,10 @@ --- - block: - - include_tasks: zabbix_authentication_tests.yml + - include_tasks: zabbix_authentication_tests.yml always: - - name: Cleanup - zabbix_user_directory: - name: TestUserDirectory - state: absent - ignore_errors: true + - name: Cleanup + community.zabbix.zabbix_user_directory: + name: TestUserDirectory + state: absent + ignore_errors: true diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/zabbix_authentication_tests.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/zabbix_authentication_tests.yml index effc1b900..90b8b7868 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/zabbix_authentication_tests.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_authentication/tasks/zabbix_authentication_tests.yml @@ -1,71 +1,53 @@ --- -- name: test - do not run tests with < Zabbix 4.0 - meta: end_play - when: zabbix_version is version('4.0', '<') - -- when: zabbix_version is version('5.4', '<') - name: Unsupport Zabbix version (<5.4) - block: - - name: test - fail to update authentication setting - zabbix_authentication: - authentication_type: internal - ignore_errors: true - register: zbxauth_update - - - assert: - that: zbxauth_update.failed is sameas True - -- when: - - zabbix_version is version('5.4', '>=') - - zabbix_version is version('6.0', '<=') - name: support Zabbix version (>=5.4 <=6.0) +- when: zabbix_version is version('6.0', '=') + name: support Zabbix version (=6.0) block: - - name: test - update ldap_configured without mandatory paramters - zabbix_authentication: + - name: test - update ldap_configured without mandatory paramters + community.zabbix.zabbix_authentication: ldap_configured: true ignore_errors: true register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: - zbxauth_update.failed is sameas True - zbxauth_update.msg == "Please set ldap_host, ldap_search_attribute and ldap_base_dn when you change a value of ldap_configured to true." - - name: test - update saml_auth_enabled without mandatory paramters - zabbix_authentication: + - name: test - update saml_auth_enabled without mandatory paramters + community.zabbix.zabbix_authentication: saml_auth_enabled: true ignore_errors: true register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: - zbxauth_update.failed is sameas True - zbxauth_update.msg == "Please set saml_idp_entityid, saml_sso_url, saml_username_attribute and saml_sp_entityid when you change a value of saml_auth_enabled to true." - name: test - update all authentication setting - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form - http_strip_domains: 'comp,any' + http_strip_domains: "comp,any" http_case_sensitive: true ldap_configured: true - ldap_host: 'ldap://localhost' + ldap_host: "ldap://localhost" ldap_port: 389 - ldap_base_dn: 'ou=Users,ou=system' - ldap_search_attribute: 'uid' - ldap_bind_dn: 'uid=ldap_search,ou=system' + ldap_base_dn: "ou=Users,ou=system" + ldap_search_attribute: "uid" + ldap_bind_dn: "uid=ldap_search,ou=system" ldap_case_sensitive: true - ldap_bind_password: 'password' + ldap_bind_password: "password" saml_auth_enabled: true - saml_idp_entityid: '' - saml_sso_url: 'https://localhost/SAML2/SSO' - saml_slo_url: 'https://localhost/SAML2/SLO' - saml_username_attribute: 'uid' - saml_sp_entityid: 'https://localhost' - saml_nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity' + saml_idp_entityid: "" + saml_sso_url: "https://localhost/SAML2/SSO" + saml_slo_url: "https://localhost/SAML2/SLO" + saml_username_attribute: "uid" + saml_sp_entityid: "https://localhost" + saml_nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity" saml_sign_messages: true saml_sign_assertions: true saml_sign_authn_requests: true @@ -83,11 +65,11 @@ register: zbxauth_update - name: assert that authentication was updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas True - name: test - update all authentication setting (again) - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form @@ -96,20 +78,20 @@ - any http_case_sensitive: true ldap_configured: true - ldap_host: 'ldap://localhost' + ldap_host: "ldap://localhost" ldap_port: 389 - ldap_base_dn: 'ou=Users,ou=system' - ldap_search_attribute: 'uid' - ldap_bind_dn: 'uid=ldap_search,ou=system' + ldap_base_dn: "ou=Users,ou=system" + ldap_search_attribute: "uid" + ldap_bind_dn: "uid=ldap_search,ou=system" ldap_case_sensitive: true - ldap_bind_password: 'password' + ldap_bind_password: "password" saml_auth_enabled: true - saml_idp_entityid: '' - saml_sso_url: 'https://localhost/SAML2/SSO' - saml_slo_url: 'https://localhost/SAML2/SLO' - saml_username_attribute: 'uid' - saml_sp_entityid: 'https://localhost' - saml_nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity' + saml_idp_entityid: "" + saml_sso_url: "https://localhost/SAML2/SSO" + saml_slo_url: "https://localhost/SAML2/SLO" + saml_username_attribute: "uid" + saml_sp_entityid: "https://localhost" + saml_nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity" saml_sign_messages: true saml_sign_assertions: true saml_sign_authn_requests: true @@ -127,31 +109,31 @@ register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas False - name: test - initialize all authentication setting - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: false http_login_form: zabbix_login_form http_strip_domains: [] http_case_sensitive: true ldap_configured: false - ldap_host: '' + ldap_host: "" ldap_port: 389 - ldap_base_dn: '' - ldap_search_attribute: '' - ldap_bind_dn: '' + ldap_base_dn: "" + ldap_search_attribute: "" + ldap_bind_dn: "" ldap_case_sensitive: true - ldap_bind_password: '' + ldap_bind_password: "" saml_auth_enabled: false - saml_idp_entityid: '' - saml_sso_url: '' - saml_slo_url: '' - saml_username_attribute: '' - saml_sp_entityid: '' - saml_nameid_format: '' + saml_idp_entityid: "" + saml_sso_url: "" + saml_slo_url: "" + saml_username_attribute: "" + saml_sp_entityid: "" + saml_nameid_format: "" saml_sign_messages: false saml_sign_assertions: false saml_sign_authn_requests: false @@ -166,62 +148,61 @@ register: zbxauth_update - name: assert that authentication was updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas True -- when: - - zabbix_version is version('6.2', '=') +- when: zabbix_version is version('6.2', '=') name: support Zabbix version (=6.2) block: - name: test - create user directory - zabbix_user_directory: + community.zabbix.zabbix_user_directory: name: TestUserDirectory - host: 'test.com' + host: "test.com" port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - - - name: test - update ldap_configured without mandatory paramters - zabbix_authentication: + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + + - name: test - update ldap_configured without mandatory paramters + community.zabbix.zabbix_authentication: ldap_configured: true ignore_errors: true register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: - zbxauth_update.failed is sameas True - zbxauth_update.msg == "Please set ldap_userdirectory when you change a value of ldap_configured to true." - - name: test - update saml_auth_enabled without mandatory paramters - zabbix_authentication: + - name: test - update saml_auth_enabled without mandatory paramters + community.zabbix.zabbix_authentication: saml_auth_enabled: true ignore_errors: true register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: - zbxauth_update.failed is sameas True - zbxauth_update.msg == "Please set saml_idp_entityid, saml_sso_url, saml_username_attribute and saml_sp_entityid when you change a value of saml_auth_enabled to true." - name: test - update all authentication setting - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form - http_strip_domains: 'comp,any' + http_strip_domains: "comp,any" http_case_sensitive: true ldap_configured: true ldap_case_sensitive: true ldap_userdirectory: TestUserDirectory saml_auth_enabled: true - saml_idp_entityid: '' - saml_sso_url: 'https://localhost/SAML2/SSO' - saml_slo_url: 'https://localhost/SAML2/SLO' - saml_username_attribute: 'uid' - saml_sp_entityid: 'https://localhost' - saml_nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity' + saml_idp_entityid: "" + saml_sso_url: "https://localhost/SAML2/SSO" + saml_slo_url: "https://localhost/SAML2/SLO" + saml_username_attribute: "uid" + saml_sp_entityid: "https://localhost" + saml_nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity" saml_sign_messages: true saml_sign_assertions: true saml_sign_authn_requests: true @@ -239,11 +220,11 @@ register: zbxauth_update - name: assert that authentication was updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas True - name: test - update all authentication setting (again) - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form @@ -255,12 +236,12 @@ ldap_case_sensitive: true ldap_userdirectory: TestUserDirectory saml_auth_enabled: true - saml_idp_entityid: '' - saml_sso_url: 'https://localhost/SAML2/SSO' - saml_slo_url: 'https://localhost/SAML2/SLO' - saml_username_attribute: 'uid' - saml_sp_entityid: 'https://localhost' - saml_nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity' + saml_idp_entityid: "" + saml_sso_url: "https://localhost/SAML2/SSO" + saml_slo_url: "https://localhost/SAML2/SLO" + saml_username_attribute: "uid" + saml_sp_entityid: "https://localhost" + saml_nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:entity" saml_sign_messages: true saml_sign_assertions: true saml_sign_authn_requests: true @@ -278,11 +259,11 @@ register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas False - name: test - initialize all authentication setting - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: false http_login_form: zabbix_login_form @@ -291,12 +272,12 @@ ldap_configured: false ldap_case_sensitive: true saml_auth_enabled: false - saml_idp_entityid: '' - saml_sso_url: '' - saml_slo_url: '' - saml_username_attribute: '' - saml_sp_entityid: '' - saml_nameid_format: '' + saml_idp_entityid: "" + saml_sso_url: "" + saml_slo_url: "" + saml_username_attribute: "" + saml_sp_entityid: "" + saml_nameid_format: "" saml_sign_messages: false saml_sign_assertions: false saml_sign_authn_requests: false @@ -311,43 +292,43 @@ register: zbxauth_update - name: assert that authentication was updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas True - name: test - delete user directory - zabbix_user_directory: + community.zabbix.zabbix_user_directory: name: TestUserDirectory state: absent - when: zabbix_version is version('6.4', '>=') name: support Zabbix version (>=6.4) block: - - name: test - update ldap_configured without mandatory paramters - zabbix_authentication: + - name: test - update ldap_configured without mandatory paramters + community.zabbix.zabbix_authentication: ldap_auth_enabled: true ignore_errors: true register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: - zbxauth_update.failed is sameas True - zbxauth_update.msg == "Please set ldap_userdirectory when you change a value of ldap_auth_enabled to true." - name: test - create LDAP user directory - zabbix_user_directory: + community.zabbix.zabbix_user_directory: name: TestUserDirectory idp_type: ldap - host: 'test.ca' + host: "test.ca" port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" provision_status: True group_name: cn group_basedn: ou=Group,dc=example,dc=org group_member: member user_ref_attr: uid - group_filter: '(member=uid=%{ref},ou=Users,dc=example,dc=com)' + group_filter: "(member=uid=%{ref},ou=Users,dc=example,dc=com)" user_username: first_name user_lastname: last_name provision_media: @@ -361,11 +342,11 @@ - Guests - name: test - update all authentication setting - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form - http_strip_domains: 'comp,any' + http_strip_domains: "comp,any" http_case_sensitive: true ldap_auth_enabled: true ldap_case_sensitive: true @@ -385,15 +366,15 @@ register: zbxauth_update - name: assert that authentication was updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas True - name: test - update all authentication setting (again) - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: true http_login_form: zabbix_login_form - http_strip_domains: 'comp,any' + http_strip_domains: "comp,any" http_case_sensitive: true ldap_auth_enabled: true ldap_case_sensitive: true @@ -413,11 +394,11 @@ register: zbxauth_update - name: assert that authentication was NOT updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas False - name: test - initialize all authentication setting - zabbix_authentication: + community.zabbix.zabbix_authentication: authentication_type: internal http_auth_enabled: false http_login_form: zabbix_login_form @@ -435,5 +416,5 @@ register: zbxauth_update - name: assert that authentication was updated - assert: + ansible.builtin.assert: that: zbxauth_update.changed is sameas True diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_autoregister/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_autoregister/tasks/main.yml index 3dcf93dbe..797ad2c2c 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_autoregister/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_autoregister/tasks/main.yml @@ -1,108 +1,87 @@ --- -- name: test - do not run tests with < Zabbix 4.0 - meta: end_play - when: zabbix_version is version('4.0', '<') - -- when: zabbix_version is version('4.4', '<') - name: Unsupport Zabbix version (<4.4) - block: - - name: test fail to update autoregistration - community.zabbix.zabbix_autoregister: - tls_accept: "tls_with_psk" - tls_psk_identity: 'PSK 001' - tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" - register: zbxautoregister_update_result - ignore_errors: true - - - assert: - that: zbxautoregister_update_result.failed is sameas True - -- when: zabbix_version is version('4.4', '>=') - name: Support Zabbix version (>=4.4) - block: - - name: test update autoregistration with no parameter - community.zabbix.zabbix_autoregister: - register: zbxautoregister_update_result - ignore_errors: true - - - assert: - that: zbxautoregister_update_result.failed is sameas True - - - name: test update autoregistration with all parameters - community.zabbix.zabbix_autoregister: - tls_accept: - - unsecure - - tls_with_psk - tls_psk_identity: 'PSK 001' - tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" - register: zbxautoregister_update_result - - - assert: - that: zbxautoregister_update_result.changed is sameas True - - - name: test update autoregistration with all parameters (again) - community.zabbix.zabbix_autoregister: - tls_accept: - - unsecure - - tls_with_psk - tls_psk_identity: 'PSK 001' - tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" - register: zbxautoregister_update_result - - - assert: - that: zbxautoregister_update_result.changed is sameas True - - - name: test update autoregistration with only tls_accept - community.zabbix.zabbix_autoregister: - tls_accept: "tls_with_psk" - register: zbxautoregister_update_result - - - assert: - that: zbxautoregister_update_result.changed is sameas True - - - name: test update autoregistration with only tls_accept (again) - community.zabbix.zabbix_autoregister: - tls_accept: - - tls_with_psk - register: zbxautoregister_update_result - - - assert: - that: zbxautoregister_update_result.changed is sameas False - - - name: test update autoregistration with only tls_accept (unsecure) - community.zabbix.zabbix_autoregister: - tls_accept: - - unsecure - register: zbxautoregister_update_result - - - assert: - that: zbxautoregister_update_result.changed is sameas True - - - name: test fail to update autoregistration with only tls_accept (tls_with_psk) - community.zabbix.zabbix_autoregister: - tls_accept: "tls_with_psk" - register: zbxautoregister_update_result - ignore_errors: true - - - assert: - that: zbxautoregister_update_result.failed is sameas True - - - name: test fail to update autoregistration with only tls_accept and tls_psk_identity (tls_with_psk) - community.zabbix.zabbix_autoregister: - tls_accept: "tls_with_psk" - tls_psk_identity: 'PSK 001' - register: zbxautoregister_update_result - ignore_errors: true - - - assert: - that: zbxautoregister_update_result.failed is sameas True - - - name: test fail to update autoregistration with only tls_accept and tls_psk (tls_with_psk) - community.zabbix.zabbix_autoregister: - tls_accept: "tls_with_psk" - tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" - register: zbxautoregister_update_result - ignore_errors: true - - - assert: - that: zbxautoregister_update_result.failed is sameas True +- name: test update autoregistration with no parameter + community.zabbix.zabbix_autoregister: + register: zbxautoregister_update_result + ignore_errors: true + +- ansible.builtin.assert: + that: zbxautoregister_update_result.failed is sameas True + +- name: test update autoregistration with all parameters + community.zabbix.zabbix_autoregister: + tls_accept: + - unsecure + - tls_with_psk + tls_psk_identity: "PSK 001" + tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" + register: zbxautoregister_update_result + +- ansible.builtin.assert: + that: zbxautoregister_update_result.changed is sameas True + +- name: test update autoregistration with all parameters (again) + community.zabbix.zabbix_autoregister: + tls_accept: + - unsecure + - tls_with_psk + tls_psk_identity: "PSK 001" + tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" + register: zbxautoregister_update_result + +- ansible.builtin.assert: + that: zbxautoregister_update_result.changed is sameas True + +- name: test update autoregistration with only tls_accept + community.zabbix.zabbix_autoregister: + tls_accept: "tls_with_psk" + register: zbxautoregister_update_result + +- ansible.builtin.assert: + that: zbxautoregister_update_result.changed is sameas True + +- name: test update autoregistration with only tls_accept (again) + community.zabbix.zabbix_autoregister: + tls_accept: + - tls_with_psk + register: zbxautoregister_update_result + +- ansible.builtin.assert: + that: zbxautoregister_update_result.changed is sameas False + +- name: test update autoregistration with only tls_accept (unsecure) + community.zabbix.zabbix_autoregister: + tls_accept: + - unsecure + register: zbxautoregister_update_result + +- ansible.builtin.assert: + that: zbxautoregister_update_result.changed is sameas True + +- name: test fail to update autoregistration with only tls_accept (tls_with_psk) + community.zabbix.zabbix_autoregister: + tls_accept: "tls_with_psk" + register: zbxautoregister_update_result + ignore_errors: true + +- ansible.builtin.assert: + that: zbxautoregister_update_result.failed is sameas True + +- name: test fail to update autoregistration with only tls_accept and tls_psk_identity (tls_with_psk) + community.zabbix.zabbix_autoregister: + tls_accept: "tls_with_psk" + tls_psk_identity: "PSK 001" + register: zbxautoregister_update_result + ignore_errors: true + +- ansible.builtin.assert: + that: zbxautoregister_update_result.failed is sameas True + +- name: test fail to update autoregistration with only tls_accept and tls_psk (tls_with_psk) + community.zabbix.zabbix_autoregister: + tls_accept: "tls_with_psk" + tls_psk: "11111595725ac58dd977beef14b97461a7c1045b9a1c923453302c5473193478" + register: zbxautoregister_update_result + ignore_errors: true + +- ansible.builtin.assert: + that: zbxautoregister_update_result.failed is sameas True diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_discovery_rule/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_discovery_rule/tasks/main.yml index 16062a52e..cbf13b391 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_discovery_rule/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_discovery_rule/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: test - do not run tests for Zabbix 3.0 - meta: end_play - when: zabbix_version is version('3.0', '=') - - name: test - Zabbix discovery rule module_defaults: community.zabbix.zabbix_discovery_rule: @@ -11,270 +7,269 @@ iprange: 192.168.1.1-255 dchecks: - type: ICMP - delay: "{{ 3600 if zabbix_version is version('3.4', '<=') else omit }}" block: - - name: test - create new Zabbix discovery rule (checkmode) - zabbix_discovery_rule: - check_mode: true - register: drule_new_checkmode - - - name: assert that drule will be created (checkmode) - assert: - that: drule_new_checkmode is changed - - - name: test - create new Zabbix discovery rule - zabbix_discovery_rule: - register: drule_new - - - name: assert that drule was created - assert: - that: drule_new is changed - - - name: test - create same Zabbix discovery rule - zabbix_discovery_rule: - register: drule_exists - - - name: assert that nothing has been changed - assert: - that: not drule_exists is changed - - - name: test - update Zabbix discovery rule iprange (checkmode) - zabbix_discovery_rule: - iprange: - - 192.168.1.1-255 - - 10.0.0.1-255 - check_mode: true - register: drule_iprange_update_checkmode - - - name: assert that iprange will be changed - assert: - that: drule_iprange_update_checkmode is changed - - - name: test - update Zabbix discovery rule iprange - zabbix_discovery_rule: - iprange: - - 192.168.1.1-255 - - 10.0.0.1-255 - register: drule_iprange_update - - - name: assert that iprange has been changed - assert: - that: drule_iprange_update is changed - - - name: test - reset Zabbix discovery rule to default - zabbix_discovery_rule: - register: drule_reset - - - name: assert that iprange has been changed - assert: - that: drule_reset is changed - - - name: test - update Zabbix discovery rule status - zabbix_discovery_rule: - status: disabled - register: drule_status_update - - - name: assert that iprange has been changed - assert: - that: drule_status_update is changed - - - name: test - reset Zabbix discovery rule to default - zabbix_discovery_rule: - register: drule_reset - - - name: assert that iprange has been changed - assert: - that: drule_reset is changed - - - name: test - update Zabbix discovery rule dchecks - zabbix_discovery_rule: - dchecks: - - type: ICMP - - type: Zabbix - key: "system.hostname" - ports: "10050" - uniq: true - host_source: discovery - register: drule_dchecks_update - - - name: assert that dcheck has been changed - assert: - that: drule_dchecks_update is changed - - - name: test - update Zabbix discovery rule dchecks ssh - zabbix_discovery_rule: - dchecks: - - type: ICMP - - type: SSH - ports: "22" - register: drule_dchecks_ssh_update - - - name: assert that dcheck has been changed - assert: - that: drule_dchecks_ssh_update is changed - - - name: test - update Zabbix discovery rule dchecks ldap - zabbix_discovery_rule: - dchecks: - - type: ICMP - - type: SSH - ports: "22" - - type: LDAP - ports: "389" - register: drule_dchecks_ldap_update - - - name: assert that dcheck has been changed - assert: - that: drule_dchecks_ldap_update is changed - - - name: test - update Zabbix discovery rule dchecks smtp - zabbix_discovery_rule: - dchecks: - - type: ICMP - - type: SSH - ports: "22" - - type: LDAP - ports: "389" - - type: SMTP - ports: 25,465,587 - register: drule_dchecks_smtp_update - - - name: assert that dcheck has been changed - assert: - that: drule_dchecks_smtp_update is changed - - - name: test - update Zabbix discovery rule dchecks http - zabbix_discovery_rule: - dchecks: - - type: ICMP - - type: SSH - ports: "22" - - type: LDAP - ports: "389" - - type: SMTP - ports: 25,465,587 - - type: HTTP - ports: 80,8080 - register: drule_dchecks_http_update - - - name: assert that dcheck has been changed - assert: - that: drule_dchecks_http_update is changed - - - name: test - remove Zabbix discovery rule dchecks - zabbix_discovery_rule: - dchecks: - - type: ICMP - register: drule_dchecks_remove_update - - - name: assert that dcheck has been changed - assert: - that: drule_dchecks_remove_update is changed - - - name: test - update Zabbix discovery rule snmp dcheck - zabbix_discovery_rule: - dchecks: - - type: SNMPv2 - snmp_community: CUSTOMER@snmp-readonly - ports: "161" - key: iso.3.6.1.2.1.1.1.0 - uniq: false - host_source: discovery - name_source: discovery - register: drule_snmp_update - - - name: assert that snmp dcheck has been changed - assert: - that: drule_snmp_update is changed - - - name: test - update Zabbix discovery rule snmp3 dcheck - zabbix_discovery_rule: - dchecks: - - type: SNMPv3 - snmp_community: CUSTOMER@snmp3-readonly - ports: "161" - key: iso.3.6.1.2.1.1.1.0 - snmpv3_contextname: "ContextName" - snmpv3_securityname: "SecurityName" - snmpv3_securitylevel: authPriv - snmpv3_authprotocol: SHA - snmpv3_authpassphrase: "SeCrEt" - snmpv3_privprotocol: AES - snmpv3_privpassphrase: "TopSecret" - uniq: false - host_source: DNS - name_source: None - register: drule_snmp3_update - - - name: assert that snmp3 dcheck has been changed - assert: - that: drule_snmp3_update is changed - - - name: test - reset Zabbix discovery rule to default - zabbix_discovery_rule: - register: drule_reset - - - name: assert that iprange has been changed - assert: - that: drule_reset is changed - - - name: test - create new active Zabbix proxy server - zabbix_proxy: - proxy_name: ACME_proxy - status: active - state: present - register: zbxproxy_active - - - name: assert that proxy was created - assert: - that: zbxproxy_active is changed - - - name: test - update Zabbix discovery rule proxy - zabbix_discovery_rule: - proxy: ACME_proxy - register: drule_proxy_update - - - name: assert that proxy has been changed - assert: - that: drule_proxy_update is changed - - - name: test - update Zabbix discovery rule proxy (again) - zabbix_discovery_rule: - proxy: ACME_proxy - register: drule_proxy_update_again - - - name: assert that nothing has been changed - assert: - that: not drule_proxy_update_again is changed + - name: test - create new Zabbix discovery rule (checkmode) + community.zabbix.zabbix_discovery_rule: + check_mode: true + register: drule_new_checkmode + + - name: assert that drule will be created (checkmode) + ansible.builtin.assert: + that: drule_new_checkmode is changed + + - name: test - create new Zabbix discovery rule + community.zabbix.zabbix_discovery_rule: + register: drule_new + + - name: assert that drule was created + ansible.builtin.assert: + that: drule_new is changed + + - name: test - create same Zabbix discovery rule + community.zabbix.zabbix_discovery_rule: + register: drule_exists + + - name: assert that nothing has been changed + ansible.builtin.assert: + that: not drule_exists is changed + + - name: test - update Zabbix discovery rule iprange (checkmode) + community.zabbix.zabbix_discovery_rule: + iprange: + - 192.168.1.1-255 + - 10.0.0.1-255 + check_mode: true + register: drule_iprange_update_checkmode + + - name: assert that iprange will be changed + ansible.builtin.assert: + that: drule_iprange_update_checkmode is changed + + - name: test - update Zabbix discovery rule iprange + community.zabbix.zabbix_discovery_rule: + iprange: + - 192.168.1.1-255 + - 10.0.0.1-255 + register: drule_iprange_update + + - name: assert that iprange has been changed + ansible.builtin.assert: + that: drule_iprange_update is changed + + - name: test - reset Zabbix discovery rule to default + community.zabbix.zabbix_discovery_rule: + register: drule_reset + + - name: assert that iprange has been changed + ansible.builtin.assert: + that: drule_reset is changed + + - name: test - update Zabbix discovery rule status + community.zabbix.zabbix_discovery_rule: + status: disabled + register: drule_status_update + + - name: assert that iprange has been changed + ansible.builtin.assert: + that: drule_status_update is changed + + - name: test - reset Zabbix discovery rule to default + community.zabbix.zabbix_discovery_rule: + register: drule_reset + + - name: assert that iprange has been changed + ansible.builtin.assert: + that: drule_reset is changed + + - name: test - update Zabbix discovery rule dchecks + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: ICMP + - type: Zabbix + key: "system.hostname" + ports: "10050" + uniq: true + host_source: discovery + register: drule_dchecks_update + + - name: assert that dcheck has been changed + ansible.builtin.assert: + that: drule_dchecks_update is changed + + - name: test - update Zabbix discovery rule dchecks ssh + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: ICMP + - type: SSH + ports: "22" + register: drule_dchecks_ssh_update + + - name: assert that dcheck has been changed + ansible.builtin.assert: + that: drule_dchecks_ssh_update is changed + + - name: test - update Zabbix discovery rule dchecks ldap + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: ICMP + - type: SSH + ports: "22" + - type: LDAP + ports: "389" + register: drule_dchecks_ldap_update + + - name: assert that dcheck has been changed + ansible.builtin.assert: + that: drule_dchecks_ldap_update is changed + + - name: test - update Zabbix discovery rule dchecks smtp + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: ICMP + - type: SSH + ports: "22" + - type: LDAP + ports: "389" + - type: SMTP + ports: 25,465,587 + register: drule_dchecks_smtp_update + + - name: assert that dcheck has been changed + ansible.builtin.assert: + that: drule_dchecks_smtp_update is changed + + - name: test - update Zabbix discovery rule dchecks http + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: ICMP + - type: SSH + ports: "22" + - type: LDAP + ports: "389" + - type: SMTP + ports: 25,465,587 + - type: HTTP + ports: 80,8080 + register: drule_dchecks_http_update + + - name: assert that dcheck has been changed + ansible.builtin.assert: + that: drule_dchecks_http_update is changed + + - name: test - remove Zabbix discovery rule dchecks + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: ICMP + register: drule_dchecks_remove_update + + - name: assert that dcheck has been changed + ansible.builtin.assert: + that: drule_dchecks_remove_update is changed + + - name: test - update Zabbix discovery rule snmp dcheck + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: SNMPv2 + snmp_community: CUSTOMER@snmp-readonly + ports: "161" + key: iso.3.6.1.2.1.1.1.0 + uniq: false + host_source: discovery + name_source: discovery + register: drule_snmp_update + + - name: assert that snmp dcheck has been changed + ansible.builtin.assert: + that: drule_snmp_update is changed + + - name: test - update Zabbix discovery rule snmp3 dcheck + community.zabbix.zabbix_discovery_rule: + dchecks: + - type: SNMPv3 + snmp_community: CUSTOMER@snmp3-readonly + ports: "161" + key: iso.3.6.1.2.1.1.1.0 + snmpv3_contextname: "ContextName" + snmpv3_securityname: "SecurityName" + snmpv3_securitylevel: authPriv + snmpv3_authprotocol: SHA + snmpv3_authpassphrase: "SeCrEt" + snmpv3_privprotocol: AES + snmpv3_privpassphrase: "TopSecret" + uniq: false + host_source: DNS + name_source: None + register: drule_snmp3_update + + - name: assert that snmp3 dcheck has been changed + ansible.builtin.assert: + that: drule_snmp3_update is changed + + - name: test - reset Zabbix discovery rule to default + community.zabbix.zabbix_discovery_rule: + register: drule_reset + + - name: assert that iprange has been changed + ansible.builtin.assert: + that: drule_reset is changed + + - name: test - create new active Zabbix proxy server + community.zabbix.zabbix_proxy: + proxy_name: ACME_proxy + status: active + state: present + register: zbxproxy_active + + - name: assert that proxy was created + ansible.builtin.assert: + that: zbxproxy_active is changed + + - name: test - update Zabbix discovery rule proxy + community.zabbix.zabbix_discovery_rule: + proxy: ACME_proxy + register: drule_proxy_update + + - name: assert that proxy has been changed + ansible.builtin.assert: + that: drule_proxy_update is changed + + - name: test - update Zabbix discovery rule proxy (again) + community.zabbix.zabbix_discovery_rule: + proxy: ACME_proxy + register: drule_proxy_update_again + + - name: assert that nothing has been changed + ansible.builtin.assert: + that: not drule_proxy_update_again is changed - name: test - delete Zabbix discovery rule - zabbix_discovery_rule: + community.zabbix.zabbix_discovery_rule: name: ACME state: absent register: drule_delete - name: assert that proxy has been deleted - assert: + ansible.builtin.assert: that: drule_delete is changed - name: test - delete Zabbix discovery rule (again) - zabbix_discovery_rule: + community.zabbix.zabbix_discovery_rule: name: ACME state: absent register: drule_delete_again - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not drule_delete_again is changed # Cleanup - name: delete active Zabbix proxy server - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: ACME_proxy state: absent register: zbxproxy_delete - name: assert that proxy has been deleted - assert: + ansible.builtin.assert: that: zbxproxy_delete is changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_globalmacro/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_globalmacro/tasks/main.yml index ce49f0f86..bc15fec2c 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_globalmacro/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_globalmacro/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: test - attempt to create new global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test01 macro_value: 123 macro_type: text @@ -8,11 +8,11 @@ register: zbxgmacro_new - name: assert that macro was created - assert: + ansible.builtin.assert: that: zbxgmacro_new is changed - name: test - attempt to create same global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test01 macro_value: 123 macro_type: text @@ -20,11 +20,11 @@ register: zbxgmacro_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgmacro_existing is changed - name: test - attempt to create same global macro in zabbix native format - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: "{$zbxgmacro_test01}" macro_value: 123 macro_type: text @@ -32,22 +32,22 @@ register: zbxgmacro_existing_native - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgmacro_existing_native is changed - name: test - attempt to create new global macro in zabbix native format - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: "{$ZBXGMACRO_TEST02}" macro_value: abcd macro_type: text register: zbxgmacro_new_native - name: assert that nothing macro was created - assert: + ansible.builtin.assert: that: zbxgmacro_new_native is changed - name: test - attempt to update global macro with string value while force=no - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test01 macro_value: abc macro_type: text @@ -55,44 +55,44 @@ register: zbxgmacro_update_noforce - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgmacro_update_noforce is changed - name: test - attempt to update global macro with string value - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test01 macro_value: abc macro_type: text register: zbxgmacro_update - name: assert that global macro was updated - assert: + ansible.builtin.assert: that: zbxgmacro_update is changed - name: test - attempt to create global macro with context - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: low_space_limit:/home macro_value: 10 macro_type: text register: zbxgmacro_context_new - name: assert that macro was created - assert: + ansible.builtin.assert: that: zbxgmacro_context_new is changed - name: test - attempt to create same global macro with context and verify that it was converted to uppercase - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: LOW_SPACE_LIMIT:/home macro_value: 10 macro_type: text register: zbxgmacro_context_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgmacro_context_existing is changed - name: test - attempt to delete all global macros - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: "{{ item }}" state: absent loop: @@ -102,71 +102,66 @@ register: zbxgmacro_delete_existing - name: assert that all macros have been deleted - assert: + ansible.builtin.assert: that: item.changed is sameas True loop: "{{ zbxgmacro_delete_existing.results }}" - name: test - attempt to delete non-existing global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test01 state: absent register: zbxgmacro_delete_missing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgmacro_delete_missing is changed - name: test - attempt to create secret global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test_secret macro_value: 123 macro_type: secret macro_description: Global Macro description register: zbxgmacro_secret -- assert: +- ansible.builtin.assert: that: zbxgmacro_secret.changed is sameas True - name: test - attempt to create same global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test_secret macro_value: 123 macro_type: secret macro_description: Global Macro description register: zbxgmacro_secret -- assert: +- ansible.builtin.assert: that: zbxgmacro_secret.changed is sameas True - when: zabbix_version is version('5.0', '>=') - -- assert: - that: zbxgmacro_secret.changed is sameas False - when: zabbix_version is version('5.0', '<') - name: test - attempt to create vault global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test_vault macro_value: path/to/vault:zabbix macro_type: vault macro_description: Global Macro description register: zbxgmacro_vault -- assert: +- ansible.builtin.assert: that: zbxgmacro_vault.changed is sameas True - name: test - attempt to create same global macro - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: zbxgmacro_test_vault macro_value: path/to/vault:zabbix macro_type: vault macro_description: Global Macro description register: zbxgmacro_vault -- assert: +- ansible.builtin.assert: that: zbxgmacro_vault.changed is sameas False - name: delete all global macros - zabbix_globalmacro: + community.zabbix.zabbix_globalmacro: macro_name: "{{ item }}" state: absent loop: diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group/tasks/main.yml index 0f099d7c1..b45711a25 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group/tasks/main.yml @@ -1,17 +1,17 @@ --- - name: test - create new Zabbix group - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 state: present register: zbxgrp_new - name: assert that group was created - assert: + ansible.builtin.assert: that: zbxgrp_new is changed - name: test - create simple zabbix host to assign to group - zabbix_host: + community.zabbix.zabbix_host: host_name: zbxgrp_example_host01 host_groups: - zbxgrp_example_group01 @@ -23,33 +23,33 @@ register: zbxgrp_host_assignement - name: assert that host was assigned successfully - assert: + ansible.builtin.assert: that: zbxgrp_host_assignement is changed - name: test - create same Zabbix group once again - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 state: present register: zbxgrp_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgrp_existing is changed - name: test - attempt to create new Zabbix group matching name of default Zabbix group - zabbix_group: + community.zabbix.zabbix_group: host_groups: - Linux servers state: present register: zbxgrp_default_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgrp_default_existing is changed - name: test - attempt to delete host group while its only group host has assigned - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 state: absent @@ -57,32 +57,32 @@ ignore_errors: true - name: assert that group deletion failed - assert: + ansible.builtin.assert: that: zbxgrp_existing_delete_failed is failed - name: delete helper zabbix host - zabbix_host: + community.zabbix.zabbix_host: host_name: zbxgrp_example_host01 state: absent - name: test - attempt to delete previously created zabbix group - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 state: absent register: zbxgrp_existing_delete - name: assert that group was deleted - assert: + ansible.builtin.assert: that: zbxgrp_existing_delete is changed - name: test - attempt to delete non-existing zabbix group - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 state: absent register: zbxgrp_missing_delete - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxgrp_missing_delete is changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/files/trigger_testing.json b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/files/trigger_testing.json new file mode 100644 index 000000000..a642483f4 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/files/trigger_testing.json @@ -0,0 +1,48 @@ +{ + "zabbix_export": { + "version": "6.0", + "date": "2023-09-05T13:58:23Z", + "groups": [ + { + "uuid": "6932cc6c283949ee8d4c316e2f30af5f", + "name": "Templates" + } + ], + "templates": [ + { + "uuid": "641c10c5445245edb59050c3518e76a0", + "template": "Trigger testing", + "name": "Trigger testing", + "groups": [ + { + "name": "Templates" + } + ], + "items": [ + { + "uuid": "0dce402f6f0c44cfb7796c1ea6c4bb86", + "name": "Test Item", + "type": "CALCULATED", + "key": "test", + "delay": "10s", + "params": "1", + "triggers": [ + { + "uuid": "11b2645a369946dcaa00b6edc578089f", + "expression": "last(/Trigger testing/test)=0", + "name": "Ok Trigger", + "priority": "AVERAGE" + }, + { + "uuid": "f17f4b4f7fe444dfb856bc9d6366d0fe", + "expression": "last(/Trigger testing/test)=1", + "name": "Problem Trigger", + "priority": "AVERAGE" + } + ] + } + ] + } + ] + } +} diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/meta/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/meta/main.yml new file mode 100644 index 000000000..acdb704c8 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/meta/main.yml @@ -0,0 +1,3 @@ +--- +dependencies: + - setup_zabbix diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/tasks/main.yml new file mode 100644 index 000000000..601f5421f --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_events_info/tasks/main.yml @@ -0,0 +1,58 @@ +--- +- name: Import trigger test template + zabbix_template: + template_json: "{{ lookup('file', 'trigger_testing.json') }}" + state: present + +- name: Create host group + zabbix_group: + state: present + host_groups: + - Example group + +- name: Create new host with template + zabbix_host: + host_name: Example host + link_templates: + - Trigger testing + host_groups: + - Example group + +- name: Wait a minute to ensure triggers are firing + ansible.builtin.wait_for: + timeout: 60 + +- name: Get hostgroup events + zabbix_group_events_info: + hostgroup_name: Example group + trigger_severity: not_classified + register: hostgroup_events_results + +- name: Assert that trigger results are as expected + ansible.builtin.assert: + that: + - hostgroup_events_results.triggers_ok[0].description == "Ok Trigger" + - hostgroup_events_results.triggers_ok[0].value == "0" + - hostgroup_events_results.triggers_ok[0].status == "0" + # TODO: Need to figure out why this periodically fails for no reason. False Alarm + # - hostgroup_events_results.triggers_problem[0].description == "Problem Trigger" + # - hostgroup_events_results.triggers_problem[0].value == "1" + # - hostgroup_events_results.triggers_problem[0].status == "0" + # - hostgroup_events_results.triggers_problem[0].last_event.acknowledged == "0" + # - hostgroup_events_results.triggers_problem[0].last_event.value == "1" + +- name: Clean up host + zabbix_host: + host_name: Example host + state: absent + +- name: Clean up host group + zabbix_group: + host_groups: + - Example group + state: absent + +- name: Clean up template + zabbix_template: + template_name: "Trigger testing" + state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_info/tasks/main.yml index 624679603..51c03af3b 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_info/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_group_info/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: test - create new Zabbix group - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 - zbxgrp_example_group02 @@ -8,7 +8,7 @@ register: zbxgrp_new - name: assert that group was created - assert: + ansible.builtin.assert: that: zbxgrp_new is changed - name: test - get one hostgroup info @@ -18,7 +18,7 @@ register: get_hostgorup_info_result - name: assert that one group was get - assert: + ansible.builtin.assert: that: - get_hostgorup_info_result.host_groups | length == 1 - get_hostgorup_info_result.host_groups.0.name == 'zbxgrp_example_group01' @@ -31,14 +31,14 @@ register: get_hostgorup_info_result - name: assert that two group was get - assert: + ansible.builtin.assert: that: - get_hostgorup_info_result.host_groups | length == 2 - get_hostgorup_info_result.host_groups.0.name == 'zbxgrp_example_group01' - get_hostgorup_info_result.host_groups.1.name == 'zbxgrp_example_group02' - name: test - delete Zabbix group - zabbix_group: + community.zabbix.zabbix_group: host_groups: - zbxgrp_example_group01 - zbxgrp_example_group02 @@ -46,5 +46,5 @@ register: delete_zbxgrp - name: assert that group was deleted - assert: + ansible.builtin.assert: that: delete_zbxgrp is changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/main.yml index 20755061f..c4675797f 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/main.yml @@ -12,8 +12,12 @@ # tear down stuff set up earlier - include_tasks: zabbix_host_teardown.yml always: - - name: "cleanup if tests failed" - zabbix_host: - host_name: ExampleHost - state: absent - ignore_errors: true + - name: "cleanup if tests failed" + community.zabbix.zabbix_host: + host_name: "{{ item }}" + state: absent + ignore_errors: true + with_items: + - ExampleHost + - ExampleHost1 + - ExampleHost2 diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_doc.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_doc.yml index 4415e2ca1..c84050dcf 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_doc.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_doc.yml @@ -2,7 +2,7 @@ # These two tests are close to documentation example - name: Create a new host or update an existing host's info - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost1 visible_name: ExampleName description: My ExampleHost Description @@ -10,8 +10,8 @@ - Linux servers - Zabbix servers link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" + - "IMAP Service" + - "NTP Service" status: enabled state: present inventory_mode: manual @@ -41,11 +41,11 @@ dns: "" port: "12345" macros: - - macro: '{$EXAMPLEMACRO}' + - macro: "{$EXAMPLEMACRO}" value: ExampleMacroValue - macro: EXAMPLEMACRO2 value: ExampleMacroValue2 - description: Example desc that work only with Zabbix 4.4 and higher + description: Example desc tags: - tag: ExampleHostsTag - tag: ExampleHostsTag2 @@ -53,7 +53,7 @@ register: zabbix_host1 - name: Update an existing host's tls settings - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost2 visible_name: ExampleName2 interfaces: @@ -71,7 +71,7 @@ register: zabbix_host2 - name: expect both to succeed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - "zabbix_host2 is changed" diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_setup.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_setup.yml index 15e3e2fa5..924119467 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_setup.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_setup.yml @@ -2,14 +2,12 @@ # set up a zabbix proxy to test zabbix_host with - name: Create a new proxy - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: ExampleProxy description: ExampleProxy status: active state: present interface: - type: 0 - main: 1 useip: 1 ip: 10.5.6.7 dns: "" @@ -17,7 +15,7 @@ register: zabbix_proxy - name: Create Templates - zabbix_template: + community.zabbix.zabbix_template: template_name: "{{ item }}" template_groups: - Templates diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_teardown.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_teardown.yml index 7eedcf12d..1617f449f 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_teardown.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_teardown.yml @@ -2,12 +2,12 @@ # remove zabbix_proxy (hopefully) created earlier - name: remove proxy - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: ExampleProxy state: absent - name: remove Templates - zabbix_template: + community.zabbix.zabbix_template: template_name: "{{ item }}" state: absent with_items: diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_tests.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_tests.yml index d72dbe318..a4829a051 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_tests.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host/tasks/zabbix_host_tests.yml @@ -1,7 +1,6 @@ --- - name: "test: create host with many options set" - zabbix_host: - timeout: 30 # slower with py2.7 + community.zabbix.zabbix_host: host_name: ExampleHost visible_name: ExampleName description: My ExampleHost Description @@ -9,8 +8,8 @@ - Linux servers - Zabbix servers link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" + - "IMAP Service" + - "NTP Service" status: enabled state: present inventory_mode: manual @@ -45,7 +44,7 @@ macros: - macro: MACRO1 value: test1 - - macro: '{$MACRO2}' + - macro: "{$MACRO2}" value: test2 tags: - tag: Tag1 @@ -54,13 +53,12 @@ register: zabbix_host1 - name: expect to succeed and that things changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: try to create the same host with the same settings" - zabbix_host: - timeout: 30 # slower with py2.7 + community.zabbix.zabbix_host: host_name: ExampleHost visible_name: ExampleName description: My ExampleHost Description @@ -68,8 +66,8 @@ - Linux servers - Zabbix servers link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" + - "IMAP Service" + - "NTP Service" status: enabled state: present inventory_mode: manual @@ -104,7 +102,7 @@ macros: - macro: MACRO1 value: test1 - - macro: '{$MACRO2}' + - macro: "{$MACRO2}" value: test2 tags: - tag: Tag1 @@ -113,14 +111,13 @@ register: zabbix_host1 - name: updating with same values should be idempotent - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: try to create the same host with the same settings and force false" - zabbix_host: + community.zabbix.zabbix_host: force: false - timeout: 30 # slower with py2.7 host_name: ExampleHost visible_name: ExampleName description: My ExampleHost Description @@ -128,8 +125,8 @@ - Linux servers - Zabbix servers link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" + - "IMAP Service" + - "NTP Service" status: enabled state: present inventory_mode: manual @@ -164,14 +161,13 @@ register: zabbix_host1 - name: updating with same values and force false should be idempotent - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: try to create the same host changing one parameter in the inventory with force false" - zabbix_host: + community.zabbix.zabbix_host: force: false - timeout: 30 # slower with py2.7 host_name: ExampleHost visible_name: ExampleName description: My ExampleHost Description @@ -179,8 +175,8 @@ - Linux servers - Zabbix servers link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" + - "IMAP Service" + - "NTP Service" status: enabled state: present inventory_mode: manual @@ -215,56 +211,56 @@ register: zabbix_host1 - name: changing the value of an already defined inventory should work and mark task as changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change visible_name" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost visible_name: "ExampleName Changed" register: zabbix_host1 - name: expect to succeed and that things changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change visible_name (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost visible_name: "ExampleName Changed" register: zabbix_host1 - name: updating with same values should be idempotent - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change description" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost description: "My ExampleHost Description Changed" register: zabbix_host1 - name: expect to succeed and that things changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change description (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost description: "My ExampleHost Description Changed" register: zabbix_host1 - name: updating with same values should be idempotent - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host groups (adding one group)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost host_groups: - Linux servers @@ -273,12 +269,12 @@ register: zabbix_host1 - name: expect to succeed and that things changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host groups (remove one group)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost host_groups: - Linux servers @@ -286,12 +282,12 @@ register: zabbix_host1 - name: expect to succeed and that things changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host groups (add one group using force=no)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost host_groups: - Virtual machines @@ -299,13 +295,12 @@ register: zabbix_host1 - name: expect to succeed and that things changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - - name: "test: change host groups (check whether we are at three groups)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost host_groups: - Linux servers @@ -314,12 +309,12 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host groups (attempt to remove all host groups)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost # list with empty value, expected: host_groups: @@ -328,136 +323,133 @@ ignore_errors: true - name: expect to fail - assert: + ansible.builtin.assert: that: - "zabbix_host1 is failed" - name: "test: change host linked templates (same as before)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" + - "IMAP Service" + - "NTP Service" register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host linked templates (add one template)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" - - "{{ 'HTTP Service' if zabbix_version | float >= 5.2 else 'Template App HTTP Service' }}" + - "IMAP Service" + - "NTP Service" + - "HTTP Service" register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host linked templates (add one template, using force=no)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost link_templates: - - "{{ 'LDAP Service' if zabbix_version | float >= 5.2 else 'Template App LDAP Service' }}" + - "LDAP Service" force: false register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host linked templates (make sure we are at 4 templates)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost link_templates: - - "{{ 'IMAP Service' if zabbix_version | float >= 5.2 else 'Template App IMAP Service' }}" - - "{{ 'NTP Service' if zabbix_version | float >= 5.2 else 'Template App NTP Service' }}" - - "{{ 'HTTP Service' if zabbix_version | float >= 5.2 else 'Template App HTTP Service' }}" - - "{{ 'LDAP Service' if zabbix_version | float >= 5.2 else 'Template App LDAP Service' }}" + - "IMAP Service" + - "NTP Service" + - "HTTP Service" + - "LDAP Service" register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host linked templates (remove all templates)" - zabbix_host: - timeout: 60 # slower with py2.7 + community.zabbix.zabbix_host: host_name: ExampleHost - link_templates: - - + link_templates: [] register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host linked templates (check we have no templates left)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost - link_templates: - - + link_templates: [] register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host status" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost status: disabled register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host status (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost status: disabled register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host inventory mode" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost inventory_mode: automatic register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host inventory mode" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost inventory_mode: automatic register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change host inventory data (one field)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost inventory_zabbix: tag: test-tag-two @@ -470,12 +462,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host inventory data (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost inventory_zabbix: tag: test-tag-two @@ -488,45 +480,45 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: remove host proxy" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost - proxy: '' + proxy: "" register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: add host proxy" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost proxy: ExampleProxy register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: add host proxy (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost proxy: ExampleProxy register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change tls certificate settings" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost tls_connect: 4 tls_accept: 4 @@ -535,12 +527,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change tls certificate settings (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost tls_connect: 4 tls_accept: 4 @@ -549,12 +541,12 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change tls psk (write-only) settings" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost tls_connect: 2 tls_accept: 2 @@ -563,11 +555,11 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: zabbix_host1 is changed - name: "test: change tls psk (write-only) settings (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost tls_connect: 2 tls_accept: 2 @@ -576,17 +568,11 @@ register: zabbix_host1 - name: expect to succeed and that things have changed (tls_psk makes module non-idempotent) - assert: + ansible.builtin.assert: that: zabbix_host1 is changed - when: zabbix_version is version('5.4', '>=') - -- name: expect to succeed and that things have not changed - assert: - that: zabbix_host1 is not changed - when: zabbix_version is version('5.4', '<') - name: "test: change interface settings (remove one)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: 1 @@ -598,12 +584,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change interface settings (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: 1 @@ -615,12 +601,12 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: change interface settings (add one interface using force=no)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: 4 @@ -633,12 +619,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change interface settings (verify that we are at two interfaces)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: 1 @@ -656,12 +642,12 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" - name: "test: configure interface to useip=1 but provide no ip" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: 1 @@ -677,12 +663,12 @@ ignore_errors: true - name: expect to fail - assert: + ansible.builtin.assert: that: - "zabbix_host1 is failed" - name: "test: configure interface to useip=0 but provide no dns" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: 1 @@ -699,217 +685,214 @@ ignore_errors: true - name: expect to fail - assert: + ansible.builtin.assert: + that: + - "zabbix_host1 is failed" + +- name: "test: configure SNMPv2 interface without details (fail)" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + register: zabbix_host1 + ignore_errors: true + +- name: expect to fail + ansible.builtin.assert: that: - "zabbix_host1 is failed" -- when: zabbix_version is version("5.0", ">=") - block: - - name: "test: configure SNMPv2 interface without details (fail)" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - register: zabbix_host1 - ignore_errors: true - - - name: expect to fail - assert: - that: - - "zabbix_host1 is failed" - - - name: "test: configure details for SNMPv2 interface" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 2 - community: Community String - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: configure details for SNMPv2 interface (again)" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 2 - community: Community String - register: zabbix_host1 - - - name: expect to succeed and that things have not changed - assert: - that: - - "zabbix_host1 is not changed" - - - name: "test: configure SNMPv2 interface with the same options and force=False " - zabbix_host: - host_name: ExampleHost - force: False - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 2 - community: Community String - register: zabbix_host1 - - - name: expect to succeed and that things have not changed - assert: - that: - - "zabbix_host1 is not changed" - - - name: "test: update details for SNMPv2 interface with bulk sub option" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 2 - community: Community String - bulk: 0 - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: configure details for SNMPv3 interface" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 3 - contextname: snmp_context - securityname: SNMP3 sec name - securitylevel: 0 - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: configure details for SNMPv3 interface (again)" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 3 - contextname: snmp_context - securityname: SNMP3 sec name - securitylevel: 0 - register: zabbix_host1 - - - name: expect to succeed and that things have not changed - assert: - that: - - "zabbix_host1 is not changed" - - - name: "test: update details for SNMPv3 interface" - zabbix_host: - host_name: ExampleHost - interfaces: - - type: 1 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "10050" - - type: 2 - main: 1 - useip: 1 - ip: 10.1.1.1 - port: "161" - details: - version: 3 - contextname: snmp_context - securityname: SNMP3 sec name - securitylevel: 2 - authprotocol: "{{ 2 if zabbix_version | float >= 5.4 else 0 }}" - authpassphrase: secret_auth_passphrase - privprotocol: "{{ 2 if zabbix_version | float >= 5.4 else 0 }}" - privpassphrase: secret_priv_passphrase - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - -# https://github.com/ansible-collections/community.zabbix/pull/391 +- name: "test: configure details for SNMPv2 interface" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 2 + community: Community String + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: configure details for SNMPv2 interface (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 2 + community: Community String + register: zabbix_host1 + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: + - "zabbix_host1 is not changed" + +- name: "test: configure SNMPv2 interface with the same options and force=False " + community.zabbix.zabbix_host: + host_name: ExampleHost + force: False + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 2 + community: Community String + register: zabbix_host1 + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: + - "zabbix_host1 is not changed" + +- name: "test: update details for SNMPv2 interface with bulk sub option" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 2 + community: Community String + bulk: 0 + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: configure details for SNMPv3 interface" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 3 + contextname: snmp_context + securityname: SNMP3 sec name + securitylevel: 0 + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: configure details for SNMPv3 interface (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 3 + contextname: snmp_context + securityname: SNMP3 sec name + securitylevel: 0 + register: zabbix_host1 + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: + - "zabbix_host1 is not changed" + +- name: "test: update details for SNMPv3 interface" + community.zabbix.zabbix_host: + host_name: ExampleHost + interfaces: + - type: 1 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "10050" + - type: 2 + main: 1 + useip: 1 + ip: 10.1.1.1 + port: "161" + details: + version: 3 + contextname: snmp_context + securityname: SNMP3 sec name + securitylevel: 2 + authprotocol: "{{ 2 if zabbix_version | float >= 5.4 else 0 }}" + authpassphrase: secret_auth_passphrase + privprotocol: "{{ 2 if zabbix_version | float >= 5.4 else 0 }}" + privpassphrase: secret_priv_passphrase + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + - name: "reset interfaces to two of the same type" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: "1" @@ -922,12 +905,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "reset interfaces to two of the same type (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost interfaces: - type: "1" @@ -940,12 +923,12 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: add IPMI settings" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost ipmi_authtype: 2 ipmi_privilege: 4 @@ -954,12 +937,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: add IPMI settings again" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost ipmi_authtype: 2 ipmi_privilege: 4 @@ -968,22 +951,22 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: verify that an empty change is idempotent" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: IPMI set default values" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost ipmi_authtype: -1 ipmi_privilege: 2 @@ -992,12 +975,12 @@ register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: IPMI set default values (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost ipmi_authtype: -1 ipmi_privilege: 2 @@ -1006,380 +989,366 @@ register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: change host inventory mode to disabled" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost inventory_mode: disabled register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: change host inventory mode to manual" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost inventory_mode: manual register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: add new set of user macros to the host" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost macros: - - macro: '{$NEWMACRO1}' + - macro: "{$NEWMACRO1}" value: test123 - macro: NEWMACRO2 value: abc register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: add new set of user macros to the host (again - lowercase)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost macros: - - macro: '{$newmacro1}' + - macro: "{$newmacro1}" value: test123 - macro: newmacro2 value: abc register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: update one of the user macros present on the host" - zabbix_host: + community.zabbix.zabbix_host: + host_name: ExampleHost + macros: + - macro: "{$NEWMACRO1}" + value: test1234 + - macro: NEWMACRO2 + value: abc + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: update one of the user macros with description" + community.zabbix.zabbix_host: host_name: ExampleHost macros: - - macro: '{$NEWMACRO1}' + - macro: "{$NEWMACRO1}" value: test1234 + description: Example Description - macro: NEWMACRO2 value: abc register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" -# The description of tag is available since Zabbix version 4.4 -- when: zabbix_version is version("4.4", ">=") - block: - - name: "test: update one of the user macros with description" - zabbix_host: - host_name: ExampleHost - macros: - - macro: '{$NEWMACRO1}' - value: test1234 - description: Example Description - - macro: NEWMACRO2 - value: abc - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: update one of the user macros with description (again)" - zabbix_host: - host_name: ExampleHost - macros: - - macro: '{$NEWMACRO1}' - value: test1234 - description: Example Description - - macro: NEWMACRO2 - value: abc - register: zabbix_host1 - - - name: expect to succeed and that things have not changed - assert: - that: - - "zabbix_host1 is not changed" - - - name: "test: update one of the user macros by removing description" - zabbix_host: - host_name: ExampleHost - macros: - - macro: '{$NEWMACRO1}' - value: test1234 - - macro: NEWMACRO2 - value: abc - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" +- name: "test: update one of the user macros with description (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + macros: + - macro: "{$NEWMACRO1}" + value: test1234 + description: Example Description + - macro: NEWMACRO2 + value: abc + register: zabbix_host1 + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: + - "zabbix_host1 is not changed" + +- name: "test: update one of the user macros by removing description" + community.zabbix.zabbix_host: + host_name: ExampleHost + macros: + - macro: "{$NEWMACRO1}" + value: test1234 + - macro: NEWMACRO2 + value: abc + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" - name: "test: add user macro while keeping previous ones with force=no" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost force: false macros: - - macro: '{$NEWMACRO3}' + - macro: "{$NEWMACRO3}" value: testing register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: add user macro while keeping previous ones with force=no (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost force: false macros: - - macro: '{$NEWMACRO3}' + - macro: "{$NEWMACRO3}" value: testing register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: add the same user macros (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost macros: - - macro: '{$NEWMACRO1}' + - macro: "{$NEWMACRO1}" value: test1234 - macro: NEWMACRO2 value: abc - - macro: '{$NEWMACRO3}' + - macro: "{$NEWMACRO3}" value: testing register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" -# type for macros added in 5.0 -- when: zabbix_version is version("5.0", ">=") - block: - - name: "test: add new user macro with type secret" - zabbix_host: - host_name: ExampleHost - macros: - - macro: '{$NEWMACROSECRET}' - value: secretvalue - type: secret - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: add new user macro with type secret (again)" - zabbix_host: - host_name: ExampleHost - macros: - - macro: '{$NEWMACROSECRET}' - value: secretvalue - type: secret - register: zabbix_host1 - - - name: expect to succeed and that things have changed as it has secret value - assert: - that: - - "zabbix_host1 is changed" +- name: "test: add new user macro with type secret" + community.zabbix.zabbix_host: + host_name: ExampleHost + macros: + - macro: "{$NEWMACROSECRET}" + value: secretvalue + type: secret + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: add new user macro with type secret (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + macros: + - macro: "{$NEWMACROSECRET}" + value: secretvalue + type: secret + register: zabbix_host1 + +- name: expect to succeed and that things have changed as it has secret value + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" - name: "test: wipe out all of the user macros" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost macros: [] register: zabbix_host1 - name: expect to succeed and that things have changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: wipe out all of the user macros (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost macros: [] register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" -# The tag function is available since Zabbix version 4.4 -- when: zabbix_version is version("4.4", ">=") - block: - - name: "test: add new set of tags to the host" - zabbix_host: - host_name: ExampleHost - tags: - - tag: NEWTAG1 - - tag: NewTag2 - value: abc - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: add new set of tags to the host (again)" - zabbix_host: - host_name: ExampleHost - tags: - - tag: NEWTAG1 - - tag: NewTag2 - value: abc - register: zabbix_host1 - - - name: expect to succeed and that things have not changed - assert: - that: - - "zabbix_host1 is not changed" - - - name: "test: update one of the tags present on the host" - zabbix_host: - host_name: ExampleHost - tags: - - tag: NEWTAG1 - - tag: NewTag2 - value: abcd - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: add tag while keeping previous ones with force=no" - zabbix_host: - host_name: ExampleHost - force: false - tags: - - tag: newtag3 - value: testing - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" - - - name: "test: add the same tags (again)" - zabbix_host: - host_name: ExampleHost - tags: - - tag: NEWTAG1 - - tag: NewTag2 - value: abcd - - tag: newtag3 - value: testing - register: zabbix_host1 - - - name: expect to succeed and that things have not changed - assert: - that: - - "zabbix_host1 is not changed" - - - name: "test: wipe out all of the tags" - zabbix_host: - host_name: ExampleHost - tags: [] - register: zabbix_host1 - - - name: expect to succeed and that things have changed - assert: - that: - - "zabbix_host1 is changed" +- name: "test: add new set of tags to the host" + community.zabbix.zabbix_host: + host_name: ExampleHost + tags: + - tag: NEWTAG1 + - tag: NewTag2 + value: abc + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: add new set of tags to the host (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + tags: + - tag: NEWTAG1 + - tag: NewTag2 + value: abc + register: zabbix_host1 + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: + - "zabbix_host1 is not changed" + +- name: "test: update one of the tags present on the host" + community.zabbix.zabbix_host: + host_name: ExampleHost + tags: + - tag: NEWTAG1 + - tag: NewTag2 + value: abcd + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: add tag while keeping previous ones with force=no" + community.zabbix.zabbix_host: + host_name: ExampleHost + force: false + tags: + - tag: newtag3 + value: testing + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" + +- name: "test: add the same tags (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + tags: + - tag: NEWTAG1 + - tag: NewTag2 + value: abcd + - tag: newtag3 + value: testing + register: zabbix_host1 + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: + - "zabbix_host1 is not changed" + +- name: "test: wipe out all of the tags" + community.zabbix.zabbix_host: + host_name: ExampleHost + tags: [] + register: zabbix_host1 + +- name: expect to succeed and that things have changed + ansible.builtin.assert: + that: + - "zabbix_host1 is changed" - name: "test: wipe out all of the tags (again)" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost tags: [] register: zabbix_host1 - name: expect to succeed and that things have not changed - assert: + ansible.builtin.assert: that: - "zabbix_host1 is not changed" - name: "test: attempt to delete host created earlier" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost state: absent register: zabbix_host1 - name: deleting a host is a change, right? - assert: + ansible.builtin.assert: that: - "zabbix_host1 is changed" - name: "test: attempt deleting a non-existant host" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHost state: absent register: zabbix_host1 - name: deleting a non-existant host is not a change, right? - assert: + ansible.builtin.assert: that: - "not zabbix_host1 is changed" -- when: zabbix_version is version('5.2', '>=') - block: - - name: "test: create host without host interfaces" - zabbix_host: - host_name: ExampleHost - visible_name: ExampleName - description: My ExampleHost Description - host_groups: - - Linux servers - status: disabled - state: present - register: zbx_host_create_interfaceless - - - name: verify host was created without interfaces - assert: - that: zbx_host_create_interfaceless is changed - - - name: "test: create host without host interfaces (again)" - zabbix_host: - server_url: "{{ zabbix_api_server_url }}" - login_user: "{{ zabbix_api_login_user }}" - login_password: "{{ zabbix_api_login_pass }}" - host_name: ExampleHost - visible_name: ExampleName - description: My ExampleHost Description - host_groups: - - Linux servers - status: disabled - state: present - register: zbx_host_create_interfaceless - - - name: expect to succeed and that things have not changed - assert: - that: zbx_host_create_interfaceless is not changed - - - name: "cleanup" - zabbix_host: - host_name: ExampleHost - state: absent +- name: "test: create host without host interfaces" + community.zabbix.zabbix_host: + host_name: ExampleHost + visible_name: ExampleName + description: My ExampleHost Description + host_groups: + - Linux servers + status: disabled + state: present + register: zbx_host_create_interfaceless + +- name: verify host was created without interfaces + ansible.builtin.assert: + that: zbx_host_create_interfaceless is changed + +- name: "test: create host without host interfaces (again)" + community.zabbix.zabbix_host: + host_name: ExampleHost + visible_name: ExampleName + description: My ExampleHost Description + host_groups: + - Linux servers + status: disabled + state: present + register: zbx_host_create_interfaceless + +- name: expect to succeed and that things have not changed + ansible.builtin.assert: + that: zbx_host_create_interfaceless is not changed + +- name: "cleanup" + community.zabbix.zabbix_host: + host_name: ExampleHost + state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host_info/tasks/main.yml index dfcaf097d..72c2f6364 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host_info/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_host_info/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: "test - Prepare host for zabbix_host_info module" - zabbix_host: + community.zabbix.zabbix_host: host_name: ExampleHostForHostInfoModule visible_name: ExampleHostForHostInfoModuleName description: Test Host @@ -8,7 +8,7 @@ - Linux servers - Hypervisors link_templates: - - "{{ 'Zabbix server health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Server' }}" + - Zabbix server health status: enabled inventory_mode: manual inventory_zabbix: @@ -24,7 +24,7 @@ state: present register: prepare_host_result -- assert: +- ansible.builtin.assert: that: - prepare_host_result.changed is sameas true @@ -35,7 +35,7 @@ environment: ZABBIX_VALIDATE_CERTS: false -- assert: +- ansible.builtin.assert: that: - env_vars_usage.hosts[0].name == "ExampleHostForHostInfoModuleName" @@ -46,53 +46,11 @@ block: - name: "test - Gather all facts of zabbix host" - zabbix_host_info: + community.zabbix.zabbix_host_info: register: gather_all_facts_result - - when: zabbix_version is version('4.0', '<=') - assert: - that: - - gather_all_facts_result.hosts | length == 1 - - gather_all_facts_result.hosts.0.host == "ExampleHostForHostInfoModule" - - gather_all_facts_result.hosts.0.name == "ExampleHostForHostInfoModuleName" - - gather_all_facts_result.hosts.0.description == "Test Host" - - gather_all_facts_result.hosts.0.groups.0.name == "Linux servers" - - gather_all_facts_result.hosts.0.groups.1.name == "Hypervisors" - - gather_all_facts_result.hosts.0.parentTemplates.0.name == "Template App Zabbix Server" - - gather_all_facts_result.hosts.0.status == "0" - - gather_all_facts_result.hosts.0.inventory.inventory_mode == "0" - - gather_all_facts_result.hosts.0.inventory.tag == "tag1" - - gather_all_facts_result.hosts.0.inventory.os == "Linux" - - gather_all_facts_result.hosts.0.hostinterfaces.0.dns == "" - - gather_all_facts_result.hosts.0.hostinterfaces.0.ip == "192.168.0.1" - - gather_all_facts_result.hosts.0.hostinterfaces.0.main == "1" - - gather_all_facts_result.hosts.0.hostinterfaces.0.port == "10050" - - gather_all_facts_result.hosts.0.hostinterfaces.0.type == "1" - - gather_all_facts_result.hosts.0.hostinterfaces.0.useip == "1" - - - when: zabbix_version is version('4.4', '>=') and zabbix_version is version('5.0', '<=') - assert: - that: - - gather_all_facts_result.hosts | length == 1 - - gather_all_facts_result.hosts.0.host == "ExampleHostForHostInfoModule" - - gather_all_facts_result.hosts.0.name == "ExampleHostForHostInfoModuleName" - - gather_all_facts_result.hosts.0.description == "Test Host" - - gather_all_facts_result.hosts.0.groups.0.name == "Linux servers" - - gather_all_facts_result.hosts.0.groups.1.name == "Hypervisors" - - gather_all_facts_result.hosts.0.parentTemplates.0.name == "Template App Zabbix Server" - - gather_all_facts_result.hosts.0.status == "0" - - gather_all_facts_result.hosts.0.inventory_mode == "0" - - gather_all_facts_result.hosts.0.inventory.tag == "tag1" - - gather_all_facts_result.hosts.0.inventory.os == "Linux" - - gather_all_facts_result.hosts.0.hostinterfaces.0.dns == "" - - gather_all_facts_result.hosts.0.hostinterfaces.0.ip == "192.168.0.1" - - gather_all_facts_result.hosts.0.hostinterfaces.0.main == "1" - - gather_all_facts_result.hosts.0.hostinterfaces.0.port == "10050" - - gather_all_facts_result.hosts.0.hostinterfaces.0.type == "1" - - gather_all_facts_result.hosts.0.hostinterfaces.0.useip == "1" - - when: zabbix_version is version('5.4', '>=') and zabbix_version is version('6.2', '<') - assert: + ansible.builtin.assert: that: - gather_all_facts_result.hosts | length == 1 - gather_all_facts_result.hosts.0.host == "ExampleHostForHostInfoModule" @@ -113,7 +71,7 @@ - gather_all_facts_result.hosts.0.hostinterfaces.0.useip == "1" - when: zabbix_version is version('6.2', '>=') - assert: + ansible.builtin.assert: that: - gather_all_facts_result.hosts | length == 1 - gather_all_facts_result.hosts.0.host == "ExampleHostForHostInfoModule" @@ -134,52 +92,57 @@ - gather_all_facts_result.hosts.0.hostinterfaces.0.useip == "1" - name: "test - Gather facts of zabbix host with host_inventory" - zabbix_host_info: + community.zabbix.zabbix_host_info: host_inventory: - tag - os register: gather_facts_with_host_inventory_result - - when: zabbix_version is version('3.4', '<=') - assert: - that: - - gather_facts_with_host_inventory_result.hosts.0.inventory | length == 3 - - gather_facts_with_host_inventory_result.hosts.0.inventory.tag == "tag1" - - gather_facts_with_host_inventory_result.hosts.0.inventory.os == "Linux" - - - when: zabbix_version is version('4.0', '>=') - assert: + - ansible.builtin.assert: that: - gather_facts_with_host_inventory_result.hosts.0.inventory | length == 2 - gather_facts_with_host_inventory_result.hosts.0.inventory.tag == "tag1" - gather_facts_with_host_inventory_result.hosts.0.inventory.os == "Linux" - name: "test - Partial match of zabbix host name" - zabbix_host_info: + community.zabbix.zabbix_host_info: host_name: HostForHostInfo exact_match: false register: partial_match_result - - assert: + - ansible.builtin.assert: that: - partial_match_result.hosts | length == 1 - name: "test - Exact match of zabbix host name" - zabbix_host_info: + community.zabbix.zabbix_host_info: exact_match: true register: exact_match_result - - assert: + - ansible.builtin.assert: that: - exact_match_result.hosts | length == 1 - name: "test - Exact match of zabbix host name(expectations - host not found)" - zabbix_host_info: + community.zabbix.zabbix_host_info: host_name: HostForHostInfo exact_match: true register: exact_match_host_not_found_result ignore_errors: true - - assert: + - ansible.builtin.assert: that: - exact_match_host_not_found_result.failed is sameas true + +- name: Get all hosts + community.zabbix.zabbix_host_info: + register: get_all_hosts_result + +- ansible.builtin.assert: + that: + - get_all_hosts_result.hosts | length == 2 + +- name: Clean up test host + community.zabbix.zabbix_host: + host_name: ExampleHostForHostInfoModule + state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_hostmacro/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_hostmacro/tasks/main.yml index 1a9d81eff..adc4d0402 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_hostmacro/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_hostmacro/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: create helper zabbix host - zabbix_host: + community.zabbix.zabbix_host: host_name: zbx_hmacro_host01 host_groups: - Linux servers @@ -10,97 +10,105 @@ dns: zbx_hmacro_host01 - name: test - attempt to create new host macro - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test01 macro_value: 123 + macro_description: Global Macro description register: zbxhmacro_new - name: assert that macro was created - assert: + ansible.builtin.assert: that: zbxhmacro_new is changed - name: test - attempt to create same host macro - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test01 macro_value: 123 + macro_description: Global Macro description register: zbxhmacro_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxhmacro_existing is changed - name: test - attempt to create same host macro in zabbix native format - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: "{$ZBXHMACRO_TEST01}" macro_value: 123 + macro_description: Global Macro description register: zbxhmacro_existing_native - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxhmacro_existing_native is changed - name: test - attempt to create new host macro in zabbix native format - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: "{$ZBXHMACRO_TEST02}" macro_value: abcd + macro_description: Global Macro description register: zbxhmacro_new_native - name: assert that nothing macro was created - assert: + ansible.builtin.assert: that: zbxhmacro_new_native is changed - name: test - attempt to update host macro with string value while force=no - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test01 macro_value: abc + macro_description: Global Macro description force: false register: zbxhmacro_update_noforce - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxhmacro_update_noforce is changed - name: test - attempt to update host macro with string value - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test01 macro_value: abc + macro_description: Global Macro description register: zbxhmacro_update ignore_errors: true - name: assert that host macro was updated - assert: + ansible.builtin.assert: that: zbxhmacro_update is changed - name: test - attempt to create host macro with context - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: low_space_limit:/home macro_value: 10 + macro_description: Global Macro description register: zbxhmacro_context_new - name: assert that macro was created - assert: + ansible.builtin.assert: that: zbxhmacro_context_new is changed - name: test - attempt to create same host macro with context and verify that it was converted to uppercase - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: LOW_SPACE_LIMIT:/home macro_value: 10 + macro_description: Global Macro description register: zbxhmacro_context_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxhmacro_context_existing is changed - name: test - attempt to delete all host macros - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: "{{ item }}" state: absent @@ -111,53 +119,51 @@ register: zbxhmacro_delete_existing - name: assert that all macros have been deleted - assert: + ansible.builtin.assert: that: item.changed is sameas True loop: "{{ zbxhmacro_delete_existing.results }}" - name: test - attempt to delete non-existing host macro - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test01 state: absent register: zbxhmacro_delete_missing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxhmacro_delete_missing is changed -- name: test - do not run host macro secret tests for Zabbix < 5.0 - meta: end_play - when: zabbix_version is version('5.0', '<') - - name: test - attempt to create host macro with type secret - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test03 macro_value: abcd macro_type: secret + macro_description: Global Macro description register: zbxhmacro_update ignore_errors: true - name: assert that host macro was updated - assert: + ansible.builtin.assert: that: zbxhmacro_update is changed - name: test - attempt to update host macro with type secret with same value - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: zbxhmacro_test03 macro_value: abcd macro_type: secret + macro_description: Global Macro description register: zbxhmacro_update ignore_errors: true - name: assert that host macro was updated - assert: + ansible.builtin.assert: that: zbxhmacro_update is changed - name: test - attempt to delete host macros type secret - zabbix_hostmacro: + community.zabbix.zabbix_hostmacro: host_name: zbx_hmacro_host01 macro_name: "{{ item }}" state: absent @@ -166,6 +172,6 @@ register: zbxhmacro_delete_existing - name: assert that all macros have been deleted - assert: + ansible.builtin.assert: that: item.changed is sameas True loop: "{{ zbxhmacro_delete_existing.results }}" diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_housekeeping/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_housekeeping/tasks/main.yml index 6189c1d77..242b11927 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_housekeeping/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_housekeeping/tasks/main.yml @@ -1,96 +1,77 @@ --- -- name: test - do not run tests with < Zabbix 4.0 - meta: end_play - when: zabbix_version is version('4.0', '<') +- name: test update housekeeping parameters. + community.zabbix.zabbix_housekeeping: + hk_events_mode: yes + hk_events_trigger: 365d + hk_events_service: 1w + hk_events_internal: 86400s + hk_events_discovery: 48h + hk_events_autoreg: 1440m + hk_services_mode: yes + hk_services: 365d + hk_audit_mode: yes + hk_audit: 365d + hk_sessions_mode: yes + hk_sessions: 365d + hk_history_mode: yes + hk_history_global: yes + hk_history: 365d + hk_trends_mode: yes + hk_trends_global: yes + hk_trends: 365d + compression_status: off + compress_older: 7d + register: zbxhk_update_result -- when: zabbix_version is version('5.2', '<') - name: Unsupport Zabbix version (<5.2) - block: - - name: test fail to update housekeeping - community.zabbix.zabbix_housekeeping: - hk_events_mode: true - register: zbxhk_update_result - ignore_errors: true +- ansible.builtin.assert: + that: zbxhk_update_result.changed is sameas True - - assert: - that: zbxhk_update_result.failed is sameas True +- name: test update housekeeping parameters (again). + community.zabbix.zabbix_housekeeping: + hk_events_mode: yes + hk_events_trigger: 365d + hk_events_service: 1w + hk_events_internal: 86400s + hk_events_discovery: 48h + hk_events_autoreg: 1440m + hk_services_mode: yes + hk_services: 365d + hk_audit_mode: yes + hk_audit: 365d + hk_sessions_mode: yes + hk_sessions: 365d + hk_history_mode: yes + hk_history_global: yes + hk_history: 365d + hk_trends_mode: yes + hk_trends_global: yes + hk_trends: 365d + compression_status: off + compress_older: 7d + register: zbxhk_update_result -- when: zabbix_version is version('5.2', '>=') - name: Support Zabbix version (>=5.2) - block: - - name: test update housekeeping parameters. - community.zabbix.zabbix_housekeeping: - hk_events_mode: yes - hk_events_trigger: 365d - hk_events_service: 1w - hk_events_internal: 86400s - hk_events_discovery: 48h - hk_events_autoreg: 1440m - hk_services_mode: yes - hk_services: 365d - hk_audit_mode: yes - hk_audit: 365d - hk_sessions_mode: yes - hk_sessions: 365d - hk_history_mode: yes - hk_history_global: yes - hk_history: 365d - hk_trends_mode: yes - hk_trends_global: yes - hk_trends: 365d - compression_status: off - compress_older: 7d - register: zbxhk_update_result +- ansible.builtin.assert: + that: zbxhk_update_result.changed is sameas False - - assert: - that: zbxhk_update_result.changed is sameas True - - - name: test update housekeeping parameters (again). - community.zabbix.zabbix_housekeeping: - hk_events_mode: yes - hk_events_trigger: 365d - hk_events_service: 1w - hk_events_internal: 86400s - hk_events_discovery: 48h - hk_events_autoreg: 1440m - hk_services_mode: yes - hk_services: 365d - hk_audit_mode: yes - hk_audit: 365d - hk_sessions_mode: yes - hk_sessions: 365d - hk_history_mode: yes - hk_history_global: yes - hk_history: 365d - hk_trends_mode: yes - hk_trends_global: yes - hk_trends: 365d - compression_status: off - compress_older: 7d - register: zbxhk_update_result - - - assert: - that: zbxhk_update_result.changed is sameas False - - - name: initialize housekeeping setting. - community.zabbix.zabbix_housekeeping: - hk_events_mode: yes - hk_events_trigger: 365d - hk_events_service: 1d - hk_events_internal: 1d - hk_events_discovery: 1d - hk_events_autoreg: 1d - hk_services_mode: yes - hk_services: 365d - hk_audit_mode: yes - hk_audit: 365d - hk_sessions_mode: yes - hk_sessions: 365d - hk_history_mode: yes - hk_history_global: no - hk_history: 365d - hk_trends_mode: yes - hk_trends_global: no - hk_trends: 365d - compression_status: off - compress_older: 7d +- name: initialize housekeeping setting. + community.zabbix.zabbix_housekeeping: + hk_events_mode: yes + hk_events_trigger: 365d + hk_events_service: 1d + hk_events_internal: 1d + hk_events_discovery: 1d + hk_events_autoreg: 1d + hk_services_mode: yes + hk_services: 365d + hk_audit_mode: yes + hk_audit: 365d + hk_sessions_mode: yes + hk_sessions: 365d + hk_history_mode: yes + hk_history_global: no + hk_history: 365d + hk_trends_mode: yes + hk_trends_global: no + hk_trends: 365d + compression_status: off + compress_older: 7d diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_maintenance/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_maintenance/tasks/main.yml index 0daca8d13..1b9c6f6bd 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_maintenance/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_maintenance/tasks/main.yml @@ -1,7 +1,7 @@ --- # New host create test from here - name: "test - Create a new host" - zabbix_host: + community.zabbix.zabbix_host: host_name: example host_groups: - Linux servers @@ -14,24 +14,24 @@ port: 10050 register: create_host_result -- assert: +- ansible.builtin.assert: that: - create_host_result.changed is sameas true - name: "test - Create maintenance with a host_name param" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example state: present register: create_maintenance_host_name_result -- assert: +- ansible.builtin.assert: that: - create_maintenance_host_name_result.changed is sameas true # This check doesn't modify maintenace object and thus will be changed=false unless there are hosts without visible name defined - name: "test - Create maintenance with a host_name param and disabled visible_name" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example visible_name: false @@ -40,12 +40,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - create_maintenance_host_name_result.changed is sameas false - name: "test - Create maintenance with a host_name param(again - expectations: false change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example state: present @@ -53,12 +53,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - create_maintenance_host_name_again_result.changed is sameas false - name: "test - Update maintenance with a desc param" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example desc: "test description" @@ -67,12 +67,12 @@ - debug: msg="{{ update_maintenance_desc_result }}" -- assert: +- ansible.builtin.assert: that: - update_maintenance_desc_result.changed is sameas true - name: "test - Update maintenance with a desc param(again - expectations: no change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example desc: "test description" @@ -81,12 +81,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - update_maintenance_desc_again_result.changed is sameas false - name: "test - Update maintenance with a collect_data" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example desc: "test description" @@ -94,12 +94,12 @@ state: present register: update_maintenance_collect_data_result -- assert: +- ansible.builtin.assert: that: - update_maintenance_collect_data_result.changed is sameas true - name: "test - Update maintenance with a collect_data(again - expectations: no change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example desc: "test description" @@ -109,12 +109,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - update_maintenance_collect_data_again_result.changed is sameas false - name: "test - Update maintenance with a minutes param" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example desc: "test description" @@ -123,12 +123,12 @@ state: present register: update_maintenance_minutes_result -- assert: +- ansible.builtin.assert: that: - update_maintenance_minutes_result.changed is sameas true - name: "test - Update maintenance with a minutes param(again - expectations: no change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example desc: "test description" @@ -139,12 +139,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - update_maintenance_minutes_again_result.changed is sameas false - name: "test - Update maintenance with a host_groups param" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example host_groups: @@ -156,12 +156,12 @@ state: present register: update_maintenance_host_groups_result -- assert: +- ansible.builtin.assert: that: - update_maintenance_host_groups_result.changed is sameas true - name: "test - Update maintenance with a host_groups param(again - expectations: no change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example host_groups: @@ -175,12 +175,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - update_maintenance_host_groups_again_result.changed is sameas false - name: "test - Update maintenance with change host_name to host_names param" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_names: - example @@ -194,12 +194,12 @@ state: present register: update_maintenance_host_names_result -- assert: +- ansible.builtin.assert: that: - update_maintenance_host_names_result.changed is sameas true - name: "test - Update maintenance with change host_name to host_names param(again - expectations: no change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_names: - example @@ -215,12 +215,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -# - assert: +# - ansible.builtin.assert: # that: # - update_maintenance_host_names_again_result.changed is sameas false - name: "test - Update maintenance with tags" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_names: - example @@ -229,7 +229,7 @@ - Linux servers - Hypervisors desc: "test description" - collect_data: yes # required for tags + collect_data: yes # required for tags minutes: 90 state: present tags: @@ -241,12 +241,12 @@ operator: 0 register: update_maintenance_host_tags -- assert: +- ansible.builtin.assert: that: - update_maintenance_host_tags.changed is sameas true - name: "test - Update maintenance with tags (again)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_names: - example @@ -269,12 +269,12 @@ # BUGGED: sometimes when test "lags" and some time passes since previous tasks, # maintenance_start will not match and be updated, thus resulting in changed -#- assert: +#- ansible.builtin.assert: # that: # - update_maintenance_host_tags.changed is sameas false - name: "test - Delete maintenance" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example state: absent @@ -282,23 +282,23 @@ tags: - cleanup -- assert: +- ansible.builtin.assert: that: - delete_maintenance_result.changed is sameas true - name: "test - Delete maintenance(again - expectations: no change will occur)" - zabbix_maintenance: + community.zabbix.zabbix_maintenance: name: maintenance host_name: example state: absent register: delete_maintenance_again_result -- assert: +- ansible.builtin.assert: that: - delete_maintenance_again_result.changed is sameas false - name: "test - Delete testing host" - zabbix_host: + community.zabbix.zabbix_host: host_name: example state: absent tags: diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_mediatype/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_mediatype/tasks/main.yml index 4daffebdd..a49166d37 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_mediatype/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_mediatype/tasks/main.yml @@ -8,156 +8,152 @@ smtp_email: zabbix@example.com block: - - name: test - create new email mediatype without authentication - zabbix_mediatype: - register: zbxmediatype_new - - - assert: - that: zbxmediatype_new.changed is sameas True - - - name: test - create new email mediatype without authentication (again) - zabbix_mediatype: - register: zbxmediatype_new - - - assert: - that: zbxmediatype_new.changed is sameas False - - - name: test - update email mediatype smtp information - zabbix_mediatype: - smtp_helo: example.com - smtp_server: mail.example.com - smtp_server_port: 465 - register: zbxmediatype_smtp - - - assert: - that: zbxmediatype_smtp.changed is sameas True - - - name: test - update email mediatype smtp information (again) - zabbix_mediatype: - smtp_helo: example.com - smtp_server: mail.example.com - smtp_server_port: 465 - register: zbxmediatype_smtp - - - assert: - that: zbxmediatype_smtp.changed is sameas False - - - name: test - reset email mediatype smtp information to default - zabbix_mediatype: - register: zbxmediatype_reset - - - assert: - that: zbxmediatype_reset.changed is sameas True - - - name: test - update email mediatype with authentication without credentials (fail) - zabbix_mediatype: - smtp_authentication: true - smtp_security: STARTTLS - register: zbxmediatype_auth_fail - ignore_errors: true - - - assert: - that: zbxmediatype_auth_fail.failed is sameas True - - - name: test - update email mediatype with authentication - zabbix_mediatype: - smtp_authentication: true - smtp_security: STARTTLS - username: zabbix - password: Ex4mP!3 - register: zbxmediatype_auth - - - assert: - that: zbxmediatype_auth.changed is sameas True - - - name: test - update email mediatype with authentication (again) - zabbix_mediatype: - smtp_authentication: true - smtp_security: STARTTLS - username: zabbix - password: Ex4mP!3 - register: zbxmediatype_auth - - - assert: - that: zbxmediatype_auth.changed is sameas False - - - name: test - update email mediatype with SSL/TLS and host/peer verification - zabbix_mediatype: - smtp_authentication: true - smtp_security: SSL/TLS - smtp_verify_host: true - smtp_verify_peer: true - username: zabbix - password: Ex4mP!3 - register: zbxmediatype_verif - - - assert: - that: zbxmediatype_verif.changed is sameas True - - - name: test - update email mediatype with SSL/TLS and host/peer verification (again) - zabbix_mediatype: - smtp_authentication: true - smtp_security: SSL/TLS - smtp_verify_host: true - smtp_verify_peer: true - username: zabbix - password: Ex4mP!3 - register: zbxmediatype_verif - - - assert: - that: zbxmediatype_verif.changed is sameas False - - - when: zabbix_version is version('3.4', '>=') - block: + - name: test - create new email mediatype without authentication + community.zabbix.zabbix_mediatype: + register: zbxmediatype_new + + - ansible.builtin.assert: + that: zbxmediatype_new.changed is sameas True + + - name: test - create new email mediatype without authentication (again) + community.zabbix.zabbix_mediatype: + register: zbxmediatype_new + + - ansible.builtin.assert: + that: zbxmediatype_new.changed is sameas False + + - name: test - update email mediatype smtp information + community.zabbix.zabbix_mediatype: + smtp_helo: example.com + smtp_server: mail.example.com + smtp_server_port: 465 + register: zbxmediatype_smtp + + - ansible.builtin.assert: + that: zbxmediatype_smtp.changed is sameas True + + - name: test - update email mediatype smtp information (again) + community.zabbix.zabbix_mediatype: + smtp_helo: example.com + smtp_server: mail.example.com + smtp_server_port: 465 + register: zbxmediatype_smtp + + - ansible.builtin.assert: + that: zbxmediatype_smtp.changed is sameas False + + - name: test - reset email mediatype smtp information to default + community.zabbix.zabbix_mediatype: + register: zbxmediatype_reset + + - ansible.builtin.assert: + that: zbxmediatype_reset.changed is sameas True + + - name: test - update email mediatype with authentication without credentials (fail) + community.zabbix.zabbix_mediatype: + smtp_authentication: true + smtp_security: STARTTLS + register: zbxmediatype_auth_fail + ignore_errors: true + + - ansible.builtin.assert: + that: zbxmediatype_auth_fail.failed is sameas True + + - name: test - update email mediatype with authentication + community.zabbix.zabbix_mediatype: + smtp_authentication: true + smtp_security: STARTTLS + username: zabbix + password: Ex4mP!3 + register: zbxmediatype_auth + + - ansible.builtin.assert: + that: zbxmediatype_auth.changed is sameas True + + - name: test - update email mediatype with authentication (again) + community.zabbix.zabbix_mediatype: + smtp_authentication: true + smtp_security: STARTTLS + username: zabbix + password: Ex4mP!3 + register: zbxmediatype_auth + + - ansible.builtin.assert: + that: zbxmediatype_auth.changed is sameas False + + - name: test - update email mediatype with SSL/TLS and host/peer verification + community.zabbix.zabbix_mediatype: + smtp_authentication: true + smtp_security: SSL/TLS + smtp_verify_host: true + smtp_verify_peer: true + username: zabbix + password: Ex4mP!3 + register: zbxmediatype_verif + + - ansible.builtin.assert: + that: zbxmediatype_verif.changed is sameas True + + - name: test - update email mediatype with SSL/TLS and host/peer verification (again) + community.zabbix.zabbix_mediatype: + smtp_authentication: true + smtp_security: SSL/TLS + smtp_verify_host: true + smtp_verify_peer: true + username: zabbix + password: Ex4mP!3 + register: zbxmediatype_verif + + - ansible.builtin.assert: + that: zbxmediatype_verif.changed is sameas False + - name: test - reset email mediatype smtp information to default - zabbix_mediatype: + community.zabbix.zabbix_mediatype: register: zbxmediatype_reset - - assert: + - ansible.builtin.assert: that: zbxmediatype_reset.changed is sameas True - name: test - update email mediatype concurrent settings - zabbix_mediatype: + community.zabbix.zabbix_mediatype: max_sessions: 99 max_attempts: 10 attempt_interval: 30s register: zbxmediatype_concur - - assert: + - ansible.builtin.assert: that: zbxmediatype_concur.changed is sameas True - name: test - update email mediatype concurrent settings (again) - zabbix_mediatype: + community.zabbix.zabbix_mediatype: max_sessions: 99 max_attempts: 10 attempt_interval: 30s register: zbxmediatype_concur - - assert: + - ansible.builtin.assert: that: zbxmediatype_concur.changed is sameas False - name: test - update email mediatype concurrent settings above range (fail) - zabbix_mediatype: + community.zabbix.zabbix_mediatype: max_sessions: 102 max_attempts: 101 attempt_interval: 61m register: zbxmediatype_concur_fail ignore_errors: true - - assert: + - ansible.builtin.assert: that: zbxmediatype_concur_fail.failed is sameas True - - when: zabbix_version is version('5.0', '>=') - block: - name: test - reset email mediatype smtp information to default - zabbix_mediatype: + community.zabbix.zabbix_mediatype: register: zbxmediatype_reset - - assert: + - ansible.builtin.assert: that: zbxmediatype_reset.changed is sameas True - name: test - update email mediatype with message templates - zabbix_mediatype: + community.zabbix.zabbix_mediatype: message_templates: - eventsource: triggers recovery: operations @@ -177,11 +173,11 @@ body: "Internal event started at {EVEN.TIME} on {EVENT.DATE}\r\nEvent name: {EVENT.NAME}\r\n" register: zbxmediatype_msg_templates - - assert: + - ansible.builtin.assert: that: zbxmediatype_msg_templates.changed is sameas True - name: test - update email mediatype with message templates (again) - zabbix_mediatype: + community.zabbix.zabbix_mediatype: message_templates: - eventsource: triggers recovery: operations @@ -201,11 +197,11 @@ body: "Internal event started at {EVEN.TIME} on {EVENT.DATE}\r\nEvent name: {EVENT.NAME}\r\n" register: zbxmediatype_msg_templates - - assert: + - ansible.builtin.assert: that: zbxmediatype_msg_templates.changed is sameas False - name: test - update subject of message template in email mediatype - zabbix_mediatype: + community.zabbix.zabbix_mediatype: message_templates: - eventsource: triggers recovery: operations @@ -225,11 +221,11 @@ body: "Internal event started at {EVEN.TIME} on {EVENT.DATE}\r\nEvent name: {EVENT.NAME}\r\n" register: zbxmediatype_msg_templates - - assert: + - ansible.builtin.assert: that: zbxmediatype_msg_templates.changed is sameas True - name: test - update message of message template in email mediatype - zabbix_mediatype: + community.zabbix.zabbix_mediatype: message_templates: - eventsource: triggers recovery: operations @@ -249,11 +245,11 @@ body: "Internal event started at {EVEN.TIME} on {EVENT.DATE}\r\nEvent name: {EVENT.NAME}\r\n" register: zbxmediatype_msg_templates - - assert: + - ansible.builtin.assert: that: zbxmediatype_msg_templates.changed is sameas True - name: test - update subject and message of message template in email mediatype (again) - zabbix_mediatype: + community.zabbix.zabbix_mediatype: message_templates: - eventsource: triggers recovery: operations @@ -273,40 +269,40 @@ body: "Internal event started at {EVEN.TIME} on {EVENT.DATE}\r\nEvent name: {EVENT.NAME}\r\n" register: zbxmediatype_msg_templates - - assert: + - ansible.builtin.assert: that: zbxmediatype_msg_templates.changed is sameas False - - name: test - disable email mediatype - zabbix_mediatype: - status: disabled - register: zbxmediatype_disable + - name: test - disable email mediatype + community.zabbix.zabbix_mediatype: + status: disabled + register: zbxmediatype_disable - - assert: - that: zbxmediatype_disable.changed is sameas True + - ansible.builtin.assert: + that: zbxmediatype_disable.changed is sameas True - - name: test - disable email mediatype (again) - zabbix_mediatype: - status: disabled - register: zbxmediatype_disable + - name: test - disable email mediatype (again) + community.zabbix.zabbix_mediatype: + status: disabled + register: zbxmediatype_disable - - assert: - that: zbxmediatype_disable.changed is sameas False + - ansible.builtin.assert: + that: zbxmediatype_disable.changed is sameas False - - name: test - delete email mediatype - zabbix_mediatype: - state: absent - register: zbxmediatype_delete + - name: test - delete email mediatype + community.zabbix.zabbix_mediatype: + state: absent + register: zbxmediatype_delete - - assert: - that: zbxmediatype_delete.changed is sameas True + - ansible.builtin.assert: + that: zbxmediatype_delete.changed is sameas True - - name: test - delete email mediatype (again) - zabbix_mediatype: - state: absent - register: zbxmediatype_delete + - name: test - delete email mediatype (again) + community.zabbix.zabbix_mediatype: + state: absent + register: zbxmediatype_delete - - assert: - that: zbxmediatype_delete.changed is sameas False + - ansible.builtin.assert: + that: zbxmediatype_delete.changed is sameas False - name: test - script mediatypes module_defaults: @@ -316,59 +312,59 @@ type: script block: - - name: test - create new script mediatype - zabbix_mediatype: - script_name: /usr/local/bin/script.sh - register: zbxmediatype_script_new - - - assert: - that: zbxmediatype_script_new.changed is sameas True - - - name: test - create new script mediatype (again) - zabbix_mediatype: - script_name: /usr/local/bin/script.sh - register: zbxmediatype_script_new - - - assert: - that: zbxmediatype_script_new.changed is sameas False - - - name: test - update script mediatype with script parameters - zabbix_mediatype: - script_name: /usr/local/bin/script.sh - script_params: - - '-p test' - - '-q' - register: zbxmediatype_script_params - - - assert: - that: zbxmediatype_script_params.changed is sameas True - - - name: test - update script mediatype with script parameters (again) - zabbix_mediatype: - script_name: /usr/local/bin/script.sh - script_params: - - '-p test' - - '-q' - register: zbxmediatype_script_params - - - assert: - that: zbxmediatype_script_params.changed is sameas False - - - name: test - remove script mediatype parameters - zabbix_mediatype: - script_name: /usr/local/bin/script.sh - register: zbxmediatype_script_params_rev - - - assert: - that: zbxmediatype_script_params_rev.changed is sameas True - - - name: test - delete script mediatype - zabbix_mediatype: - state: absent - register: zbxmediatype_delete - - - assert: - that: zbxmediatype_delete.changed is sameas True + - name: test - create new script mediatype + community.zabbix.zabbix_mediatype: + script_name: /usr/local/bin/script.sh + register: zbxmediatype_script_new + + - ansible.builtin.assert: + that: zbxmediatype_script_new.changed is sameas True + + - name: test - create new script mediatype (again) + community.zabbix.zabbix_mediatype: + script_name: /usr/local/bin/script.sh + register: zbxmediatype_script_new + + - ansible.builtin.assert: + that: zbxmediatype_script_new.changed is sameas False + + - name: test - update script mediatype with script parameters + community.zabbix.zabbix_mediatype: + script_name: /usr/local/bin/script.sh + script_params: + - "-p test" + - "-q" + register: zbxmediatype_script_params + + - ansible.builtin.assert: + that: zbxmediatype_script_params.changed is sameas True + + - name: test - update script mediatype with script parameters (again) + community.zabbix.zabbix_mediatype: + script_name: /usr/local/bin/script.sh + script_params: + - "-p test" + - "-q" + register: zbxmediatype_script_params + + - ansible.builtin.assert: + that: zbxmediatype_script_params.changed is sameas False + + - name: test - remove script mediatype parameters + community.zabbix.zabbix_mediatype: + script_name: /usr/local/bin/script.sh + register: zbxmediatype_script_params_rev + + - ansible.builtin.assert: + that: zbxmediatype_script_params_rev.changed is sameas True + + - name: test - delete script mediatype + community.zabbix.zabbix_mediatype: + state: absent + register: zbxmediatype_delete + + - ansible.builtin.assert: + that: zbxmediatype_delete.changed is sameas True - name: test - sms mediatypes module_defaults: @@ -378,148 +374,63 @@ type: sms block: - - name: test - create new sms mediatype - zabbix_mediatype: - gsm_modem: /dev/ttyS0 - register: zbxmediatype_sms_new + - name: test - create new sms mediatype + community.zabbix.zabbix_mediatype: + gsm_modem: /dev/ttyS0 + register: zbxmediatype_sms_new - - assert: - that: zbxmediatype_sms_new.changed is sameas True + - ansible.builtin.assert: + that: zbxmediatype_sms_new.changed is sameas True - - name: test - create new sms mediatype (again) - zabbix_mediatype: - gsm_modem: /dev/ttyS0 - register: zbxmediatype_sms_new + - name: test - create new sms mediatype (again) + community.zabbix.zabbix_mediatype: + gsm_modem: /dev/ttyS0 + register: zbxmediatype_sms_new - - assert: - that: zbxmediatype_sms_new.changed is sameas False + - ansible.builtin.assert: + that: zbxmediatype_sms_new.changed is sameas False - - when: zabbix_version is version('3.4', '>=') - block: - name: test - update sms mediatype with concurrent settings - zabbix_mediatype: + community.zabbix.zabbix_mediatype: gsm_modem: /dev/ttyS0 max_sessions: 1 max_attempts: 3 attempt_interval: 30 register: zbxmediatype_sms_concur - - assert: + - ansible.builtin.assert: that: zbxmediatype_sms_concur.changed is sameas True - name: test - update sms mediatype with concurrent settings (again) - zabbix_mediatype: + community.zabbix.zabbix_mediatype: gsm_modem: /dev/ttyS0 max_sessions: 1 max_attempts: 3 attempt_interval: 30 register: zbxmediatype_sms_concur - - assert: + - ansible.builtin.assert: that: zbxmediatype_sms_concur.changed is sameas False - name: test - update sms mediatype with invalid max sessions (fail) - zabbix_mediatype: + community.zabbix.zabbix_mediatype: gsm_modem: /dev/ttyS0 max_sessions: 2 register: zbxmediatype_sms_fail ignore_errors: true - - assert: + - ansible.builtin.assert: that: zbxmediatype_sms_fail.failed is sameas True - - name: test - delete sms mediatype - zabbix_mediatype: - state: absent - register: zbxmediatype_delete + - name: test - delete sms mediatype + community.zabbix.zabbix_mediatype: + state: absent + register: zbxmediatype_delete - - assert: - that: zbxmediatype_delete.changed is sameas True - -- name: test - jabber mediatypes - when: zabbix_version is version('4.2', '<=') - module_defaults: - community.zabbix.zabbix_mediatype: - state: present - name: Example jabber - type: jabber - - block: - - name: test - create new jabber mediatype - zabbix_mediatype: - username: zabbix - password: Ex4mP!3 - register: zbxmediatype_jabber_new - - - assert: - that: zbxmediatype_jabber_new.changed is sameas True - - - name: test - create new jabber mediatype (again) - zabbix_mediatype: - username: zabbix - password: Ex4mP!3 - register: zbxmediatype_jabber_new - - - assert: - that: zbxmediatype_jabber_new.changed is sameas False - - - name: test - delete jabber mediatype - zabbix_mediatype: - state: absent - register: zbxmediatype_delete - - - assert: - that: zbxmediatype_delete.changed is sameas True - -- name: test - ez_texting mediatypes - when: zabbix_version is version('4.2', '<=') - module_defaults: - community.zabbix.zabbix_mediatype: - state: present - name: Example ez_texting - type: ez_texting - - block: - - name: test - create new ez_texting mediatype - zabbix_mediatype: - username: zabbix - password: Ex4mP!3 - message_text_limit: USA - register: zbxmediatype_ez_texting_new - - - assert: - that: zbxmediatype_ez_texting_new.changed is sameas True - - - name: test - create new ez_texting mediatype (again) - zabbix_mediatype: - username: zabbix - password: Ex4mP!3 - message_text_limit: USA - register: zbxmediatype_ez_texting_new - - - assert: - that: zbxmediatype_ez_texting_new.changed is sameas False - - - name: test - update ez_texting mediatype with text limit - zabbix_mediatype: - username: zabbix - password: Ex4mP!3 - message_text_limit: Canada - register: zbxmediatype_ez_texting_update - - - assert: - that: zbxmediatype_ez_texting_update.changed is sameas True - - - name: test - delete ez_texting mediatype - zabbix_mediatype: - state: absent - register: zbxmediatype_delete - - - assert: - that: zbxmediatype_delete.changed is sameas True + - ansible.builtin.assert: + that: zbxmediatype_delete.changed is sameas True - name: test - email mediatypes - when: zabbix_version is version('4.4', '>=') module_defaults: community.zabbix.zabbix_mediatype: state: present @@ -528,151 +439,150 @@ webhook_script: "return 'Hello, world!';" block: - - name: test - create new webhook mediatype - zabbix_mediatype: - register: zbxmediatype_webhook_new - - - assert: - that: zbxmediatype_webhook_new.changed is sameas True - - - name: test - create new webhook mediatype (again) - zabbix_mediatype: - register: zbxmediatype_webhook_new - - - assert: - that: zbxmediatype_webhook_new.changed is sameas False - - - name: test - update webhook mediatype with process_tags - zabbix_mediatype: - process_tags: true - register: zbxmediatype_webhook_tags - - - assert: - that: zbxmediatype_webhook_tags.changed is sameas True - - - name: test - update webhook mediatype with process_tags (again) - zabbix_mediatype: - process_tags: true - register: zbxmediatype_webhook_tags - - - assert: - that: zbxmediatype_webhook_tags.changed is sameas False - - # supported since 4.4 - - name: test - update webhook mediatype with description - zabbix_mediatype: - process_tags: true - description: My custom webhook mediatype - register: zbxmediatype_webhook_desc - - - assert: - that: zbxmediatype_webhook_desc.changed is sameas True - - - name: test - update webhook mediatype with description (again) - zabbix_mediatype: - process_tags: true - description: My custom webhook mediatype - register: zbxmediatype_webhook_desc - - - assert: - that: zbxmediatype_webhook_desc.changed is sameas False - - - name: test - update webhook mediatype with event_menu without name and url (fail) - zabbix_mediatype: - process_tags: true - description: My custom webhook mediatype - event_menu: true - register: zbxmediatype_webhook_eventmenu - ignore_errors: true - - - assert: - that: zbxmediatype_webhook_eventmenu.failed is sameas True - - - name: test - update webhook mediatype with event_menu - zabbix_mediatype: - process_tags: true - description: My custom webhook mediatype - event_menu: true - event_menu_name: Example entry name - event_menu_url: '{EVENT.TAGS.__message_link}' - register: zbxmediatype_webhook_eventmenu - - - assert: - that: zbxmediatype_webhook_eventmenu.changed is sameas True - - - name: test - update webhook mediatype with event_menu (again) - zabbix_mediatype: - process_tags: true - description: My custom webhook mediatype - event_menu: true - event_menu_name: Example entry name - event_menu_url: '{EVENT.TAGS.__message_link}' - register: zbxmediatype_webhook_eventmenu - - - assert: - that: zbxmediatype_webhook_eventmenu.changed is sameas False - - - name: test - reset webhook mediatype to default - zabbix_mediatype: - register: zbxmediatype_reset - - - assert: - that: zbxmediatype_reset.changed is sameas True - - - name: test - update webhook mediatype with webhook_params - zabbix_mediatype: - webhook_params: - - name: param1 - value: value1 - register: zbxmediatype_webhook_params - - - assert: - that: zbxmediatype_webhook_params.changed is sameas True - - - name: test - update webhook mediatype with webhook_params (again) - zabbix_mediatype: - webhook_params: - - name: param1 - value: value1 - register: zbxmediatype_webhook_params - - - assert: - that: zbxmediatype_webhook_params.changed is sameas False - - - name: test - update webhook mediatype with webhook_params (reorder) - zabbix_mediatype: - webhook_params: - - name: z.param2 - value: xyz - - name: param1 - value: value1 - - name: b.param3 - - name: a.param4 - value: abc - register: zbxmediatype_webhook_params - - - assert: - that: zbxmediatype_webhook_params.changed is sameas True - - - name: test - update webhook mediatype with webhook_params (reorder again) - zabbix_mediatype: - webhook_params: - - name: param1 - value: value1 - - name: a.param4 - value: abc - - name: b.param3 - - name: z.param2 - value: xyz - register: zbxmediatype_webhook_params - - - assert: - that: zbxmediatype_webhook_params.changed is sameas False - - - name: test - delete webhook mediatype - zabbix_mediatype: - state: absent - register: zbxmediatype_delete - - - assert: - that: zbxmediatype_delete.changed is sameas True + - name: test - create new webhook mediatype + community.zabbix.zabbix_mediatype: + register: zbxmediatype_webhook_new + + - ansible.builtin.assert: + that: zbxmediatype_webhook_new.changed is sameas True + + - name: test - create new webhook mediatype (again) + community.zabbix.zabbix_mediatype: + register: zbxmediatype_webhook_new + + - ansible.builtin.assert: + that: zbxmediatype_webhook_new.changed is sameas False + + - name: test - update webhook mediatype with process_tags + community.zabbix.zabbix_mediatype: + process_tags: true + register: zbxmediatype_webhook_tags + + - ansible.builtin.assert: + that: zbxmediatype_webhook_tags.changed is sameas True + + - name: test - update webhook mediatype with process_tags (again) + community.zabbix.zabbix_mediatype: + process_tags: true + register: zbxmediatype_webhook_tags + + - ansible.builtin.assert: + that: zbxmediatype_webhook_tags.changed is sameas False + + - name: test - update webhook mediatype with description + community.zabbix.zabbix_mediatype: + process_tags: true + description: My custom webhook mediatype + register: zbxmediatype_webhook_desc + + - ansible.builtin.assert: + that: zbxmediatype_webhook_desc.changed is sameas True + + - name: test - update webhook mediatype with description (again) + community.zabbix.zabbix_mediatype: + process_tags: true + description: My custom webhook mediatype + register: zbxmediatype_webhook_desc + + - ansible.builtin.assert: + that: zbxmediatype_webhook_desc.changed is sameas False + + - name: test - update webhook mediatype with event_menu without name and url (fail) + community.zabbix.zabbix_mediatype: + process_tags: true + description: My custom webhook mediatype + event_menu: true + register: zbxmediatype_webhook_eventmenu + ignore_errors: true + + - ansible.builtin.assert: + that: zbxmediatype_webhook_eventmenu.failed is sameas True + + - name: test - update webhook mediatype with event_menu + community.zabbix.zabbix_mediatype: + process_tags: true + description: My custom webhook mediatype + event_menu: true + event_menu_name: Example entry name + event_menu_url: "{EVENT.TAGS.__message_link}" + register: zbxmediatype_webhook_eventmenu + + - ansible.builtin.assert: + that: zbxmediatype_webhook_eventmenu.changed is sameas True + + - name: test - update webhook mediatype with event_menu (again) + community.zabbix.zabbix_mediatype: + process_tags: true + description: My custom webhook mediatype + event_menu: true + event_menu_name: Example entry name + event_menu_url: "{EVENT.TAGS.__message_link}" + register: zbxmediatype_webhook_eventmenu + + - ansible.builtin.assert: + that: zbxmediatype_webhook_eventmenu.changed is sameas False + + - name: test - reset webhook mediatype to default + community.zabbix.zabbix_mediatype: + register: zbxmediatype_reset + + - ansible.builtin.assert: + that: zbxmediatype_reset.changed is sameas True + + - name: test - update webhook mediatype with webhook_params + community.zabbix.zabbix_mediatype: + webhook_params: + - name: param1 + value: value1 + register: zbxmediatype_webhook_params + + - ansible.builtin.assert: + that: zbxmediatype_webhook_params.changed is sameas True + + - name: test - update webhook mediatype with webhook_params (again) + community.zabbix.zabbix_mediatype: + webhook_params: + - name: param1 + value: value1 + register: zbxmediatype_webhook_params + + - ansible.builtin.assert: + that: zbxmediatype_webhook_params.changed is sameas False + + - name: test - update webhook mediatype with webhook_params (reorder) + community.zabbix.zabbix_mediatype: + webhook_params: + - name: z.param2 + value: xyz + - name: param1 + value: value1 + - name: b.param3 + - name: a.param4 + value: abc + register: zbxmediatype_webhook_params + + - ansible.builtin.assert: + that: zbxmediatype_webhook_params.changed is sameas True + + - name: test - update webhook mediatype with webhook_params (reorder again) + community.zabbix.zabbix_mediatype: + webhook_params: + - name: param1 + value: value1 + - name: a.param4 + value: abc + - name: b.param3 + - name: z.param2 + value: xyz + register: zbxmediatype_webhook_params + + - ansible.builtin.assert: + that: zbxmediatype_webhook_params.changed is sameas False + + - name: test - delete webhook mediatype + community.zabbix.zabbix_mediatype: + state: absent + register: zbxmediatype_delete + + - ansible.builtin.assert: + that: zbxmediatype_delete.changed is sameas True diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_module_defaults_group/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_module_defaults_group/tasks/main.yml index 5b861810a..04b19f2d4 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_module_defaults_group/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_module_defaults_group/tasks/main.yml @@ -7,11 +7,11 @@ state: present block: - name: Create host group - zabbix_group: + community.zabbix.zabbix_group: register: _grp - name: Create host - zabbix_host: + community.zabbix.zabbix_host: host_name: Example Host interfaces: - type: agent @@ -20,7 +20,7 @@ register: _host - name: Assert that resources were correctly created - assert: + ansible.builtin.assert: that: - _grp is changed - _host is changed @@ -33,16 +33,16 @@ state: absent block: - name: Delete host - zabbix_host: + community.zabbix.zabbix_host: host_name: Example Host register: _host - name: Delete host group - zabbix_group: + community.zabbix.zabbix_group: register: _grp - name: Assert that resources were correctly deleted - assert: + ansible.builtin.assert: that: - _grp is changed - _host is changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy/tasks/main.yml index ee96e6e80..86ece24f3 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: test - create new passive Zabbix proxy server - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -13,11 +13,11 @@ register: zbxproxy_new - name: assert that proxy was created - assert: + ansible.builtin.assert: that: zbxproxy_new is changed - name: test - create same passive Zabbix proxy server - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -30,11 +30,11 @@ register: zbxproxy_existing - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxproxy_existing is changed - name: test - update Zabbix proxy server description - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -47,11 +47,11 @@ register: zbxproxy_desc_update - name: assert that description has been updated - assert: + ansible.builtin.assert: that: zbxproxy_desc_update is changed - name: test - update Zabbix proxy server interface - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -64,11 +64,11 @@ register: zbxproxy_interface_update - name: assert that interface has been updated - assert: + ansible.builtin.assert: that: zbxproxy_interface_update is changed - name: test - update Zabbix proxy server description & interface (again) - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -81,11 +81,11 @@ register: zbxproxy_desc_interface_update - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxproxy_desc_interface_update is changed - name: test - update Zabbix proxy server interface to use only ip - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -97,11 +97,11 @@ register: zbxproxy_interface_onlyip - name: assert that interface has been updated - assert: + ansible.builtin.assert: that: zbxproxy_interface_onlyip is changed - name: test - update Zabbix proxy server interface to use only ip again - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -113,11 +113,11 @@ register: zbxproxy_interface_onlyip_again - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxproxy_interface_onlyip_again is changed - name: test - update Zabbix proxy server interface to use only dns - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -129,11 +129,11 @@ register: zbxproxy_interface_onlydns - name: assert that interface has been updated - assert: + ansible.builtin.assert: that: zbxproxy_interface_onlydns is changed - name: test - update Zabbix proxy server interface to use only dns again - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -145,11 +145,11 @@ register: zbxproxy_interface_onlydns_again - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxproxy_interface_onlydns_again is changed - name: test - update Zabbix proxy server interface to fail - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy desc state: present @@ -162,11 +162,11 @@ ignore_errors: true - name: assert that module has failed - assert: + ansible.builtin.assert: that: zbxproxy_interface_fail is failed - name: test - update Zabbix proxy server to be active - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -174,11 +174,11 @@ register: zbxproxy_active_update - name: assert that proxy was updated - assert: + ansible.builtin.assert: that: zbxproxy_active_update is changed - name: test - update Zabbix proxy server to be active (again) - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -186,41 +186,37 @@ register: zbxproxy_active_update_again - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxproxy_active_update_again is changed -# proxy_address available on zabbix 4.0 and above -- block: - - name: test - update Zabbix proxy server to be active and use proxy_address - zabbix_proxy: - proxy_name: zbxproxy_example01 - description: Example Zabbix Proxy - state: present - status: active - proxy_address: 10.1.1.0/24,zabbix.example.com - register: zbxproxy_active_proxyaddress - - - name: assert that proxy was updated - assert: - that: zbxproxy_active_proxyaddress is changed - - - name: test - update Zabbix proxy server to be active use proxy_address (again) - zabbix_proxy: - proxy_name: zbxproxy_example01 - description: Example Zabbix Proxy - state: present - status: active - proxy_address: 10.1.1.0/24,zabbix.example.com - register: zbxproxy_active_proxyaddress_again - - - name: assert that nothing has been changed - assert: - that: not zbxproxy_active_proxyaddress_again is changed - - when: zabbix_version != "3.0" +- name: test - update Zabbix proxy server to be active and use proxy_address + community.zabbix.zabbix_proxy: + proxy_name: zbxproxy_example01 + description: Example Zabbix Proxy + state: present + status: active + proxy_address: 10.1.1.0/24,zabbix.example.com + register: zbxproxy_active_proxyaddress + +- name: assert that proxy was updated + ansible.builtin.assert: + that: zbxproxy_active_proxyaddress is changed + +- name: test - update Zabbix proxy server to be active use proxy_address (again) + community.zabbix.zabbix_proxy: + proxy_name: zbxproxy_example01 + description: Example Zabbix Proxy + state: present + status: active + proxy_address: 10.1.1.0/24,zabbix.example.com + register: zbxproxy_active_proxyaddress_again + +- name: assert that nothing has been changed + ansible.builtin.assert: + that: not zbxproxy_active_proxyaddress_again is changed - name: test - update Zabbix proxy server to use encryption - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -232,11 +228,11 @@ register: zbxproxy_encryption - name: assert that encryption has been enabled - assert: + ansible.builtin.assert: that: zbxproxy_encryption is changed - name: test - update Zabbix proxy server to use encryption (again) - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -248,19 +244,11 @@ register: zbxproxy_encryption_again - name: assert that nothing has been changed - assert: - that: not zbxproxy_encryption_again is changed - when: zabbix_version < "6.0" - -# With Zabbix >= 6.0 tls_psk and tls_psk_identity cannot be read -# thus there is no way to check idempotency -- name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: zbxproxy_encryption_again is changed - when: zabbix_version >= "6.0" - name: test - update Zabbix proxy server encryption settings - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -272,11 +260,11 @@ register: zbxproxy_encryption_update - name: assert that encryption has been updated - assert: + ansible.builtin.assert: that: zbxproxy_encryption_update is changed - name: test - update Zabbix proxy server back to being passive - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 description: Example Zabbix Proxy state: present @@ -289,25 +277,25 @@ register: zbxproxy_passive_update - name: assert that proxy was updated - assert: + ansible.builtin.assert: that: zbxproxy_passive_update is changed - name: test - delete Zabbix proxy server - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 state: absent register: zbxproxy_delete - name: assert that proxy has been deleted - assert: + ansible.builtin.assert: that: zbxproxy_delete is changed - name: test - delete Zabbix proxy server (again) - zabbix_proxy: + community.zabbix.zabbix_proxy: proxy_name: zbxproxy_example01 state: absent register: zbxproxy_delete_again - name: assert that nothing has been changed - assert: + ansible.builtin.assert: that: not zbxproxy_delete_again is changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy_info/tasks/main.yml index a5feb2731..ddd101850 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy_info/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_proxy_info/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: test - Create new Zabbix proxy - zabbix_proxy: + community.zabbix.zabbix_proxy: state: present proxy_name: ExampleProxy description: ExampleProxy @@ -12,12 +12,12 @@ dns: ExampleProxy.local register: create_proxy_result -- assert: +- ansible.builtin.assert: that: - create_proxy_result.changed is sameas true - name: test - Create new Zabbix host monitored by the proxy - zabbix_host: + community.zabbix.zabbix_host: state: present host_name: ExampleHost host_groups: @@ -33,33 +33,33 @@ port: "10050" register: create_host_result -- assert: +- ansible.builtin.assert: that: - create_host_result.changed is sameas true - name: test - Get zabbix proxy information - zabbix_proxy_info: + community.zabbix.zabbix_proxy_info: proxy_name: ExampleProxy proxy_hosts: true register: get_proxy_info_result -- assert: +- ansible.builtin.assert: that: - - get_proxy_info_result["zabbix_proxy"].host == "ExampleProxy" - - get_proxy_info_result["zabbix_proxy"].hosts | length > 0 - - get_proxy_info_result["zabbix_proxy"].hosts[0].host == "ExampleHost" - - get_proxy_info_result["zabbix_proxy"].interface | length > 0 - - get_proxy_info_result["zabbix_proxy"].interface.ip == "10.1.1.2" - - get_proxy_info_result["zabbix_proxy"].interface.useip == "1" - - get_proxy_info_result["zabbix_proxy"].interface.port == "10051" - - get_proxy_info_result["zabbix_proxy"].interface.dns == "ExampleProxy.local" + - get_proxy_info_result["zabbix_proxy"].host == "ExampleProxy" + - get_proxy_info_result["zabbix_proxy"].hosts | length > 0 + - get_proxy_info_result["zabbix_proxy"].hosts[0].host == "ExampleHost" + - get_proxy_info_result["zabbix_proxy"].interface | length > 0 + - get_proxy_info_result["zabbix_proxy"].interface.ip == "10.1.1.2" + - get_proxy_info_result["zabbix_proxy"].interface.useip == "1" + - get_proxy_info_result["zabbix_proxy"].interface.port == "10051" + - get_proxy_info_result["zabbix_proxy"].interface.dns == "ExampleProxy.local" - name: test - cleanup test Zabbix host - zabbix_host: + community.zabbix.zabbix_host: state: absent host_name: ExampleHost - name: test - cleanup test Zabbix proxy - zabbix_proxy: + community.zabbix.zabbix_proxy: state: absent proxy_name: ExampleProxy diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_regexp/meta/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_regexp/meta/main.yml new file mode 100644 index 000000000..acdb704c8 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_regexp/meta/main.yml @@ -0,0 +1,3 @@ +--- +dependencies: + - setup_zabbix diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_regexp/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_regexp/tasks/main.yml new file mode 100644 index 000000000..8e2afc02d --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_regexp/tasks/main.yml @@ -0,0 +1,113 @@ +--- +- name: test - do not run tests with < Zabbix 4.0 + meta: end_play + when: zabbix_version is version('4.0', '<') + +- when: zabbix_version is version('6.0', '<') + name: Unsupport Zabbix version (<6.0) + block: + - name: test - fail to update regexp setting + community.zabbix.zabbix_regexp: + name: File systems for discovery + test_string: ext3 + expressions: + - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$" + - expression_type: result_is_true + ignore_errors: true + register: zbxauth_update + + - ansible.builtin.assert: + that: zbxauth_update.failed is sameas True + +- when: zabbix_version is version('6.0', '>=') + name: support Zabbix version (>=6.0) + block: + - name: test - try to update regexp (present) + community.zabbix.zabbix_regexp: + name: File systems for discovery + test_string: ext3 + expressions: + - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$" + expression_type: result_is_true + register: zbxregexp_update + + - name: assert that regexp was NOT updated + ansible.builtin.assert: + that: + - zbxregexp_update.changed is sameas False + + - name: test - try to delete regexp + community.zabbix.zabbix_regexp: + name: File systems for discovery + state: absent + register: zbxregexp_update + + - name: assert that regexp was deleted + ansible.builtin.assert: + that: + - zbxregexp_update.changed is sameas True + - zbxregexp_update.msg == "Successfully deleted regular expression setting." + + - name: test - try to create regexp + community.zabbix.zabbix_regexp: + name: File systems for discovery + test_string: ext3 + expressions: + - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$" + expression_type: result_is_true + register: zbxregexp_update + + - name: assert that regexp was created + ansible.builtin.assert: + that: + - zbxregexp_update.changed is sameas True + - zbxregexp_update.msg == "Successfully created regular expression setting." + + - name: test - try to update regexp + community.zabbix.zabbix_regexp: + name: File systems for discovery + test_string: ext3 + expressions: + - expression: "create" + expression_type: character_string_included + - expression: "update/delete" + expression_type: any_character_string_included + case_sensitive: true + exp_delimiter: "/" + - expression: "failed" + expression_type: character_string_not_included + - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$" + expression_type: result_is_true + - expression: "regexp" + expression_type: result_is_false + register: zbxregexp_update + + - name: assert that regexp was updated + ansible.builtin.assert: + that: + - zbxregexp_update.changed is sameas True + - zbxregexp_update.msg == "Successfully updated regular expression setting." + + - name: test - try to update regexp (will not update) + community.zabbix.zabbix_regexp: + name: File systems for discovery + test_string: ext3 + expressions: + - expression: "update/delete" + expression_type: any_character_string_included + case_sensitive: true + exp_delimiter: "/" + - expression: "create" + expression_type: character_string_included + - expression: "failed" + expression_type: character_string_not_included + - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$" + expression_type: result_is_true + - expression: "regexp" + expression_type: result_is_false + register: zbxregexp_update + + - name: assert that regexp was updated + ansible.builtin.assert: + that: + - zbxregexp_update.changed is sameas False diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_screen/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_screen/tasks/main.yml deleted file mode 100644 index 82d1e5f0e..000000000 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_screen/tasks/main.yml +++ /dev/null @@ -1,149 +0,0 @@ ---- - -- name: ensure zabbix server is being monitored - community.zabbix.zabbix_host: - host_name: Zabbix server - status: enabled - -- name: "Screen got removed with 5.4" - block: - - name: test - Check if screen fails on Zabbix >= 5.4 - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreenFail54 - host_group: Zabbix servers - state: present - graph_names: - - 'Zabbix cache usage, % used' - - 'Zabbix internal process busy %' - graph_width: 200 - graph_height: 100 - graphs_in_row: 5 - register: result - ignore_errors: true - when: zabbix_version is version('5.4', '>=') - - - name: expect to fail - assert: - that: - - "result is failed" - when: zabbix_version is version('5.4', '>=') - - - name: End play if Zabbix >= 5.4 - meta: end_play - when: zabbix_version is version('5.4', '>=') - -- name: test - delete the screen again - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - state: absent - -# ################################################# -# Test screen creation -# ################################################# - -- name: test - Create a new screen - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - host_group: Zabbix servers - state: present - graph_names: - - 'Zabbix cache usage, % used' - - 'Zabbix internal process busy %' - graph_width: 200 - graph_height: 100 - graphs_in_row: 5 - register: result - -- assert: - that: - - result.changed - -- name: test - Create a new screen again - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - host_group: Zabbix servers - state: present - graph_names: - - 'Zabbix cache usage, % used' - - 'Zabbix internal process busy %' - graph_width: 200 - graph_height: 100 - graphs_in_row: 5 - register: result - -- assert: - that: - - not result.changed - -# ################################################# -# Test screen editing -# ################################################# - -- name: test - Adding new graph - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - host_group: Zabbix servers - state: present - graph_names: - - 'Zabbix cache usage, % used' - - 'Zabbix internal process busy %' - - 'Zabbix internal queues' - - 'Zabbix server performance' - - 'Zabbix data gathering process busy %' - graph_width: 200 - graph_height: 100 - graphs_in_row: 5 - register: result - -- assert: - that: - - result.changed - -- name: test - Removing graph - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - host_group: Zabbix servers - state: present - graph_names: - - 'Zabbix cache usage, % used' - - 'Zabbix internal queues' - graph_width: 200 - graph_height: 100 - graphs_in_row: 5 - register: result - -- assert: - that: - - result.changed - -# ################################################# -# Test screen deletion -# ################################################# - -- name: test - delete the screen - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - state: absent - register: result - -- assert: - that: - - result.changed - -- name: test - delete the screen again - community.zabbix.zabbix_screen: - screens: - - screen_name: TestScreen1 - state: absent - register: result - -- assert: - that: - - not result.changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_script/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_script/tasks/main.yml index fe5c40519..4c5ea8a4c 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_script/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_script/tasks/main.yml @@ -1,347 +1,343 @@ --- -- name: test - do not run tests for Zabbix < 6.0 - meta: end_play - when: zabbix_version is version('6.0', '<') - - name: test - Test action operation script module_defaults: community.zabbix.zabbix_script: name: Test action operation script scope: action_operation script_type: webhook - command: 'return 0' + command: "return 0" description: "Test action operation script" state: present block: - - name: test - Create new action operation script to execute webhook check mode - zabbix_script: - check_mode: true - register: create_action_check_mode_result - - - assert: - that: - - create_action_check_mode_result.changed is sameas true - - - name: test - Create new action operation script to execute webhook - zabbix_script: - register: create_action_result - - - assert: - that: - - create_action_result.changed is sameas true - - - name: test - Create new action operation script to execute webhook again - zabbix_script: - register: create_action_again_result - - - assert: - that: - - create_action_again_result.changed is sameas false - - - name: test - Update action operation script to execute webhook with host group - zabbix_script: - host_group: 'Discovered hosts' - register: update_action_host_group_result - - - assert: - that: - - update_action_host_group_result.changed is sameas true - - - name: test - Update action operation script to execute webhook with host group again - zabbix_script: - host_group: 'Discovered hosts' - register: update_action_host_group_again_result - - - assert: - that: - - update_action_host_group_again_result.changed is sameas false - - - name: test - Update action operation script to execute webhook with parameters - zabbix_script: - host_group: 'Discovered hosts' - parameters: - - name: param_name1 - register: update_action_param_result - - - assert: - that: - - update_action_param_result.changed is sameas true - - - name: test - Update action operation script to execute webhook with parameters again - zabbix_script: - host_group: 'Discovered hosts' - parameters: - - name: param_name1 - register: update_action_param_again_result - - - assert: - that: - - update_action_param_again_result.changed is sameas false - - - name: test - Update action operation script to execute webhook with parameters and value - zabbix_script: - host_group: 'Discovered hosts' - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: update_action_param_value_result - - - assert: - that: - - update_action_param_value_result.changed is sameas true - - - name: test - Update action operation script to execute webhook with parameters and value again - zabbix_script: - host_group: 'Discovered hosts' - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: update_action_param_value_again_result - - - assert: - that: - - update_action_param_value_again_result.changed is sameas false - - - name: test - Update action operation script remove host group - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: update_action_no_host_group_result - - - assert: - that: - - update_action_no_host_group_result.changed is sameas true - - - name: test - Update action operation script remove host group again - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: update_action_no_host_group_again_result - - - assert: - that: - - update_action_no_host_group_again_result.changed is sameas false - - - name: test - Update action operation script to type Script - zabbix_script: - script_type: script - execute_on: zabbix_agent - command: echo 1 - register: update_action_script_result - - - assert: - that: - - update_action_script_result.changed is sameas true - - - name: test - Update action operation script to type Script again - zabbix_script: - script_type: script - execute_on: zabbix_agent - command: echo 1 - register: update_action_script_again_result - - - assert: - that: - - update_action_script_again_result.changed is sameas false - - - name: test - Update action operation script to execute on server - zabbix_script: - script_type: script - execute_on: zabbix_server - command: echo 1 - register: update_action_script_server_result - - - assert: - that: - - update_action_script_server_result.changed is sameas true - - - name: test - Update action operation script to execute on server again - zabbix_script: - script_type: script - execute_on: zabbix_server - command: echo 1 - register: update_action_script_server_again_result - - - assert: - that: - - update_action_script_server_again_result.changed is sameas false - - - name: test - Update action operation script to execute on server or proxy - zabbix_script: - script_type: script - execute_on: zabbix_server_proxy - command: echo 1 - register: update_action_script_server_proxy_result - - - assert: - that: - - update_action_script_server_proxy_result.changed is sameas true - - - name: test - Update action operation script to execute on server or proxy again - zabbix_script: - script_type: script - execute_on: zabbix_server_proxy - command: echo 1 - register: update_action_script_server_proxy_again_result - - - assert: - that: - - update_action_script_server_proxy_again_result.changed is sameas false - - - name: test - Update action operation script to type SSH - zabbix_script: - script_type: ssh - authtype: password - username: bla - password: blabla - command: echo 2 - register: update_action_script_ssh_result - - - assert: - that: - - update_action_script_ssh_result.changed is sameas true - - - name: test - Update action operation script to type SSH again - zabbix_script: - script_type: ssh - authtype: password - username: bla - password: blabla - command: echo 2 - register: update_action_script_ssh_again_result - - - assert: - that: - - update_action_script_ssh_again_result.changed is sameas false - - - name: test - Update action operation script type SSH key auth - zabbix_script: - script_type: ssh - authtype: public_key - username: bla - publickey: blabla - privatekey: blablabla - command: echo 3 - register: update_action_script_ssh_authkey_result - - - assert: - that: - - update_action_script_ssh_authkey_result.changed is sameas true - - - name: test - Update action operation script type SSH key auth again - zabbix_script: - script_type: ssh - authtype: public_key - username: bla - publickey: blabla - privatekey: blablabla - command: echo 3 - register: update_action_script_ssh_authkey_again_result - - - assert: - that: - - update_action_script_ssh_authkey_again_result.changed is sameas false - - - name: test - Update action operation script type SSH add port - zabbix_script: - script_type: ssh - authtype: public_key - username: bla - publickey: blabla - privatekey: blablabla - command: echo 3 - port: 222 - register: update_action_script_ssh_port_result - - - assert: - that: - - update_action_script_ssh_port_result.changed is sameas true - - - name: test - Update action operation script type SSH add port again - zabbix_script: - script_type: ssh - authtype: public_key - username: bla - publickey: blabla - privatekey: blablabla - command: echo 3 - port: 222 - register: update_action_script_ssh_port_again_result - - - assert: - that: - - update_action_script_ssh_port_again_result.changed is sameas false - - - name: test - Update action operation script to type Telnet - zabbix_script: - script_type: telnet - username: bla1 - password: blabla1 - command: echo 4 - port: 223 - register: update_action_script_telnet_result - - - assert: - that: - - update_action_script_telnet_result.changed is sameas true - - - name: test - Update action operation script to type Telnet again - zabbix_script: - script_type: telnet - username: bla1 - password: blabla1 - command: echo 4 - port: 223 - register: update_action_script_telnet_again_result - - - assert: - that: - - update_action_script_telnet_again_result.changed is sameas false - - - name: test - Update action operation script to type IPMI - zabbix_script: - script_type: ipmi - command: echo 5 - register: update_action_script_ipmi_result - - - assert: - that: - - update_action_script_ipmi_result.changed is sameas true - - - name: test - Update action operation script to type IPMI again - zabbix_script: - script_type: ipmi - command: echo 5 - register: update_action_script_ipmi_again_result - - - assert: - that: - - update_action_script_ipmi_again_result.changed is sameas false - - - name: test - Delete action operation script - zabbix_script: - state: absent - register: delete_action_result - - - assert: - that: - - delete_action_result.changed is sameas true - - - name: test - Delete action operation script again - zabbix_script: - state: absent - register: delete_action_again_result - - - assert: - that: - - delete_action_again_result.changed is sameas false + - name: test - Create new action operation script to execute webhook check mode + zabbix_script: + check_mode: true + register: create_action_check_mode_result + + - assert: + that: + - create_action_check_mode_result.changed is sameas true + + - name: test - Create new action operation script to execute webhook + zabbix_script: + register: create_action_result + + - assert: + that: + - create_action_result.changed is sameas true + + - name: test - Create new action operation script to execute webhook again + zabbix_script: + register: create_action_again_result + + - assert: + that: + - create_action_again_result.changed is sameas false + + - name: test - Update action operation script to execute webhook with host group + zabbix_script: + host_group: "Discovered hosts" + register: update_action_host_group_result + + - assert: + that: + - update_action_host_group_result.changed is sameas true + + - name: test - Update action operation script to execute webhook with host group again + zabbix_script: + host_group: "Discovered hosts" + register: update_action_host_group_again_result + + - assert: + that: + - update_action_host_group_again_result.changed is sameas false + + - name: test - Update action operation script to execute webhook with parameters + zabbix_script: + host_group: "Discovered hosts" + parameters: + - name: param_name1 + register: update_action_param_result + + - assert: + that: + - update_action_param_result.changed is sameas true + + - name: test - Update action operation script to execute webhook with parameters again + zabbix_script: + host_group: "Discovered hosts" + parameters: + - name: param_name1 + register: update_action_param_again_result + + - assert: + that: + - update_action_param_again_result.changed is sameas false + + - name: test - Update action operation script to execute webhook with parameters and value + zabbix_script: + host_group: "Discovered hosts" + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: update_action_param_value_result + + - assert: + that: + - update_action_param_value_result.changed is sameas true + + - name: test - Update action operation script to execute webhook with parameters and value again + zabbix_script: + host_group: "Discovered hosts" + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: update_action_param_value_again_result + + - assert: + that: + - update_action_param_value_again_result.changed is sameas false + + - name: test - Update action operation script remove host group + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: update_action_no_host_group_result + + - assert: + that: + - update_action_no_host_group_result.changed is sameas true + + - name: test - Update action operation script remove host group again + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: update_action_no_host_group_again_result + + - assert: + that: + - update_action_no_host_group_again_result.changed is sameas false + + - name: test - Update action operation script to type Script + zabbix_script: + script_type: script + execute_on: zabbix_agent + command: echo 1 + register: update_action_script_result + + - assert: + that: + - update_action_script_result.changed is sameas true + + - name: test - Update action operation script to type Script again + zabbix_script: + script_type: script + execute_on: zabbix_agent + command: echo 1 + register: update_action_script_again_result + + - assert: + that: + - update_action_script_again_result.changed is sameas false + + - name: test - Update action operation script to execute on server + zabbix_script: + script_type: script + execute_on: zabbix_server + command: echo 1 + register: update_action_script_server_result + + - assert: + that: + - update_action_script_server_result.changed is sameas true + + - name: test - Update action operation script to execute on server again + zabbix_script: + script_type: script + execute_on: zabbix_server + command: echo 1 + register: update_action_script_server_again_result + + - assert: + that: + - update_action_script_server_again_result.changed is sameas false + + - name: test - Update action operation script to execute on server or proxy + zabbix_script: + script_type: script + execute_on: zabbix_server_proxy + command: echo 1 + register: update_action_script_server_proxy_result + + - assert: + that: + - update_action_script_server_proxy_result.changed is sameas true + + - name: test - Update action operation script to execute on server or proxy again + zabbix_script: + script_type: script + execute_on: zabbix_server_proxy + command: echo 1 + register: update_action_script_server_proxy_again_result + + - assert: + that: + - update_action_script_server_proxy_again_result.changed is sameas false + + - name: test - Update action operation script to type SSH + zabbix_script: + script_type: ssh + authtype: password + username: bla + password: blabla + command: echo 2 + register: update_action_script_ssh_result + + - assert: + that: + - update_action_script_ssh_result.changed is sameas true + + - name: test - Update action operation script to type SSH again + zabbix_script: + script_type: ssh + authtype: password + username: bla + password: blabla + command: echo 2 + register: update_action_script_ssh_again_result + + - assert: + that: + - update_action_script_ssh_again_result.changed is sameas false + + - name: test - Update action operation script type SSH key auth + zabbix_script: + script_type: ssh + authtype: public_key + username: bla + publickey: blabla + privatekey: blablabla + command: echo 3 + register: update_action_script_ssh_authkey_result + + - assert: + that: + - update_action_script_ssh_authkey_result.changed is sameas true + + - name: test - Update action operation script type SSH key auth again + zabbix_script: + script_type: ssh + authtype: public_key + username: bla + publickey: blabla + privatekey: blablabla + command: echo 3 + register: update_action_script_ssh_authkey_again_result + + - assert: + that: + - update_action_script_ssh_authkey_again_result.changed is sameas false + + - name: test - Update action operation script type SSH add port + zabbix_script: + script_type: ssh + authtype: public_key + username: bla + publickey: blabla + privatekey: blablabla + command: echo 3 + port: 222 + register: update_action_script_ssh_port_result + + - assert: + that: + - update_action_script_ssh_port_result.changed is sameas true + + - name: test - Update action operation script type SSH add port again + zabbix_script: + script_type: ssh + authtype: public_key + username: bla + publickey: blabla + privatekey: blablabla + command: echo 3 + port: 222 + register: update_action_script_ssh_port_again_result + + - assert: + that: + - update_action_script_ssh_port_again_result.changed is sameas false + + - name: test - Update action operation script to type Telnet + zabbix_script: + script_type: telnet + username: bla1 + password: blabla1 + command: echo 4 + port: 223 + register: update_action_script_telnet_result + + - assert: + that: + - update_action_script_telnet_result.changed is sameas true + + - name: test - Update action operation script to type Telnet again + zabbix_script: + script_type: telnet + username: bla1 + password: blabla1 + command: echo 4 + port: 223 + register: update_action_script_telnet_again_result + + - assert: + that: + - update_action_script_telnet_again_result.changed is sameas false + + - name: test - Update action operation script to type IPMI + zabbix_script: + script_type: ipmi + command: echo 5 + register: update_action_script_ipmi_result + + - assert: + that: + - update_action_script_ipmi_result.changed is sameas true + + - name: test - Update action operation script to type IPMI again + zabbix_script: + script_type: ipmi + command: echo 5 + register: update_action_script_ipmi_again_result + + - assert: + that: + - update_action_script_ipmi_again_result.changed is sameas false + + - name: test - Delete action operation script + zabbix_script: + state: absent + register: delete_action_result + + - assert: + that: + - delete_action_result.changed is sameas true + + - name: test - Delete action operation script again + zabbix_script: + state: absent + register: delete_action_again_result + + - assert: + that: + - delete_action_again_result.changed is sameas false - name: test - Test manual host action script module_defaults: @@ -349,125 +345,125 @@ name: Test manual host action script scope: manual_host_action script_type: webhook - command: 'return 0' + command: "return 0" description: "Test manual host action script" state: present block: - - name: test - Create new manual host action script to execute webhook check mode - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - check_mode: true - register: create_action_check_mode_result - - - assert: - that: - - create_action_check_mode_result.changed is sameas true - - - name: test - Create new manual host action script to execute webhook - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: create_action_result - - - assert: - that: - - create_action_result.changed is sameas true - - - name: test - Create new manual host action script to execute webhook again - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: create_action_again_result - - - assert: - that: - - create_action_again_result.changed is sameas false - - - name: test - Update manual host action script with menu path - zabbix_script: - menu_path: menu/submenu - register: update_action_result - - - assert: - that: - - update_action_result.changed is sameas true - - - name: test - Update manual host action script with menu path again - zabbix_script: - menu_path: menu/submenu - register: update_action_again_result - - - assert: - that: - - update_action_again_result.changed is sameas false - - - name: test - Update manual host action script with user group - zabbix_script: - menu_path: menu/submenu - user_group: Guests - register: update_action_usrgrp_result - - - assert: - that: - - update_action_usrgrp_result.changed is sameas true - - - name: test - Update manual host action script with user group again - zabbix_script: - menu_path: menu/submenu - user_group: Guests - register: update_action_usrgrp_again_result - - - assert: - that: - - update_action_usrgrp_again_result.changed is sameas false - - - name: test - Update manual host action script with Write permissions - zabbix_script: - host_access: write - register: update_action_host_perms_result - - - assert: - that: - - update_action_host_perms_result.changed is sameas true - - - name: test - Update manual host action script with Write permissions again - zabbix_script: - host_access: write - register: update_action_host_perms_again_result - - - assert: - that: - - update_action_host_perms_again_result.changed is sameas false - - - name: test - Update manual host action script with confirmation - zabbix_script: - confirmation: 'Are you sure?' - register: update_action_host_confirm_result - - - assert: - that: - - update_action_host_confirm_result.changed is sameas true - - - name: test - Update manual host action script with confirmation again - zabbix_script: - confirmation: 'Are you sure?' - register: update_action_host_confirm_again_result - - - assert: - that: - - update_action_host_confirm_again_result.changed is sameas false - - - name: test - Delete manual host action script - zabbix_script: - state: absent + - name: test - Create new manual host action script to execute webhook check mode + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + check_mode: true + register: create_action_check_mode_result + + - assert: + that: + - create_action_check_mode_result.changed is sameas true + + - name: test - Create new manual host action script to execute webhook + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: create_action_result + + - assert: + that: + - create_action_result.changed is sameas true + + - name: test - Create new manual host action script to execute webhook again + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: create_action_again_result + + - assert: + that: + - create_action_again_result.changed is sameas false + + - name: test - Update manual host action script with menu path + zabbix_script: + menu_path: menu/submenu + register: update_action_result + + - assert: + that: + - update_action_result.changed is sameas true + + - name: test - Update manual host action script with menu path again + zabbix_script: + menu_path: menu/submenu + register: update_action_again_result + + - assert: + that: + - update_action_again_result.changed is sameas false + + - name: test - Update manual host action script with user group + zabbix_script: + menu_path: menu/submenu + user_group: Guests + register: update_action_usrgrp_result + + - assert: + that: + - update_action_usrgrp_result.changed is sameas true + + - name: test - Update manual host action script with user group again + zabbix_script: + menu_path: menu/submenu + user_group: Guests + register: update_action_usrgrp_again_result + + - assert: + that: + - update_action_usrgrp_again_result.changed is sameas false + + - name: test - Update manual host action script with Write permissions + zabbix_script: + host_access: write + register: update_action_host_perms_result + + - assert: + that: + - update_action_host_perms_result.changed is sameas true + + - name: test - Update manual host action script with Write permissions again + zabbix_script: + host_access: write + register: update_action_host_perms_again_result + + - assert: + that: + - update_action_host_perms_again_result.changed is sameas false + + - name: test - Update manual host action script with confirmation + zabbix_script: + confirmation: "Are you sure?" + register: update_action_host_confirm_result + + - assert: + that: + - update_action_host_confirm_result.changed is sameas true + + - name: test - Update manual host action script with confirmation again + zabbix_script: + confirmation: "Are you sure?" + register: update_action_host_confirm_again_result + + - assert: + that: + - update_action_host_confirm_again_result.changed is sameas false + + - name: test - Delete manual host action script + zabbix_script: + state: absent - name: test - Test manual event action script module_defaults: @@ -475,49 +471,49 @@ name: Test manual event action script scope: manual_event_action script_type: webhook - command: 'return 0' + command: "return 0" description: "Test manual event action script" state: present block: - - name: test - Create new manual event action script to execute webhook check mode - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - check_mode: true - register: create_action_check_mode_result - - - assert: - that: - - create_action_check_mode_result.changed is sameas true - - - name: test - Create new manual event action script to execute webhook - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - register: create_action_result - - - assert: - that: - - create_action_result.changed is sameas true - - - name: test - Create new manual event action script to execute webhook again - zabbix_script: - parameters: - - name: param_name1 - - name: param_name2 - value: value2 - diff: true - register: create_action_again_result - - - assert: - that: - - create_action_again_result.changed is sameas false - - - name: test - Delete manual host action script - zabbix_script: - state: absent + - name: test - Create new manual event action script to execute webhook check mode + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + check_mode: true + register: create_action_check_mode_result + + - assert: + that: + - create_action_check_mode_result.changed is sameas true + + - name: test - Create new manual event action script to execute webhook + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + register: create_action_result + + - assert: + that: + - create_action_result.changed is sameas true + + - name: test - Create new manual event action script to execute webhook again + zabbix_script: + parameters: + - name: param_name1 + - name: param_name2 + value: value2 + diff: true + register: create_action_again_result + + - assert: + that: + - create_action_again_result.changed is sameas false + + - name: test - Delete manual host action script + zabbix_script: + state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_service/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_service/tasks/main.yml index f4fc761b1..03501a43b 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_service/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_service/tasks/main.yml @@ -1,305 +1,5 @@ --- -- when: zabbix_version is version('6.0', '<') - module_defaults: - community.zabbix.zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.99 - sortorder: 0 - state: present - - block: - - name: "test - Create a new service with check_mode" - zabbix_service: - check_mode: true - register: create_service_check_mode_result - - - assert: - that: - - create_service_check_mode_result.changed is sameas true - - - name: "test - Create a new service" - zabbix_service: - register: create_service_result - - - assert: - that: - - create_service_result.changed is sameas true - - - name: "test - Create a new service (idempotency check)" - zabbix_service: - register: create_service_idempotency_check_result - - - assert: - that: - - create_service_idempotency_check_result.changed is sameas false - - - name: "test - Update a sla with check_mode" - zabbix_service: - sla: 99.999 - check_mode: true - register: update_sla_check_mode_result - - - assert: - that: - - update_sla_check_mode_result.changed is sameas true - - - name: "test - Update a sla" - zabbix_service: - sla: 99.999 - register: update_sla_result - - - assert: - that: - - update_sla_result.changed is sameas true - - - name: "test - Update a sla (idempotency check)" - zabbix_service: - sla: 99.999 - register: update_sla_idempotency_check_result - - - assert: - that: - - update_sla_idempotency_check_result.changed is sameas false - - - name: "test - Update a calculate_sla with check_mode" - zabbix_service: - sla: 99.999 - calculate_sla: true - check_mode: true - register: update_calculate_sla_check_mode_result - - - assert: - that: - - update_calculate_sla_check_mode_result.changed is sameas true - - - name: "test - Update a calculate_sla" - zabbix_service: - sla: 99.999 - calculate_sla: true - register: update_calculate_sla_result - - - assert: - that: - - update_calculate_sla_result.changed is sameas true - - - name: "test - Update a calculate_sla (idempotency check)" - zabbix_service: - sla: 99.999 - calculate_sla: true - register: update_calculate_sla_idempotency_check_result - - - assert: - that: - - update_calculate_sla_idempotency_check_result.changed is sameas false - - - name: "Override trigger_name for different version of Zabbix" - set_fact: - service_example_trigger: "Zabbix server: Utilization of http poller processes over 75%" - when: zabbix_version is version("5.0", "==") - - - name: "test - Update trigger_host and trigger_name with check_mode" - zabbix_service: - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - check_mode: true - register: update_trigger_name_check_mode_result - - - assert: - that: - - update_trigger_name_check_mode_result.changed is sameas true - - - name: "test - Update trigger_host and trigger_name" - zabbix_service: - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - register: update_trigger_name_result - - - assert: - that: - - update_trigger_name_result.changed is sameas true - - - name: "test - Update trigger_host and trigger_name (idempotency check)" - zabbix_service: - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - register: update_trigger_name_idempotency_check_result - - - assert: - that: - - update_trigger_name_idempotency_check_result.changed is sameas false - - - name: "test - Update a algorithm of service with check_mode" - zabbix_service: - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - algorithm: all_children - check_mode: true - register: update_algorithm_check_mode_result - - - assert: - that: - - update_algorithm_check_mode_result.changed is sameas true - - - name: "test - Update a algorithm of service" - zabbix_service: - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - algorithm: all_children - register: update_algorithm_result - - - assert: - that: - - update_algorithm_result.changed is sameas true - - - name: "test - Update a algorithm of service (idempotency check)" - zabbix_service: - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - algorithm: all_children - register: update_algorithm_idempotency_check_result - - - assert: - that: - - update_algorithm_idempotency_check_result.changed is sameas false - - - name: "test - Create a new root service for parent test" - zabbix_service: - name: ExampleServiceForServiceModuleRoot - sla: 99.99 - register: create_child_service_result - - - assert: - that: - - create_child_service_result.changed is sameas true - - - name: "test - Update a parent of child service with check_mode" - zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - algorithm: all_children - parent: ExampleServiceForServiceModuleRoot - check_mode: true - register: create_parent_child_service_check_mode_result - - - assert: - that: - - create_parent_child_service_check_mode_result.changed is sameas true - - - name: "test - Update a parent of child service" - zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - algorithm: all_children - parent: ExampleServiceForServiceModuleRoot - register: create_parent_child_service_result - - - assert: - that: - - create_parent_child_service_result.changed is sameas true - - - name: "test - Update a parent of child service (idempotency check)" - zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.999 - calculate_sla: true - trigger_host: "Zabbix server" - trigger_name: "{{ service_example_trigger }}" - algorithm: all_children - parent: ExampleServiceForServiceModuleRoot - register: create_parent_child_service_idempotency_check_result - - - assert: - that: - - create_parent_child_service_idempotency_check_result.changed is sameas false - - - name: "test - Remove ExampleServiceForServiceModule service with check_mode" - zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.999 - state: absent - check_mode: true - register: remove_service_with_check_mode_result - - - assert: - that: - - remove_service_with_check_mode_result.changed is sameas true - - - name: "test - Remove ExampleServiceForServiceModule service" - zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.999 - state: absent - register: remove_service_result - - - assert: - that: - - remove_service_result.changed is sameas true - - - name: "test - Remove ExampleServiceForServiceModule service (idempotency check)" - zabbix_service: - name: ExampleServiceForServiceModule - sla: 99.999 - state: absent - register: remove_service_idempotency_check_result - - - assert: - that: - - remove_service_idempotency_check_result.changed is sameas false - - - name: "test - Remove ExampleServiceForServiceModuleRoot service with check_mode" - zabbix_service: - name: ExampleServiceForServiceModuleRoot - sla: 99.999 - state: absent - check_mode: true - register: remove_root_service_with_check_mode_result - - - assert: - that: - - remove_root_service_with_check_mode_result.changed is sameas true - - - name: "test - Remove ExampleServiceForServiceModuleRoot service" - zabbix_service: - name: ExampleServiceForServiceModuleRoot - sla: 99.999 - state: absent - register: remove_root_service_result - - - assert: - that: - - remove_root_service_result.changed is sameas true - - - name: "test - Remove ExampleServiceForServiceModuleRoot service (idempotency check)" - zabbix_service: - name: ExampleServiceForServiceModuleRoot - sla: 99.999 - state: absent - register: remove_root_service_idempotency_check_result - - - assert: - that: - - remove_root_service_idempotency_check_result.changed is sameas false - -- name: test - service for Zabbix >= 6.0 - when: zabbix_version is version('6.0', '>=') +- name: test - service module_defaults: community.zabbix.zabbix_service: description: "Example Service for Service Module" @@ -310,59 +10,59 @@ block: - name: "test - Create a new service with check_mode" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule check_mode: true register: create_service_check_mode_result - - assert: + - ansible.builtin.assert: that: - create_service_check_mode_result.changed is sameas true - name: "test - Create a new service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule register: create_service_result - - assert: + - ansible.builtin.assert: that: - create_service_result.changed is sameas true - name: "test - Create a new service (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule register: create_service_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - create_service_idempotency_check_result.changed is sameas false - name: "test - Update service add service tags" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule tags: - tag: TagName1 value: TagValue1 register: update_service_stags_result - - assert: + - ansible.builtin.assert: that: - update_service_stags_result.changed is sameas true - name: "test - Update service with service tags (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule tags: - tag: TagName1 value: TagValue1 register: update_service_stags_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_stags_idempotency_check_result.changed is sameas false - name: "test - Update service add more service tags" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule tags: - tag: TagName1 @@ -371,12 +71,12 @@ value: TagValue2 register: update_service_more_stags_result - - assert: + - ansible.builtin.assert: that: - update_service_more_stags_result.changed is sameas true - name: "test - Update service add more service tags (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule tags: - tag: TagName1 @@ -385,41 +85,41 @@ value: TagValue2 register: update_service_more_stags_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_more_stags_idempotency_check_result.changed is sameas false - name: "test - Update service remove service tags" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule tags: - tag: TagName2 value: TagValue2 register: update_service_less_stags_result - - assert: + - ansible.builtin.assert: that: - update_service_less_stags_result.changed is sameas true - name: "test - Update service remove service tags (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule tags: - tag: TagName2 value: TagValue2 register: update_service_less_stags_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_less_stags_idempotency_check_result.changed is sameas false - name: "test - Delete service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule state: absent - name: "test - Create service with one problem tag" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -427,12 +127,12 @@ value: TagValue1 register: create_service_with_ptag_result - - assert: + - ansible.builtin.assert: that: - create_service_with_ptag_result.changed is sameas true - name: "test - Create service with one problem tag (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -441,7 +141,7 @@ register: create_service_with_ptag_idempotency_check_result - name: "test - Update service with problem tag without operator" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -451,12 +151,12 @@ value: TagValue2 register: update_service_with_ptag_woop_result - - assert: + - ansible.builtin.assert: that: - update_service_with_ptag_woop_result.changed is sameas true - name: "test - Update service with problem tag without operator (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -466,12 +166,12 @@ value: TagValue2 register: update_service_with_ptag_woop_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_with_ptag_woop_idempotency_check_result.changed is sameas false - name: "test - Update service with problem tag with like operator" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -484,12 +184,12 @@ value: TagValue3 register: update_service_with_ptag_wlikeop_result - - assert: + - ansible.builtin.assert: that: - update_service_with_ptag_wlikeop_result.changed is sameas true - name: "test - Update service with problem tag with like operator (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -502,12 +202,12 @@ value: TagValue3 register: update_service_with_ptag_wlikeop_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_with_ptag_wlikeop_idempotency_check_result.changed is sameas false - name: "test - Update service with problem tag without operator and without value" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -521,12 +221,12 @@ - tag: TagName4 register: update_service_with_ptag_woov_result - - assert: + - ansible.builtin.assert: that: - update_service_with_ptag_woov_result.changed is sameas true - name: "test - Update service with problem tag without operator and without value (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -540,12 +240,12 @@ - tag: TagName4 register: update_service_with_ptag_woov_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_with_ptag_woov_idempotency_check_result.changed is sameas false - name: "test - Update service remove problem tags" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -556,12 +256,12 @@ value: TagValue3 register: update_service_remove_tags_result - - assert: + - ansible.builtin.assert: that: - update_service_remove_tags_result.changed is sameas true - name: "test - Update service remove problem tags (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule problem_tags: - tag: TagName1 @@ -572,237 +272,237 @@ value: TagValue3 register: update_service_remove_tags_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_remove_tags_idempotency_check_result.changed is sameas false - name: "test - Update service remove all problem tags" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule register: update_service_remove_all_tags_result - - assert: + - ansible.builtin.assert: that: - update_service_remove_all_tags_result.changed is sameas true - name: "test - Update service remove all problem tags (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule register: update_service_remove_all_tags_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_remove_all_tags_idempotency_check_result.changed is sameas false - name: "test - Create a new child service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule sortorder: 10 parents: - ExampleServiceForServiceModule register: create_child_service_result - - assert: + - ansible.builtin.assert: that: - create_child_service_result.changed is sameas true - name: "test - Create a new child service (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule sortorder: 10 parents: - ExampleServiceForServiceModule register: create_child_service_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - create_child_service_idempotency_check_result.changed is sameas false - name: "test - Update child service to remove parent" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule parents: [] register: update_child_service_delete_parent_result - - assert: + - ansible.builtin.assert: that: - update_child_service_delete_parent_result.changed is sameas true - name: "test - Create a new parent service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule - name: "test - Delete child service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule state: absent - name: "test - Create a new child service with two parents" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule parents: - ExampleServiceForServiceModule - ExampleParentServiceForServiceModule register: create_child_service_two_parents_result - - assert: + - ansible.builtin.assert: that: - create_child_service_two_parents_result.changed is sameas true - name: "test - Create a new child service with two parents (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule parents: - ExampleServiceForServiceModule - ExampleParentServiceForServiceModule register: create_child_service_two_parents_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - create_child_service_two_parents_idempotency_check_result.changed is sameas false - name: "test - Remove one parent from new child service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule parents: - ExampleParentServiceForServiceModule register: update_child_service_remove_parent_result - - assert: + - ansible.builtin.assert: that: - update_child_service_remove_parent_result.changed is sameas true - name: "test - Remove one parent from new child service (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule parents: - ExampleParentServiceForServiceModule register: update_child_service_remove_parent_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_child_service_remove_parent_idempotency_check_result.changed is sameas false - name: "test - Delete parent service 2" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule state: absent - name: "test - Create parent service with child service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule children: - ExampleChildServiceForServiceModule register: create_parent_service_with_child_result - - assert: + - ansible.builtin.assert: that: - create_parent_service_with_child_result.changed is sameas true - name: "test - Create parent service with child service (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule children: - ExampleChildServiceForServiceModule register: create_parent_service_with_child_result_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - create_parent_service_with_child_result_idempotency_check_result.changed is sameas false - name: "test - Create second chile service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule2 - name: "test - Update parent service with the second child service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule children: - ExampleChildServiceForServiceModule - ExampleChildServiceForServiceModule2 register: update_parent_service_with_second_child_result - - assert: + - ansible.builtin.assert: that: - update_parent_service_with_second_child_result.changed is sameas true - name: "test - Update parent service with the second child service (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule children: - ExampleChildServiceForServiceModule - ExampleChildServiceForServiceModule2 register: update_parent_service_with_second_child_result_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_parent_service_with_second_child_result_idempotency_check_result.changed is sameas false - name: "test - Delete parent service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule state: absent - name: "test - Create parent service with two child services" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule children: - ExampleChildServiceForServiceModule - ExampleChildServiceForServiceModule2 register: create_parent_service_with_two_children_result - - assert: + - ansible.builtin.assert: that: - create_parent_service_with_two_children_result.changed is sameas true - name: "test - Create parent service with child services (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule children: - ExampleChildServiceForServiceModule - ExampleChildServiceForServiceModule2 register: create_parent_service_with_two_children_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - create_parent_service_with_two_children_idempotency_check_result.changed is sameas false - name: "test - Delete parent service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleParentServiceForServiceModule state: absent - name: "test - Delete child service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule state: absent - name: "test - Delete child servicei 2" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleChildServiceForServiceModule2 state: absent - name: "test - Delete new service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule state: absent register: delete_service_result - - assert: + - ansible.builtin.assert: that: - delete_service_result.changed is sameas true - name: "test - Delete new service (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule state: absent register: delete_service_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - delete_service_idempotency_check_result.changed is sameas false - name: "test - Create a new service with status rule" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule status_rules: - type: at_least_n_child_services_have_status_or_above @@ -811,12 +511,12 @@ new_status: not_classified register: create_service_sr_result - - assert: + - ansible.builtin.assert: that: - create_service_sr_result.changed is sameas true - name: "test - Create a new service with status rule (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule status_rules: - type: at_least_n_child_services_have_status_or_above @@ -825,12 +525,12 @@ new_status: not_classified register: create_service_sr_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - create_service_sr_idempotency_check_result.changed is sameas false - name: "test - Update service with the second status rule" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule status_rules: - type: at_least_n_child_services_have_status_or_above @@ -843,12 +543,12 @@ new_status: warning register: update_service_add_sr_result - - assert: + - ansible.builtin.assert: that: - update_service_add_sr_result.changed is sameas true - name: "test - Update service with the second status rule (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule status_rules: - type: at_least_n_child_services_have_status_or_above @@ -861,12 +561,12 @@ new_status: warning register: update_service_add_sr_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_add_sr_idempotency_check_result.changed is sameas false - name: "test - Update service remove status rule" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule status_rules: - type: at_least_npct_child_services_have_status_or_above @@ -875,12 +575,12 @@ new_status: warning register: update_service_remove_sr_result - - assert: + - ansible.builtin.assert: that: - update_service_remove_sr_result.changed is sameas true - name: "test - Update service remove status rule (idempotency check)" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule status_rules: - type: at_least_npct_child_services_have_status_or_above @@ -889,12 +589,12 @@ new_status: warning register: update_service_remove_sr_idempotency_check_result - - assert: + - ansible.builtin.assert: that: - update_service_remove_sr_idempotency_check_result.changed is sameas false - name: "test - Delete new service" - zabbix_service: + community.zabbix.zabbix_service: name: ExampleServiceForServiceModule state: absent register: delete_service_result diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_settings/meta/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_settings/meta/main.yml new file mode 100644 index 000000000..acdb704c8 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_settings/meta/main.yml @@ -0,0 +1,3 @@ +--- +dependencies: + - setup_zabbix diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_settings/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_settings/tasks/main.yml new file mode 100644 index 000000000..7be88158e --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_settings/tasks/main.yml @@ -0,0 +1,332 @@ +--- +- name: test - Update zabbix settings (same as default) + community.zabbix.zabbix_settings: + alert_usrgrp: "Zabbix administrators" + auditlog_enabled: true + blink_period: "2m" + connect_timeout: "3s" + custom_color: false + default_inventory_mode: disabled + default_lang: en_US + default_theme: blue-theme + default_timezone: system + discovery_group: "Discovered hosts" + geomaps_attribution: "" + geomaps_max_zoom: false + geomaps_tile_provider: "OpenStreetMap.Mapnik" + geomaps_tile_url: "" + history_period: "24h" + iframe_sandboxing_enabled: true + iframe_sandboxing_exceptions: "" + item_test_timeout: "60s" + login_attempts: 5 + login_block: "30s" + max_in_table: 50 + max_overview_table_size: 50 + max_period: "2y" + media_type_test_timeout: "65s" + ok_ack_color: "009900" + ok_ack_style: true + ok_period: "5m" + ok_unack_color: "009900" + ok_unack_style: true + period_default: "1h" + problem_ack_color: "CC0000" + problem_ack_style: true + problem_unack_color: "CC0000" + problem_unack_style: true + report_test_timeout: "60s" + script_timeout: "60s" + search_limit: 1000 + server_check_interval: true + severity_color_0: "97AAB3" + severity_color_1: "7499FF" + severity_color_2: "FFC859" + severity_color_3: "FFA059" + severity_color_4: "E97659" + severity_color_5: "E45959" + severity_name_0: "Not classified" + severity_name_1: "Information" + severity_name_2: "Warning" + severity_name_3: "Average" + severity_name_4: "High" + severity_name_5: "Disaster" + show_technical_errors: false + snmptrap_logging: true + socket_timeout: "3s" + uri_valid_schemes: + - http + - https + - ftp + - file + - mailto + - tel + - ssh + frontend_url: "" + validate_uri_schemes: true + work_period: "1-5,09:00-18:00" + x_frame_options: "SAMEORIGIN" + register: zbx_settings + +- name: assert that settings was NOT updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas False + +- when: zabbix_version is version('6.2', '>=') + name: support Zabbix version (>=6.2) + block: + - name: test - Zabbix settings (same as default) + community.zabbix.zabbix_settings: + vault_provider: HashiCorp_Vault + register: zbx_settings + + - name: assert that settings was NOT updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas False + + - name: test - Update zabbix settings + community.zabbix.zabbix_settings: + vault_provider: CyberArk_Vault + register: zbx_settings + + - name: assert that settings was updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas True + +- name: test - Update zabbix settings + community.zabbix.zabbix_settings: + alert_usrgrp: "0" + auditlog_enabled: false + blink_period: "10m" + connect_timeout: "30s" + custom_color: false + default_inventory_mode: automatic + default_lang: en_GB + default_theme: hc-dark + default_timezone: Asia/Tokyo + discovery_group: "Hypervisors" + geomaps_attribution: "hogehoge" + geomaps_max_zoom: true + geomaps_tile_provider: "another" + geomaps_tile_url: "" + history_period: "1w" + iframe_sandboxing_enabled: false + iframe_sandboxing_exceptions: "hogehoge" + item_test_timeout: "5m" + login_attempts: 30 + login_block: "5m" + max_in_table: 1000 + max_overview_table_size: 1000 + max_period: "1y" + media_type_test_timeout: "1m" + ok_ack_color: "0099AA" + ok_ack_style: false + ok_period: "10m" + ok_unack_color: "0099BB" + ok_unack_style: false + period_default: "2h" + problem_ack_color: "CC0000" + problem_ack_style: false + problem_unack_color: "CC0000" + problem_unack_style: false + report_test_timeout: "2m" + script_timeout: "2m" + search_limit: 10000 + server_check_interval: false + severity_color_0: "97AAAA" + severity_color_1: "7499BB" + severity_color_2: "FFC8CC" + severity_color_3: "FFA0DD" + severity_color_4: "E976EE" + severity_color_5: "E459FF" + severity_name_0: "Not classified(test)" + severity_name_1: "Information(test)" + severity_name_2: "Warning(test)" + severity_name_3: "Average(test)" + severity_name_4: "High(test)" + severity_name_5: "Disaster(test)" + show_technical_errors: true + snmptrap_logging: false + socket_timeout: "30s" + uri_valid_schemes: + - https + - ftp + - file + - mailto + - tel + - ssh + frontend_url: "https://www.zabbix.com/" + validate_uri_schemes: false + work_period: "1-5,09:00-18:00;1-5,22:00-23:00" + x_frame_options: "SAMEORIGIN(TEST)" + register: zbx_settings + +- name: assert that settings was updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas True + +- name: test - Update zabbix settings (same setting) + community.zabbix.zabbix_settings: + alert_usrgrp: "0" + auditlog_enabled: false + blink_period: "10m" + connect_timeout: "30s" + custom_color: false + default_inventory_mode: automatic + default_lang: en_GB + default_theme: hc-dark + default_timezone: Asia/Tokyo + discovery_group: "Hypervisors" + geomaps_attribution: "hogehoge" + geomaps_max_zoom: true + geomaps_tile_provider: "another" + geomaps_tile_url: "" + history_period: "1w" + iframe_sandboxing_enabled: false + iframe_sandboxing_exceptions: "hogehoge" + item_test_timeout: "5m" + login_attempts: 30 + login_block: "5m" + max_in_table: 1000 + max_overview_table_size: 1000 + max_period: "1y" + media_type_test_timeout: "1m" + ok_ack_color: "0099AA" + ok_ack_style: false + ok_period: "10m" + ok_unack_color: "0099BB" + ok_unack_style: false + period_default: "2h" + problem_ack_color: "CC0000" + problem_ack_style: false + problem_unack_color: "CC0000" + problem_unack_style: false + report_test_timeout: "2m" + script_timeout: "2m" + search_limit: 10000 + server_check_interval: false + severity_color_0: "97AAAA" + severity_color_1: "7499BB" + severity_color_2: "FFC8CC" + severity_color_3: "FFA0DD" + severity_color_4: "E976EE" + severity_color_5: "E459FF" + severity_name_0: "Not classified(test)" + severity_name_1: "Information(test)" + severity_name_2: "Warning(test)" + severity_name_3: "Average(test)" + severity_name_4: "High(test)" + severity_name_5: "Disaster(test)" + show_technical_errors: true + snmptrap_logging: false + socket_timeout: "30s" + uri_valid_schemes: + - https + - ftp + - file + - mailto + - tel + - ssh + frontend_url: "https://www.zabbix.com/" + validate_uri_schemes: false + work_period: "1-5,09:00-18:00;1-5,22:00-23:00" + x_frame_options: "SAMEORIGIN(TEST)" + register: zbx_settings + +- name: assert that settings was NOT updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas False + +- name: test - Update zabbix alert_usrgrp setting + community.zabbix.zabbix_settings: + alert_usrgrp: "No access to the frontend" + register: zbx_settings + +- name: assert that setting was updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas True + +- name: test - Update zabbix alert_usrgrp setting (same parameter) + community.zabbix.zabbix_settings: + alert_usrgrp: "No access to the frontend" + register: zbx_settings + +- name: assert that settings was NOT updated + ansible.builtin.assert: + that: + - zbx_settings.changed is sameas False + +- name: test - Update zabbix settings (same as default) + community.zabbix.zabbix_settings: + alert_usrgrp: "Zabbix administrators" + auditlog_enabled: true + blink_period: "2m" + connect_timeout: "3s" + custom_color: false + default_inventory_mode: disabled + default_lang: en_US + default_theme: blue-theme + default_timezone: system + discovery_group: "Discovered hosts" + geomaps_attribution: "" + geomaps_max_zoom: false + geomaps_tile_provider: "OpenStreetMap.Mapnik" + geomaps_tile_url: "" + history_period: "24h" + iframe_sandboxing_enabled: true + iframe_sandboxing_exceptions: "" + item_test_timeout: "60s" + login_attempts: 5 + login_block: "30s" + max_in_table: 50 + max_overview_table_size: 50 + max_period: "2y" + media_type_test_timeout: "65s" + ok_ack_color: "009900" + ok_ack_style: true + ok_period: "5m" + ok_unack_color: "009900" + ok_unack_style: true + period_default: "1h" + problem_ack_color: "CC0000" + problem_ack_style: true + problem_unack_color: "CC0000" + problem_unack_style: true + report_test_timeout: "60s" + script_timeout: "60s" + search_limit: 1000 + server_check_interval: true + severity_color_0: "97AAB3" + severity_color_1: "7499FF" + severity_color_2: "FFC859" + severity_color_3: "FFA059" + severity_color_4: "E97659" + severity_color_5: "E45959" + severity_name_0: "Not classified" + severity_name_1: "Information" + severity_name_2: "Warning" + severity_name_3: "Average" + severity_name_4: "High" + severity_name_5: "Disaster" + show_technical_errors: false + snmptrap_logging: true + socket_timeout: "3s" + uri_valid_schemes: + - http + - https + - ftp + - file + - mailto + - tel + - ssh + frontend_url: "" + validate_uri_schemes: true + work_period: "1-5,09:00-18:00" + x_frame_options: "SAMEORIGIN" + register: zbx_settings diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/files/template2_50_lower.xml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/files/template2_50_lower.xml deleted file mode 100644 index 93a32f0c5..000000000 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/files/template2_50_lower.xml +++ /dev/null @@ -1,53 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<zabbix_export> - <date>2020-05-29T15:22:11Z</date> - <templates> - <template> - <template>ExampleHost</template> - <name>ExampleHost</name> - <description></description> - <groups> - <group> - <name>Templates</name> - </group> - <group> - <name>Templates/Applications</name> - </group> - </groups> - <macros> - <macro> - <macro>{$EXAMPLE_MACRO1}</macro> - <value>1000</value> - </macro> - <macro> - <macro>{$EXAMPLE_MACRO2}</macro> - <value>text</value> - </macro> - <macro> - <macro>{$EXAMPLE_MACRO3}</macro> - <value>text2</value> - </macro> - </macros> - <templates> - <template> - <name>Template App FTP Service</name> - </template> - <template> - <name>Template App Zabbix Proxy</name> - </template> - <template> - <name>Template App HTTP Service</name> - </template> - </templates> - </template> - </templates> - <version>3.0</version> - <groups> - <group> - <name>Templates</name> - </group> - <group> - <name>Templates/Applications</name> - </group> - </groups> -</zabbix_export> diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/import_54_higher.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/import_54_higher.yml deleted file mode 100644 index 8ce7a51e1..000000000 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/import_54_higher.yml +++ /dev/null @@ -1,126 +0,0 @@ ---- - -# -# For Zabbix lower than 5.4 we test against the ExampleHost which was created in the -# main.yml tests. Due to changes in the Zabbix API (mainly because UUIDs) this is -# not possible for 5.4 onwards - so there we first delete the example hosts. -# - -- name: Delete Zabbix template. - zabbix_template: - template_name: ExampleHost - state: absent - register: delete_zabbix_template_result - -- assert: - that: - - delete_zabbix_template_result.changed is sameas true - -- name: Delete Zabbix template (idempotency check). - zabbix_template: - template_name: ExampleHost - state: absent - register: delete_zabbix_template_result - -- assert: - that: - - delete_zabbix_template_result.changed is sameas false - -# -# JSON Tests -# - -- block: - - name: Import Zabbix template from JSON file (idempotency check) - >= Zabbix 5.4. - zabbix_template: - template_json: "{{ lookup('file', 'template3_54_higher.json') }}" - state: present - register: import_template_json - - - name: Assert Zabbix template from JSON file (idempotency check) - >= Zabbix 5.4. - assert: - that: - - import_template_json.changed is sameas true - - - name: Import Zabbix template from JSON file with matching values (idempotency check) - >= Zabbix 5.4. - zabbix_template: - template_json: "{{ lookup('file', 'template3_54_higher.json') }}" - state: present - register: import_template_json - - - name: Assert Zabbix template from JSON file with matching values (idempotency check) - >= Zabbix 5.4. - assert: - that: - - import_template_json.changed is sameas false - -- name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleHost - format: json - register: gather_template_result - -- block: - - assert: - that: - - gather_template_result.template_json[template_export_key][template_groups_key].0.name == 'Templates' - - gather_template_result.template_json[template_export_key][template_groups_key].1.name == 'Templates/Applications' - - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'FTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Zabbix proxy health' - - gather_template_result.template_json[template_export_key].templates.0.macros.0.macro == '{$EXAMPLE_MACRO1}' - - gather_template_result.template_json[template_export_key].templates.0.macros.0.value == '1000' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.macro == '{$EXAMPLE_MACRO2}' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.value == 'text' - -- block: - - name: Import Zabbix template from JSON file with updated values. - zabbix_template: - template_json: "{{ lookup('file', 'template3-changed_54_higher.json') }}" - state: present - register: import_template_json - - - assert: - that: - - import_template_json.changed is sameas true - -- name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleHost - format: json - register: gather_template_result - -- assert: - that: - - gather_template_result.template_json[template_export_key].templates.0.macros.0.macro == '{$EXAMPLE_MACRO1}' - - gather_template_result.template_json[template_export_key].templates.0.macros.0.value == '1000' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.macro == '{$EXAMPLE_MACRO2}' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.value == 'text' - - gather_template_result.template_json[template_export_key].templates.0.macros.2.macro == '{$EXAMPLE_MACRO3}' - - gather_template_result.template_json[template_export_key].templates.0.macros.2.value == 'text2' - -# -# xml -# - -- block: - - name: Import Zabbix template from XML file with updated values. - zabbix_template: - template_xml: "{{ lookup('file', 'template3_54_higher.xml') }}" - state: present - register: import_template_xml - - - assert: - that: - - import_template_xml.changed is sameas true - -- name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleHost - format: json - register: gather_template_result - -# zabbix returns values sorted alphabetically so HTTP Service template comes before Zabbix Proxy template -- block: - - assert: - that: - - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'FTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Zabbix proxy health' diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/import_54_lower.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/import_54_lower.yml deleted file mode 100644 index 48d180210..000000000 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/import_54_lower.yml +++ /dev/null @@ -1,120 +0,0 @@ ---- - -# -# For Zabbix lower than 5.4 we test against the ExampleHost which was created in the -# main.yml tests. Due to changes in the Zabbix API (mainly because UUIDs) this is -# not possible for 5.4 onwards - so there we first delete the Example host. -# - -# -# JSON Tests -# - -- name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleHost - format: json - register: gather_template_result - -- block: - - assert: - that: - - gather_template_result.template_json[template_export_key].groups.0.name == 'Templates' - - gather_template_result.template_json[template_export_key].groups.1.name == 'Templates/Applications' - - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'Template App FTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Template App Zabbix Proxy' - - gather_template_result.template_json[template_export_key].templates.0.macros.0.macro == '{$EXAMPLE_MACRO1}' - - gather_template_result.template_json[template_export_key].templates.0.macros.0.value == '1000' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.macro == '{$EXAMPLE_MACRO2}' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.value == 'text' - -- block: - - name: Import Zabbix template from JSON file with matching values (idempotency check) - < Zabbix 5.4. - zabbix_template: - template_json: "{{ lookup('file', 'template1_50_lower.json') }}" - state: present - register: import_template_json - - - name: Assert Zabbix template from JSON file with matching values (idempotency check) - < Zabbix 5.4. - assert: - that: - - import_template_json.changed is sameas false - -- block: - - name: Import Zabbix template from JSON file with updated values. - zabbix_template: - template_json: "{{ lookup('file', 'template1-changed_50_lower.json') }}" - state: present - register: import_template_json - - - assert: - that: - - import_template_json.changed is sameas true - -- name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleHost - format: json - register: gather_template_result - -- assert: - that: - - gather_template_result.template_json[template_export_key].templates.0.macros.0.macro == '{$EXAMPLE_MACRO1}' - - gather_template_result.template_json[template_export_key].templates.0.macros.0.value == '1000' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.macro == '{$EXAMPLE_MACRO2}' - - gather_template_result.template_json[template_export_key].templates.0.macros.1.value == 'text' - - gather_template_result.template_json[template_export_key].templates.0.macros.2.macro == '{$EXAMPLE_MACRO3}' - - gather_template_result.template_json[template_export_key].templates.0.macros.2.value == 'text2' - -- name: Dump Zabbix template to JSON format. - zabbix_template: - template_name: ExampleHost - dump_format: json - state: dump - register: template_dump_result - -- assert: - that: - - template_dump_result.deprecations is defined - - template_dump_result.deprecations.0.version == '3.0.0' - -# -# XML Tests -# - -- block: - - name: Import Zabbix template from XML file with updated values. - zabbix_template: - template_xml: "{{ lookup('file', 'template2_50_lower.xml') }}" - state: present - register: import_template_xml - - - assert: - that: - - import_template_xml.changed is sameas true - -- name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleHost - format: json - register: gather_template_result - -# zabbix returns values sorted alphabetically so HTTP Service template comes before Zabbix Proxy template -- block: - - assert: - that: - - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'Template App FTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Template App HTTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.2.name == 'Template App Zabbix Proxy' - -- name: Dump Zabbix template to XML format. - zabbix_template: - template_name: ExampleHost - dump_format: xml - state: dump - register: template_dump_result - -- assert: - that: - - template_dump_result.deprecations is defined - - template_dump_result.deprecations.0.version == '3.0.0' diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/main.yml index 66505f9a7..69aabe6b0 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template/tasks/main.yml @@ -1,197 +1,186 @@ --- - name: Create FTP Service Template - zabbix_template: + community.zabbix.zabbix_template: template_name: FTP Service template_groups: - - 'Templates' + - "Templates" state: present - name: Create a new Zabbix template (check mode). - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" state: present register: create_zabbix_template_result check_mode: true -- assert: +- ansible.builtin.assert: that: - create_zabbix_template_result.changed is sameas true - name: Create a new Zabbix template. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" state: present register: create_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - create_zabbix_template_result.changed is sameas true - name: Create a new Zabbix template (idempotency check). - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" state: present register: create_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - create_zabbix_template_result.changed is sameas false - name: Create a new Zabbix template with linked templates. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHostWithLinked template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" state: present register: create_zabbix_template_linked_result -- assert: +- ansible.builtin.assert: that: - create_zabbix_template_linked_result.changed is sameas true - name: Gather Zabbix template infomation. - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleHost format: json register: gather_template_result - name: "test - Set key to template_export_key variable(This deals with the key being masked)" - set_fact: + ansible.builtin.set_fact: template_export_key: "{{ item }}" loop: "{{ gather_template_result.template_json.keys() | list }}" when: - item | regex_search('_export') -- assert: +- ansible.builtin.assert: that: - gather_template_result.template_json[template_export_key][template_groups_key].0.name == 'Templates' - gather_template_result.template_json[template_export_key][template_groups_key].1.name == 'Templates/Applications' - name: Add link_templates to Zabbix template. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" state: present register: update_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - update_zabbix_template_result.changed is sameas true - name: Add link_templates to Zabbix template (idempotency check). - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" state: present register: update_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - update_zabbix_template_result.changed is sameas false - name: Gather Zabbix template infomation. - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleHost format: json register: gather_template_result -- when: zabbix_version is version('5.4', '<') - block: - - assert: - that: - - gather_template_result.template_json[template_export_key].groups.0.name == 'Templates' - - gather_template_result.template_json[template_export_key].groups.1.name == 'Templates/Applications' - - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'Template App FTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Template App Zabbix Proxy' - -- when: zabbix_version is version('5.4', '>=') - block: - - assert: - that: - - gather_template_result.template_json[template_export_key][template_groups_key].0.name == 'Templates' - - gather_template_result.template_json[template_export_key][template_groups_key].1.name == 'Templates/Applications' - - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'FTP Service' - - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Zabbix proxy health' +- ansible.builtin.assert: + that: + - gather_template_result.template_json[template_export_key][template_groups_key].0.name == 'Templates' + - gather_template_result.template_json[template_export_key][template_groups_key].1.name == 'Templates/Applications' + - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'FTP Service' + - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Zabbix proxy health' - name: Add macros to Zabbix template. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" macros: - - macro: '{$EXAMPLE_MACRO1}' + - macro: "{$EXAMPLE_MACRO1}" value: 1000 - - macro: '{$EXAMPLE_MACRO2}' - value: 'text' + - macro: "{$EXAMPLE_MACRO2}" + value: "text" state: present register: update_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - update_zabbix_template_result.changed is sameas true - name: Add macros to Zabbix template (idempotency check). - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" macros: - - macro: '{$EXAMPLE_MACRO1}' + - macro: "{$EXAMPLE_MACRO1}" value: 1000 - - macro: '{$EXAMPLE_MACRO2}' - value: 'text' + - macro: "{$EXAMPLE_MACRO2}" + value: "text" state: present register: update_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - update_zabbix_template_result.changed is sameas false - name: Add tags to Zabbix template. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" macros: - - macro: '{$EXAMPLE_MACRO1}' + - macro: "{$EXAMPLE_MACRO1}" value: 1000 - - macro: '{$EXAMPLE_MACRO2}' - value: 'text' + - macro: "{$EXAMPLE_MACRO2}" + value: "text" tags: - tag: tag1 value: 1000 @@ -199,26 +188,24 @@ value: text state: present register: update_zabbix_template_result - when: zabbix_version is version('4.2', '>=') -- assert: +- ansible.builtin.assert: that: update_zabbix_template_result is changed - when: zabbix_version is version('4.2', '>=') - name: Add tags to Zabbix template (idempotency check). - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" macros: - - macro: '{$EXAMPLE_MACRO1}' + - macro: "{$EXAMPLE_MACRO1}" value: 1000 - - macro: '{$EXAMPLE_MACRO2}' - value: 'text' + - macro: "{$EXAMPLE_MACRO2}" + value: "text" tags: - tag: tag1 value: 1000 @@ -226,66 +213,159 @@ value: text state: present register: update_zabbix_template_result - when: zabbix_version is version('4.2', '>=') -- assert: +- ansible.builtin.assert: that: update_zabbix_template_result is not changed - when: zabbix_version is version('4.2', '>=') - name: Remove tags from Zabbix template. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost template_groups: - - 'Templates' - - 'Templates/Applications' + - "Templates" + - "Templates/Applications" link_templates: - - "{{ 'Zabbix proxy health' if zabbix_version | float >= 5.4 else 'Template App Zabbix Proxy' }}" - - "{{ 'FTP Service' if zabbix_version | float >= 5.4 else 'Template App FTP Service' }}" + - "Zabbix proxy health" + - "FTP Service" macros: - - macro: '{$EXAMPLE_MACRO1}' + - macro: "{$EXAMPLE_MACRO1}" value: 1000 - - macro: '{$EXAMPLE_MACRO2}' - value: 'text' + - macro: "{$EXAMPLE_MACRO2}" + value: "text" tags: [] state: present register: update_zabbix_template_result - when: zabbix_version is version('4.2', '>=') -- assert: +- ansible.builtin.assert: that: update_zabbix_template_result is changed - when: zabbix_version is version('4.2', '>=') -# #### -# Import template tests -# #### +- name: Delete Zabbix template. + community.zabbix.zabbix_template: + template_name: ExampleHost + state: absent + register: delete_zabbix_template_result + +- ansible.builtin.assert: + that: + - delete_zabbix_template_result.changed is sameas true + +# +# JSON Tests +# + +- name: Import Zabbix template from JSON file (idempotency check). + community.zabbix.zabbix_template: + template_json: "{{ lookup('file', 'template3_54_higher.json') }}" + state: present + register: import_template_json -- include_tasks: import_54_lower.yml - when: zabbix_version is version('5.4', '<') +- name: Assert Zabbix template from JSON file (idempotency check). + ansible.builtin.assert: + that: + - import_template_json.changed is sameas true + +- name: Import Zabbix template from JSON file with matching values (idempotency check). + community.zabbix.zabbix_template: + template_json: "{{ lookup('file', 'template3_54_higher.json') }}" + state: present + register: import_template_json -- include_tasks: import_54_higher.yml - when: zabbix_version is version('5.4', '>=') +- name: Assert Zabbix template from JSON file with matching values (idempotency check). + ansible.builtin.assert: + that: + - import_template_json.changed is sameas false + +- name: Gather Zabbix template infomation. + community.zabbix.zabbix_template_info: + template_name: ExampleHost + format: json + register: gather_template_result + +- block: + - ansible.builtin.assert: + that: + - gather_template_result.template_json[template_export_key][template_groups_key].0.name == 'Templates' + - gather_template_result.template_json[template_export_key][template_groups_key].1.name == 'Templates/Applications' + - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'FTP Service' + - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Zabbix proxy health' + - gather_template_result.template_json[template_export_key].templates.0.macros.0.macro == '{$EXAMPLE_MACRO1}' + - gather_template_result.template_json[template_export_key].templates.0.macros.0.value == '1000' + - gather_template_result.template_json[template_export_key].templates.0.macros.1.macro == '{$EXAMPLE_MACRO2}' + - gather_template_result.template_json[template_export_key].templates.0.macros.1.value == 'text' + +- name: Import Zabbix template from JSON file with updated values. + community.zabbix.zabbix_template: + template_json: "{{ lookup('file', 'template3-changed_54_higher.json') }}" + state: present + register: import_template_json + +- ansible.builtin.assert: + that: + - import_template_json.changed is sameas true + +- name: Gather Zabbix template infomation. + community.zabbix.zabbix_template_info: + template_name: ExampleHost + format: json + register: gather_template_result + +- ansible.builtin.assert: + that: + - gather_template_result.template_json[template_export_key].templates.0.macros.0.macro == '{$EXAMPLE_MACRO1}' + - gather_template_result.template_json[template_export_key].templates.0.macros.0.value == '1000' + - gather_template_result.template_json[template_export_key].templates.0.macros.1.macro == '{$EXAMPLE_MACRO2}' + - gather_template_result.template_json[template_export_key].templates.0.macros.1.value == 'text' + - gather_template_result.template_json[template_export_key].templates.0.macros.2.macro == '{$EXAMPLE_MACRO3}' + - gather_template_result.template_json[template_export_key].templates.0.macros.2.value == 'text2' + +# +# xml +# + +- block: + - name: Import Zabbix template from XML file with updated values. + community.zabbix.zabbix_template: + template_xml: "{{ lookup('file', 'template3_54_higher.xml') }}" + state: present + register: import_template_xml + + - ansible.builtin.assert: + that: + - import_template_xml.changed is sameas true + +- name: Gather Zabbix template infomation. + community.zabbix.zabbix_template_info: + template_name: ExampleHost + format: json + register: gather_template_result + +# zabbix returns values sorted alphabetically so HTTP Service template comes before Zabbix Proxy template +- block: + - ansible.builtin.assert: + that: + - gather_template_result.template_json[template_export_key].templates.0.templates.0.name == 'FTP Service' + - gather_template_result.template_json[template_export_key].templates.0.templates.1.name == 'Zabbix proxy health' # # Cleanup again # - name: Delete Zabbix template. - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost state: absent register: delete_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - delete_zabbix_template_result.changed is sameas true - name: Delete Zabbix template (idempotency check). - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHost state: absent register: delete_zabbix_template_result -- assert: +- ansible.builtin.assert: that: - delete_zabbix_template_result.changed is sameas false @@ -293,38 +373,36 @@ # Unicode stuff # -- when: zabbix_version is version('5.0', '>=') - block: - # The test if decode Unicode correctly and to be imported the template. - # https://github.com/ansible-collections/community.zabbix/issues/314 - - name: Import Zabbix template from JSON file with unicode. - zabbix_template: - template_json: "{{ lookup('file', 'template1_50_higher_decode_unicode.json') }}" - state: present - register: import_template_json +# The test if decode Unicode correctly and to be imported the template. +# https://github.com/ansible-collections/community.zabbix/issues/314 +- name: Import Zabbix template from JSON file with unicode. + community.zabbix.zabbix_template: + template_json: "{{ lookup('file', 'template1_50_higher_decode_unicode.json') }}" + state: present + register: import_template_json - - name: Gather Zabbix template infomation. - zabbix_template_info: - template_name: ExampleTemplate314 - format: json - register: gather_template_result +- name: Gather Zabbix template infomation. + community.zabbix.zabbix_template_info: + template_name: ExampleTemplate314 + format: json + register: gather_template_result - - assert: - that: - - import_template_json.changed is sameas true - - gather_template_result.template_json.zabbix_export.templates.0.description == "\u30c6\u30b9\u30c8\u30b3\u30e1\u30f3\u30c8" +- ansible.builtin.assert: + that: + - import_template_json.changed is sameas true + - gather_template_result.template_json.zabbix_export.templates.0.description == "\u30c6\u30b9\u30c8\u30b3\u30e1\u30f3\u30c8" - - name: Delete Zabbix template. - zabbix_template: - template_name: ExampleTemplate314 - state: absent - register: delete_zabbix_template_result +- name: Delete Zabbix template. + community.zabbix.zabbix_template: + template_name: ExampleTemplate314 + state: absent + register: delete_zabbix_template_result - - assert: - that: - - delete_zabbix_template_result.changed is sameas true +- ansible.builtin.assert: + that: + - delete_zabbix_template_result.changed is sameas true - name: Clean up ExampleHostWithLinked template - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleHostWithLinked state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template_info/tasks/main.yml index 3146c04b3..ae790f1f9 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template_info/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_template_info/tasks/main.yml @@ -1,48 +1,48 @@ --- - name: "test - Prepare integration tests for zabbix_template_info module" - zabbix_template: + community.zabbix.zabbix_template: template_name: ExampleTemplateForTempleteInfoModule template_groups: - Templates state: present register: prepare_result -- assert: +- ansible.builtin.assert: that: - prepare_result.changed is sameas true - name: "test - Fetch template info as a JSON format from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: json register: fetch_template_json_format_result - name: "test - Set key to template_export_key variable(This deals with the key being masked)" - set_fact: + ansible.builtin.set_fact: template_export_key: "{{ item }}" loop: "{{ fetch_template_json_format_result.template_json.keys() | list }}" when: - item | regex_search('_export') -- assert: +- ansible.builtin.assert: that: - fetch_template_json_format_result.template_json[template_export_key].date is defined when: zabbix_version is version('6.2', '<=') -- assert: +- ansible.builtin.assert: that: - fetch_template_json_format_result.template_json[template_export_key][template_groups_key].0.name == "Templates" - fetch_template_json_format_result.template_json[template_export_key].templates.0.name == "ExampleTemplateForTempleteInfoModule" - fetch_template_json_format_result.template_json[template_export_key].templates.0.template == "ExampleTemplateForTempleteInfoModule" - name: "test - Fetch template info as a JSON format with omit_date parameter from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: json omit_date: true register: fetch_template_json_format_omit_date_result -- assert: +- ansible.builtin.assert: that: - fetch_template_json_format_omit_date_result.template_json[template_export_key].date is not defined - fetch_template_json_format_omit_date_result.template_json[template_export_key][template_groups_key].0.name == "Templates" @@ -50,66 +50,62 @@ - fetch_template_json_format_omit_date_result.template_json[template_export_key].templates.0.template == "ExampleTemplateForTempleteInfoModule" - name: "test - Fetch template info as a XML format from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: xml register: fetch_template_xml_format_result -- assert: +- ansible.builtin.assert: that: - fetch_template_xml_format_result.template_xml | regex_search('<date>.*</date>') is defined - fetch_template_xml_format_result.template_xml | regex_search('</date><groups><group><name>Templates</name></group></groups><templates>') is defined - fetch_template_xml_format_result.template_xml | regex_search('<templates><template><template>ExampleTemplateForTempleteInfoModule</template><name>ExampleTemplateForTempleteInfoModule</name><groups><group><name>Templates</name></group></groups></template></templates>') is defined - name: "test - Fetch template info as a XML format with omit_date parameter from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: xml omit_date: true register: fetch_template_xml_format_omit_date_result -- assert: +- ansible.builtin.assert: that: - fetch_template_xml_format_omit_date_result.template_xml | regex_search('<date>.*</date>') is none - fetch_template_xml_format_omit_date_result.template_xml | regex_search('</date><groups><group><name>Templates</name></group></groups><templates>') is defined - fetch_template_xml_format_omit_date_result.template_xml | regex_search('<templates><template><template>ExampleTemplateForTempleteInfoModule</template><name>ExampleTemplateForTempleteInfoModule</name><groups><group><name>Templates</name></group></groups></template></templates>') is defined - name: "test - Fetch template info as a YAML format from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: yaml register: fetch_template_yaml_format_result - when: zabbix_version is version('5.2', '>=') -- assert: +- ansible.builtin.assert: that: - fetch_template_yaml_format_result.template_yaml | regex_search('date: .+') is defined - fetch_template_yaml_format_result.template_yaml | regex_search('name: Templates') is defined - fetch_template_yaml_format_result.template_yaml | regex_search('template: ExampleTemplateForTempleteInfoModule') is defined - when: zabbix_version is version('5.2', '>=') - name: "test - Fetch template info as a YAML format with omit_date parameter from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: yaml omit_date: true register: fetch_template_yaml_format_omit_date_result - when: zabbix_version is version('5.2', '>=') -- assert: +- ansible.builtin.assert: that: - fetch_template_yaml_format_result.template_yaml | regex_search('date: .+') is not defined - fetch_template_yaml_format_result.template_yaml | regex_search('name: Templates') is defined - fetch_template_yaml_format_result.template_yaml | regex_search('template: ExampleTemplateForTempleteInfoModule') is defined - when: zabbix_version is version('5.2', '>=') - name: "test - Fetch template info with none format from Zabbix Server" - zabbix_template_info: + community.zabbix.zabbix_template_info: template_name: ExampleTemplateForTempleteInfoModule format: none register: fetch_template_none_format_result -- assert: +- ansible.builtin.assert: that: - fetch_template_none_format_result.template_id is defined - fetch_template_none_format_result.template_json is not defined diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_templategroup/meta/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_templategroup/meta/main.yml new file mode 100644 index 000000000..acdb704c8 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_templategroup/meta/main.yml @@ -0,0 +1,3 @@ +--- +dependencies: + - setup_zabbix diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_templategroup/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_templategroup/tasks/main.yml new file mode 100644 index 000000000..c04c20497 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_templategroup/tasks/main.yml @@ -0,0 +1,59 @@ +--- +- name: test - do not run tests for Zabbix < 6.2 + meta: end_play + when: zabbix_version is version('6.2', '<') + +- name: test - create new Zabbix template group + community.zabbix.zabbix_templategroup: + template_groups: + - zbxtempgrp_example_group01 + state: present + register: zbxtempgrp_new + +- name: assert that group was created + ansible.builtin.assert: + that: zbxtempgrp_new is changed + +- name: test - create same Zabbix template group once again + community.zabbix.zabbix_templategroup: + template_groups: + - zbxtempgrp_example_group01 + state: present + register: zbxtempgrp_existing + +- name: assert that nothing has been changed + ansible.builtin.assert: + that: not zbxtempgrp_existing is changed + +- name: test - attempt to create new Zabbix template group matching name of default Zabbix template group + community.zabbix.zabbix_templategroup: + template_groups: + - Templates + state: present + register: zbxtempgrp_default_existing + +- name: assert that nothing has been changed + ansible.builtin.assert: + that: not zbxtempgrp_default_existing is changed + +- name: test - attempt to delete previously created zabbix template group + community.zabbix.zabbix_templategroup: + template_groups: + - zbxtempgrp_example_group01 + state: absent + register: zbxtempgrp_existing_delete + +- name: assert that group was deleted + ansible.builtin.assert: + that: zbxtempgrp_existing_delete is changed + +- name: test - attempt to delete non-existing zabbix template group + community.zabbix.zabbix_templategroup: + template_groups: + - zbxtempgrp_example_group01 + state: absent + register: zbxtempgrp_missing_delete + +- name: assert that nothing has been changed + ansible.builtin.assert: + that: not zbxtempgrp_missing_delete is changed diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_token/meta/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_token/meta/main.yml new file mode 100644 index 000000000..acdb704c8 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_token/meta/main.yml @@ -0,0 +1,3 @@ +--- +dependencies: + - setup_zabbix diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_token/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_token/tasks/main.yml new file mode 100644 index 000000000..59b87b0f4 --- /dev/null +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_token/tasks/main.yml @@ -0,0 +1,99 @@ +--- +- name: Create token + community.zabbix.zabbix_token: + name: test token + description: Admin test token + username: Admin + status: true + expires_at: 1700000000 + state: present + register: zbx_token + +- name: assert that token was created + ansible.builtin.assert: + that: + - zbx_token is changed + +- name: Update token + community.zabbix.zabbix_token: + name: test token + description: Admin test token (Updated) + username: Admin + status: false + expires_at: 0 + register: zbx_token + +- name: assert that token was updated + ansible.builtin.assert: + that: + - zbx_token is changed + +- name: Update token (not changes) + community.zabbix.zabbix_token: + name: test token + description: Admin test token (Updated) + username: Admin + status: false + expires_at: 0 + register: zbx_token + +- name: assert that token was NOT updated + ansible.builtin.assert: + that: + - not zbx_token is changed + +- name: Delete token + community.zabbix.zabbix_token: + name: test token + username: Admin + state: absent + register: zbx_token + +- name: assert that token was deleted + ansible.builtin.assert: + that: + - zbx_token is changed + +- name: Delete token (already deleted) + community.zabbix.zabbix_token: + name: test token + username: Admin + state: absent + register: zbx_token + +- name: assert that token was not deleted + ansible.builtin.assert: + that: + - not zbx_token is changed + +- name: Create token with generating token + community.zabbix.zabbix_token: + name: test token + username: Admin + generate_token: true + register: zbx_token + +- name: assert that token was created + ansible.builtin.assert: + that: + - zbx_token is changed + +- name: Re-generate token + community.zabbix.zabbix_token: + name: test token + username: Admin + generate_token: true + register: zbx_new_token + +- name: assert that token was updated + ansible.builtin.assert: + that: + - zbx_token is changed + - zbx_token.token != zbx_new_token.token + +- name: Delete token + community.zabbix.zabbix_token: + name: test token + username: Admin + state: absent + register: zbx_token diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/for_zabbix_50_lower.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/for_zabbix_50_lower.yml deleted file mode 100644 index b658e970a..000000000 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/for_zabbix_50_lower.yml +++ /dev/null @@ -1,1044 +0,0 @@ ---- -# New user create test from here -- name: test - Create a new Zabbix user with check_mode and diff - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - passwd: password - check_mode: true - diff: true - register: create_zabbix_user_result - -- assert: - that: - - create_zabbix_user_result.changed is sameas true - -- name: test - Create a new Zabbix user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - passwd: password - register: create_zabbix_user_result - -- assert: - that: - - create_zabbix_user_result.changed is sameas true - -- name: test - Create a new Zabbix user(again) - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - passwd: password - register: create_zabbix_user_result - -- assert: - that: - - not create_zabbix_user_result.changed is sameas true - -# Parameter add test from here to existing user -- name: test - Add user group to existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: password - register: add_usergroup_to_existing_user_result - -- assert: - that: - - add_usergroup_to_existing_user_result.changed is sameas true - -- name: test - Add user medias(Email) to existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: password - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: add_user_medias_to_existing_user_result - -- assert: - that: - - add_user_medias_to_existing_user_result.changed is sameas true - -- name: test - Add multiple user medias(Email and SMS) to existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: password - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: add_user_medias_to_existing_user_result - -- assert: - that: - - add_user_medias_to_existing_user_result.changed is sameas true - -# Existing parameter updates test from here -- name: test - Update password parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - override_passwd: true - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_password_parameter_existing_user_result - -- assert: - that: - - update_password_parameter_existing_user_result.changed is sameas true - -- name: test - Update autologin parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologin: true - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_autologin_parameter_existing_user_result - -- assert: - that: - - update_autologin_parameter_existing_user_result.changed is sameas true - -- name: test - Update autologout parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_autologout_parameter_existing_user_result - -- assert: - that: - - update_autologout_parameter_existing_user_result.changed is sameas true - -- name: test - Update refresh parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_refresh_parameter_existing_user_result - -- assert: - that: - - update_refresh_parameter_existing_user_result.changed is sameas true - -- name: test - Update rows_per_page parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_rows_per_page_parameter_existing_user_result - -- assert: - that: - - update_rows_per_page_parameter_existing_user_result.changed is sameas true - -- name: test - Update after_login_url parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_after_login_url_parameter_existing_user_result - -- assert: - that: - - update_after_login_url_parameter_existing_user_result.changed is sameas true - -- name: test - Update theme parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: "{{ item }}" - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - loop: - - blue-theme - - dark-theme - register: update_theme_parameter_existing_user_result - -- assert: - that: - - item.changed is sameas true - loop: "{{ update_theme_parameter_existing_user_result.results }}" - -- name: test - Update type parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: "{{ item }}" - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - loop: - - Zabbix admin - - Zabbix super admin - register: update_type_parameter_existing_user_result - -- assert: - that: - - item.changed is sameas true - loop: "{{ update_type_parameter_existing_user_result.results }}" - -- name: test - Update lang parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_US - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_lang_parameter_existing_user_result - -- assert: - that: - - update_lang_parameter_existing_user_result.changed is sameas true - -- name: test - Update name and surname parameter for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_US - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_name_and_surname_parameter_existing_user_result - -- assert: - that: - - update_name_and_surname_parameter_existing_user_result.changed is sameas true - -- name: test - Update lang parameter for existing user with check_mode and diff - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - check_mode: true - diff: true - register: update_lang_parameter_existing_user_with_check_mode_diff_result - -- assert: - that: - - update_lang_parameter_existing_user_with_check_mode_diff_result.changed is sameas true - -- name: test - Update lang parameter for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_lang_parameter_existing_user_result - -- assert: - that: - - update_lang_parameter_existing_user_result.changed is sameas true - -- name: test - Update lang parameter for existing user(again) - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_lang_parameter_existing_user_result - -- assert: - that: - - not update_lang_parameter_existing_user_result.changed is sameas true - -# Parameter delete test from here from existing user -- name: test - Delete user medias(SMS) for existing user with check_mode and diff - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - check_mode: true - diff: true - register: delete_user_medias_existing_user_result - -- assert: - that: - - delete_user_medias_existing_user_result.changed is sameas true - -- name: test - Delete user medias(SMS) for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: delete_user_medias_existing_user_result - -- assert: - that: - - delete_user_medias_existing_user_result.changed is sameas true - -- name: test - Delete user group for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: delete_user_group_existing_user_result - -- assert: - that: - - delete_user_group_existing_user_result.changed is sameas true - -- name: test - optional user_medias - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - type: Zabbix super admin - lang: en_GB - register: update_user_optional_user_medias_existing_user_result - -- assert: - that: - - update_user_optional_user_medias_existing_user_result.changed is sameas False - -- name: test - Delete existing user with check_mode and diff - zabbix_user: - alias: example1 - state: absent - check_mode: true - diff: true - register: delete_existing_user_result - -- assert: - that: - - delete_existing_user_result.changed is sameas true - -- name: test - Delete existing user - zabbix_user: - alias: example1 - state: absent - register: delete_existing_user_result - -- assert: - that: - - delete_existing_user_result.changed is sameas true - -- name: test - Delete existing user(again) - zabbix_user: - alias: example1 - state: absent - register: delete_existing_user_result - -- assert: - that: - - not delete_existing_user_result.changed is sameas true - -- when: zabbix_version is version('4.0', '<') - block: - - name: test - Create new password-less user without LDAP group (fail, <4.0) - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - Guests - register: create_zabbix_user_ldap_fail - ignore_errors: true - - - assert: - that: - - create_zabbix_user_ldap_fail.failed is sameas True - -- when: zabbix_version is version('4.0', '>=') - block: - - name: test prepare - Create LDAP user group - zabbix_usergroup: - name: testLDAPgrp - gui_access: LDAP - register: zbxuser_create_ldap_group - - - assert: - that: - - zbxuser_create_ldap_group.changed is sameas True - - - name: test - Create new password-less user without LDAP group (fail) - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - Guests - register: create_zabbix_user_ldap_fail - ignore_errors: true - - - assert: - that: - - create_zabbix_user_ldap_fail.failed is sameas True - - - name: test - Create new password-less user as member in LDAP group - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - testLDAPgrp - register: create_zabbix_user_ldap_result - - - assert: - that: - - create_zabbix_user_ldap_result.changed is sameas True - - - name: test - Create new password-less user as member in LDAP group (again) - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - testLDAPgrp - register: create_zabbix_user_ldap_result - - - assert: - that: - - create_zabbix_user_ldap_result.changed is sameas False - - - name: test - Delete existing user - zabbix_user: - alias: example2alias - state: absent - register: delete_existing_user_result - - - assert: - that: - - delete_existing_user_result.changed is sameas true - -# The tests are to check the patch for PR hasn't a problem. -# https://github.com/ansible-collections/community.zabbix/pull/382 -- name: test - Create a zabbix user with minimum parameters - zabbix_user: - alias: example2 - usrgrps: - - Guests - passwd: password - register: create_zabbix_user_with_minimum_params_result - -- assert: - that: - - create_zabbix_user_with_minimum_params_result.changed is sameas true - -- name: test - Create a zabbix user with minimum parameters(again) - zabbix_user: - alias: example2 - usrgrps: - - Guests - passwd: password - register: create_zabbix_user_with_minimum_params_result - -- assert: - that: - - create_zabbix_user_with_minimum_params_result.changed is sameas false - -- name: test - Update the parameters without role_name - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: password - register: update_params_without_role_name_result - -- assert: - that: - - update_params_without_role_name_result.changed is sameas true - -- name: test - Update the parameters without role_name(again) - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: password - register: update_params_without_role_name_result - -- assert: - that: - - update_params_without_role_name_result.changed is sameas false - -- name: test - Add user medias(Email) as list to existing user - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - user_medias: - - mediatype: Email - sendto: - - example@example.com - - example1@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: add_user_email_media_as_list_to_existing_user_result - -- assert: - that: - - add_user_email_media_as_list_to_existing_user_result.changed is sameas true - -- name: test - Add user medias(Email) as list to existing user(again) - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - user_medias: - - mediatype: Email - sendto: - - example@example.com - - example1@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: add_user_email_media_as_list_to_existing_user_result - -- assert: - that: - - add_user_email_media_as_list_to_existing_user_result.changed is sameas false - -- name: test - Delete existing user - zabbix_user: - alias: example2 - state: absent - -- name: test prepare - Delete LDAP user group - zabbix_usergroup: - name: testLDAPgrp - state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/for_zabbix_54_higher.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/for_zabbix_54_higher.yml deleted file mode 100644 index 9d3d913ce..000000000 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/for_zabbix_54_higher.yml +++ /dev/null @@ -1,1100 +0,0 @@ ---- -# New user create test from here -- name: test - Create a new Zabbix user with check_mode and diff - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - check_mode: true - diff: true - register: create_zabbix_user_result - -- assert: - that: - - create_zabbix_user_result.changed is sameas true - -- name: test - Create a new Zabbix user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - register: create_zabbix_user_result - -- assert: - that: - - create_zabbix_user_result.changed is sameas true - -- name: test - Create a new Zabbix user(again) - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - register: create_zabbix_user_result - -- assert: - that: - - not create_zabbix_user_result.changed is sameas true - -# Parameter add test from here to existing user -- name: test - Add user group to existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: G$jd_79!jw - register: add_usergroup_to_existing_user_result - -- assert: - that: - - add_usergroup_to_existing_user_result.changed is sameas true - -- name: test - Add user medias(Email) to existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: G$jd_79!jw - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: add_user_medias_to_existing_user_result - -- assert: - that: - - add_user_medias_to_existing_user_result.changed is sameas true - -- name: test - Add multiple user medias(Email and SMS) to existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: G$jd_79!jw - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: add_user_medias_to_existing_user_result - -- assert: - that: - - add_user_medias_to_existing_user_result.changed is sameas true - -# Existing parameter updates test from here -- name: test - Update password parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - override_passwd: true - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_password_parameter_existing_user_result - -- assert: - that: - - update_password_parameter_existing_user_result.changed is sameas true - -- name: test - Update autologin parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologin: true - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_autologin_parameter_existing_user_result - -- assert: - that: - - update_autologin_parameter_existing_user_result.changed is sameas true - -- name: test - Update autologout parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_autologout_parameter_existing_user_result - -- assert: - that: - - update_autologout_parameter_existing_user_result.changed is sameas true - -- name: test - Update refresh parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_refresh_parameter_existing_user_result - -- assert: - that: - - update_refresh_parameter_existing_user_result.changed is sameas true - -- name: test - Update rows_per_page parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_rows_per_page_parameter_existing_user_result - -- assert: - that: - - update_rows_per_page_parameter_existing_user_result.changed is sameas true - -- name: test - Update after_login_url parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_after_login_url_parameter_existing_user_result - -- assert: - that: - - update_after_login_url_parameter_existing_user_result.changed is sameas true - -- name: test - Update theme parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: "{{ item }}" - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - loop: - - blue-theme - - dark-theme - register: update_theme_parameter_existing_user_result - -- assert: - that: - - item.changed is sameas true - loop: "{{ update_theme_parameter_existing_user_result.results }}" - -- name: test - Update role_name parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: "{{ item }}" - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - loop: - - Guest role - - Admin role - register: update_type_parameter_existing_user_result - -- assert: - that: - - item.changed is sameas true - loop: "{{ update_type_parameter_existing_user_result.results }}" - -- name: test - Update lang parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - lang: en_US - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_lang_parameter_existing_user_result - -- assert: - that: - - update_lang_parameter_existing_user_result.changed is sameas true - -- name: test - Update timezone parameter for existing user - zabbix_user: - alias: example1 - name: example - surname: test - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: en_US - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_timezone_parameter_existing_user_result - -- assert: - that: - - update_timezone_parameter_existing_user_result.changed is sameas true - -- name: test - Update name and surname parameter for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: en_US - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_name_and_surname_parameter_existing_user_result - -- assert: - that: - - update_name_and_surname_parameter_existing_user_result.changed is sameas true - -- name: test - Update lang parameter for existing user with check_mode and diff - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - check_mode: true - diff: true - register: update_lang_parameter_existing_user_with_check_mode_diff_result - -- assert: - that: - - update_lang_parameter_existing_user_with_check_mode_diff_result.changed is sameas true - -- name: test - Update lang parameter for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_lang_parameter_existing_user_result - -- assert: - that: - - update_lang_parameter_existing_user_result.changed is sameas true - -- name: test - Update lang parameter for existing user(again) - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - - mediatype: SMS - sendto: example@example.com - period: 1-5,01:00-23:00 - severity: - not_classified: false - information: true - warning: true - average: false - high: true - disaster: true - active: true - register: update_lang_parameter_existing_user_result - -- assert: - that: - - not update_lang_parameter_existing_user_result.changed is sameas true - -# Parameter delete test from here from existing user -- name: test - Delete user medias(SMS) for existing user with check_mode and diff - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - check_mode: true - diff: true - register: delete_user_medias_existing_user_result - -- assert: - that: - - delete_user_medias_existing_user_result.changed is sameas true - -- name: test - Delete user medias(SMS) for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Guests - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: delete_user_medias_existing_user_result - -- assert: - that: - - delete_user_medias_existing_user_result.changed is sameas true - -- name: test - Delete user group for existing user - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: delete_user_group_existing_user_result - -- assert: - that: - - delete_user_group_existing_user_result.changed is sameas true - -- name: test - optional user_medias - zabbix_user: - alias: example1 - name: example2 - surname: test2 - usrgrps: - - Zabbix administrators - passwd: update_password - autologout: 500 - refresh: 60 - rows_per_page: 300 - after_login_url: http://example.com - theme: dark-theme - role_name: Admin role - timezone: Asia/Tokyo - lang: fr_FR - register: update_user_optional_user_medias_existing_user_result - -- assert: - that: - - update_user_optional_user_medias_existing_user_result.changed is sameas False - -- name: test - Delete existing user with check_mode and diff - zabbix_user: - alias: example1 - state: absent - check_mode: true - diff: true - register: delete_existing_user_result - -- assert: - that: - - delete_existing_user_result.changed is sameas true - -- name: test - Delete existing user - zabbix_user: - alias: example1 - state: absent - register: delete_existing_user_result - -- assert: - that: - - delete_existing_user_result.changed is sameas true - -- name: test - Delete existing user(again) - zabbix_user: - alias: example1 - state: absent - register: delete_existing_user_result - -- assert: - that: - - not delete_existing_user_result.changed is sameas true - -- when: zabbix_version is version('4.0', '<') - block: - - name: test - Create new password-less user without LDAP group (fail, <4.0) - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - Guests - register: create_zabbix_user_ldap_fail - ignore_errors: true - - - assert: - that: - - create_zabbix_user_ldap_fail.failed is sameas True - -- when: zabbix_version is version('4.0', '>=') - block: - - name: test prepare - Create LDAP user group - zabbix_usergroup: - name: testLDAPgrp - gui_access: LDAP - register: zbxuser_create_ldap_group - - - assert: - that: - - zbxuser_create_ldap_group.changed is sameas True - - - name: test - Create new password-less user without LDAP group (fail) - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - Guests - register: create_zabbix_user_ldap_fail - ignore_errors: true - - - assert: - that: - - create_zabbix_user_ldap_fail.failed is sameas True - - - name: test - Create new password-less user as member in LDAP group - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - testLDAPgrp - register: create_zabbix_user_ldap_result - - - assert: - that: - - create_zabbix_user_ldap_result.changed is sameas True - - - name: test - Create new password-less user as member in LDAP group (again) - zabbix_user: - alias: example2alias - name: example2 - surname: testldap - usrgrps: - - testLDAPgrp - register: create_zabbix_user_ldap_result - - - assert: - that: - - create_zabbix_user_ldap_result.changed is sameas False - - - name: test - Delete existing user - zabbix_user: - alias: example2alias - state: absent - register: delete_existing_user_result - - - assert: - that: - - delete_existing_user_result.changed is sameas true - -# The tests are to check the patch for PR hasn't a problem. -# https://github.com/ansible-collections/community.zabbix/pull/382 -- name: test - Create a zabbix user with minimum parameters - zabbix_user: - alias: example2 - usrgrps: - - Guests - passwd: G$jd_79!jw - role_name: "User role" - register: create_zabbix_user_with_minimum_params_result - -- assert: - that: - - create_zabbix_user_with_minimum_params_result.changed is sameas true - -- name: test - Create a zabbix user with minimum parameters(again) - zabbix_user: - alias: example2 - usrgrps: - - Guests - passwd: G$jd_79!jw - role_name: "User role" - register: create_zabbix_user_with_minimum_params_result - -- assert: - that: - - create_zabbix_user_with_minimum_params_result.changed is sameas false - -- name: test - Update the parameters without role_name - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - register: update_params_without_role_name_result - -- assert: - that: - - update_params_without_role_name_result.changed is sameas true - -- name: test - Update the parameters without role_name(again) - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - register: update_params_without_role_name_result - -- assert: - that: - - update_params_without_role_name_result.changed is sameas false - -- name: test - Add user medias(Email) as list to existing user - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - user_medias: - - mediatype: Email - sendto: - - example@example.com - - example1@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: add_user_email_media_as_list_to_existing_user_result - -- assert: - that: - - add_user_email_media_as_list_to_existing_user_result.changed is sameas true - -- name: test - Add user medias(Email) as list to existing user(again) - zabbix_user: - alias: example2 - name: example2 - surname: test - usrgrps: - - Guests - passwd: G$jd_79!jw - user_medias: - - mediatype: Email - sendto: - - example@example.com - - example1@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: true - register: add_user_email_media_as_list_to_existing_user_result - -- assert: - that: - - add_user_email_media_as_list_to_existing_user_result.changed is sameas false - -- name: test - Delete existing user - zabbix_user: - alias: example2 - state: absent - -- name: test prepare - Delete LDAP user group - zabbix_usergroup: - name: testLDAPgrp - state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/main.yml index f762591cf..29163436f 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user/tasks/main.yml @@ -1,10 +1,1082 @@ --- -- name: Execute the integration test for Zabbix 5.0 and lower - include_tasks: for_zabbix_50_lower.yml - when: - - zabbix_version | float <= 5.0 - -- name: Execute the integration test for Zabbix 5.4 and higher - include_tasks: for_zabbix_54_higher.yml - when: - - zabbix_version | float >= 5.4 +# New user create test from here +- name: test - Create a new Zabbix user with check_mode and diff + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + check_mode: true + diff: true + register: create_zabbix_user_result + +- ansible.builtin.assert: + that: + - create_zabbix_user_result.changed is sameas true + +- name: test - Create a new Zabbix user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + register: create_zabbix_user_result + +- ansible.builtin.assert: + that: + - create_zabbix_user_result.changed is sameas true + +- name: test - Create a new Zabbix user(again) + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + register: create_zabbix_user_result + +- ansible.builtin.assert: + that: + - not create_zabbix_user_result.changed is sameas true + +# Parameter add test from here to existing user +- name: test - Add user group to existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: G$jd_79!jw + register: add_usergroup_to_existing_user_result + +- ansible.builtin.assert: + that: + - add_usergroup_to_existing_user_result.changed is sameas true + +- name: test - Add user medias(Email) to existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: G$jd_79!jw + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + register: add_user_medias_to_existing_user_result + +- ansible.builtin.assert: + that: + - add_user_medias_to_existing_user_result.changed is sameas true + +- name: test - Add multiple user medias(Email and SMS) to existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: G$jd_79!jw + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: add_user_medias_to_existing_user_result + +- ansible.builtin.assert: + that: + - add_user_medias_to_existing_user_result.changed is sameas true + +# Existing parameter updates test from here +- name: test - Update password parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + override_passwd: true + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_password_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_password_parameter_existing_user_result.changed is sameas true + +- name: test - Update autologin parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologin: true + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_autologin_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_autologin_parameter_existing_user_result.changed is sameas true + +- name: test - Update autologout parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_autologout_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_autologout_parameter_existing_user_result.changed is sameas true + +- name: test - Update refresh parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_refresh_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_refresh_parameter_existing_user_result.changed is sameas true + +- name: test - Update rows_per_page parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_rows_per_page_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_rows_per_page_parameter_existing_user_result.changed is sameas true + +- name: test - Update after_login_url parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_after_login_url_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_after_login_url_parameter_existing_user_result.changed is sameas true + +- name: test - Update theme parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: "{{ item }}" + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + loop: + - blue-theme + - dark-theme + register: update_theme_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - item.changed is sameas true + loop: "{{ update_theme_parameter_existing_user_result.results }}" + +- name: test - Update role_name parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: "{{ item }}" + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + loop: + - Guest role + - Admin role + register: update_type_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - item.changed is sameas true + loop: "{{ update_type_parameter_existing_user_result.results }}" + +- name: test - Update lang parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + lang: en_US + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_lang_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_lang_parameter_existing_user_result.changed is sameas true + +- name: test - Update timezone parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example + surname: test + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: en_US + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_timezone_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_timezone_parameter_existing_user_result.changed is sameas true + +- name: test - Update name and surname parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: en_US + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_name_and_surname_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_name_and_surname_parameter_existing_user_result.changed is sameas true + +- name: test - Update lang parameter for existing user with check_mode and diff + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + check_mode: true + diff: true + register: update_lang_parameter_existing_user_with_check_mode_diff_result + +- ansible.builtin.assert: + that: + - update_lang_parameter_existing_user_with_check_mode_diff_result.changed is sameas true + +- name: test - Update lang parameter for existing user + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_lang_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - update_lang_parameter_existing_user_result.changed is sameas true + +- name: test - Update lang parameter for existing user(again) + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + - mediatype: SMS + sendto: example@example.com + period: 1-5,01:00-23:00 + severity: + not_classified: false + information: true + warning: true + average: false + high: true + disaster: true + active: true + register: update_lang_parameter_existing_user_result + +- ansible.builtin.assert: + that: + - not update_lang_parameter_existing_user_result.changed is sameas true + +# Parameter delete test from here from existing user +- name: test - Delete user medias(SMS) for existing user with check_mode and diff + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + check_mode: true + diff: true + register: delete_user_medias_existing_user_result + +- ansible.builtin.assert: + that: + - delete_user_medias_existing_user_result.changed is sameas true + +- name: test - Delete user medias(SMS) for existing user + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Guests + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + register: delete_user_medias_existing_user_result + +- ansible.builtin.assert: + that: + - delete_user_medias_existing_user_result.changed is sameas true + +- name: test - Delete user group for existing user + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + register: delete_user_group_existing_user_result + +- ansible.builtin.assert: + that: + - delete_user_group_existing_user_result.changed is sameas true + +- name: test - optional user_medias + community.zabbix.zabbix_user: + username: example1 + name: example2 + surname: test2 + usrgrps: + - Zabbix administrators + passwd: update_password + autologout: 500 + refresh: 60 + rows_per_page: 300 + after_login_url: http://example.com + theme: dark-theme + role_name: Admin role + timezone: Asia/Tokyo + lang: fr_FR + register: update_user_optional_user_medias_existing_user_result + +- ansible.builtin.assert: + that: + - update_user_optional_user_medias_existing_user_result.changed is sameas False + +- name: test - Delete existing user with check_mode and diff + community.zabbix.zabbix_user: + username: example1 + state: absent + check_mode: true + diff: true + register: delete_existing_user_result + +- ansible.builtin.assert: + that: + - delete_existing_user_result.changed is sameas true + +- name: test - Delete existing user + community.zabbix.zabbix_user: + username: example1 + state: absent + register: delete_existing_user_result + +- ansible.builtin.assert: + that: + - delete_existing_user_result.changed is sameas true + +- name: test - Delete existing user(again) + community.zabbix.zabbix_user: + username: example1 + state: absent + register: delete_existing_user_result + +- ansible.builtin.assert: + that: + - not delete_existing_user_result.changed is sameas true + +- name: test prepare - Create LDAP user group + community.zabbix.zabbix_usergroup: + name: testLDAPgrp + gui_access: LDAP + register: zbxuser_create_ldap_group + +- ansible.builtin.assert: + that: + - zbxuser_create_ldap_group.changed is sameas True + +- name: test - Create new password-less user without LDAP group (fail) + community.zabbix.zabbix_user: + username: example2username + name: example2 + surname: testldap + usrgrps: + - Guests + register: create_zabbix_user_ldap_fail + ignore_errors: true + +- ansible.builtin.assert: + that: + - create_zabbix_user_ldap_fail.failed is sameas True + +- name: test - Create new password-less user as member in LDAP group + community.zabbix.zabbix_user: + username: example2username + name: example2 + surname: testldap + usrgrps: + - testLDAPgrp + register: create_zabbix_user_ldap_result + +- ansible.builtin.assert: + that: + - create_zabbix_user_ldap_result.changed is sameas True + +- name: test - Create new password-less user as member in LDAP group (again) + community.zabbix.zabbix_user: + username: example2username + name: example2 + surname: testldap + usrgrps: + - testLDAPgrp + register: create_zabbix_user_ldap_result + +- ansible.builtin.assert: + that: + - create_zabbix_user_ldap_result.changed is sameas False + +- name: test - Delete existing user + community.zabbix.zabbix_user: + username: example2username + state: absent + register: delete_existing_user_result + +- ansible.builtin.assert: + that: + - delete_existing_user_result.changed is sameas true + +# The tests are to check the patch for PR hasn't a problem. +# https://github.com/ansible-collections/community.zabbix/pull/382 +- name: test - Create a zabbix user with minimum parameters + community.zabbix.zabbix_user: + username: example2 + usrgrps: + - Guests + passwd: G$jd_79!jw + role_name: "User role" + register: create_zabbix_user_with_minimum_params_result + +- ansible.builtin.assert: + that: + - create_zabbix_user_with_minimum_params_result.changed is sameas true + +- name: test - Create a zabbix user with minimum parameters(again) + community.zabbix.zabbix_user: + username: example2 + usrgrps: + - Guests + passwd: G$jd_79!jw + role_name: "User role" + register: create_zabbix_user_with_minimum_params_result + +- ansible.builtin.assert: + that: + - create_zabbix_user_with_minimum_params_result.changed is sameas false + +- name: test - Update the parameters without role_name + community.zabbix.zabbix_user: + username: example2 + name: example2 + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + register: update_params_without_role_name_result + +- ansible.builtin.assert: + that: + - update_params_without_role_name_result.changed is sameas true + +- name: test - Update the parameters without role_name(again) + community.zabbix.zabbix_user: + username: example2 + name: example2 + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + register: update_params_without_role_name_result + +- ansible.builtin.assert: + that: + - update_params_without_role_name_result.changed is sameas false + +- name: test - Add user medias(Email) as list to existing user + community.zabbix.zabbix_user: + username: example2 + name: example2 + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + user_medias: + - mediatype: Email + sendto: + - example@example.com + - example1@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + register: add_user_email_media_as_list_to_existing_user_result + +- ansible.builtin.assert: + that: + - add_user_email_media_as_list_to_existing_user_result.changed is sameas true + +- name: test - Add user medias(Email) as list to existing user(again) + community.zabbix.zabbix_user: + username: example2 + name: example2 + surname: test + usrgrps: + - Guests + passwd: G$jd_79!jw + user_medias: + - mediatype: Email + sendto: + - example@example.com + - example1@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: true + register: add_user_email_media_as_list_to_existing_user_result + +- ansible.builtin.assert: + that: + - add_user_email_media_as_list_to_existing_user_result.changed is sameas false + +- name: test - Delete existing user + community.zabbix.zabbix_user: + username: example2 + state: absent + +- name: test prepare - Delete LDAP user group + community.zabbix.zabbix_usergroup: + name: testLDAPgrp + state: absent diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/main.yml index 6c697a2e5..e4cc87d28 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/main.yml @@ -3,8 +3,8 @@ - include_tasks: zabbix_user_directory_tests.yml always: - - name: Cleanup - zabbix_user_directory: - name: TestUserDirectory - state: absent - ignore_errors: true + - name: Cleanup + community.zabbix.zabbix_user_directory: + name: TestUserDirectory + state: absent + ignore_errors: true diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/zabbix_user_directory_tests.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/zabbix_user_directory_tests.yml index db057a5d0..6488b80e5 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/zabbix_user_directory_tests.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_directory/tasks/zabbix_user_directory_tests.yml @@ -10,97 +10,97 @@ name: TestUserDirectory block: - - name: test - create new user directory in check mode - zabbix_user_directory: - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - check_mode: true - register: directory_check_result - - - assert: - that: directory_check_result.changed is sameas True - - - name: test - attempt to create new user directory with not all mandatory parameters - zabbix_user_directory: - host: 'test.com' - port: 389 - ignore_errors: true - register: directory_expect_fail_result - - - assert: - that: directory_expect_fail_result.failed is sameas True - - - name: test - create new user directory withoud bind_password - zabbix_user_directory: - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - register: directory_result - - - assert: - that: directory_result.changed is sameas True - - - name: test - create new user directory without bind_password again - zabbix_user_directory: - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - register: directory_again_result - - - assert: - that: directory_again_result.changed is sameas False - - - name: test - delete user directory - zabbix_user_directory: - state: absent - register: directory_delete_result - - - assert: - that: directory_delete_result.changed is sameas True - - - name: test - create new user directory with bind_password - zabbix_user_directory: - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - bind_password: 'password' - register: directory_result - - - assert: - that: directory_result.changed is sameas True - - - name: test - create new user directory with bind_password again - zabbix_user_directory: - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - bind_password: 'password' - register: directory_again_result - - - assert: - that: directory_again_result.changed is sameas True - - - name: test - update only host parameter in user directory - zabbix_user_directory: - host: 'test.ca' - register: directory_update_result - - - assert: - that: directory_update_result.changed is sameas True - - - name: test - update only host parameter in user directory again - zabbix_user_directory: - host: 'test.ca' - register: directory_update_again_result - - - assert: - that: directory_update_again_result.changed is sameas False + - name: test - create new user directory in check mode + community.zabbix.zabbix_user_directory: + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + check_mode: true + register: directory_check_result + + - ansible.builtin.assert: + that: directory_check_result.changed is sameas True + + - name: test - attempt to create new user directory with not all mandatory parameters + community.zabbix.zabbix_user_directory: + host: "test.com" + port: 389 + ignore_errors: true + register: directory_expect_fail_result + + - ansible.builtin.assert: + that: directory_expect_fail_result.failed is sameas True + + - name: test - create new user directory withoud bind_password + community.zabbix.zabbix_user_directory: + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + register: directory_result + + - ansible.builtin.assert: + that: directory_result.changed is sameas True + + - name: test - create new user directory without bind_password again + community.zabbix.zabbix_user_directory: + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + register: directory_again_result + + - ansible.builtin.assert: + that: directory_again_result.changed is sameas False + + - name: test - delete user directory + community.zabbix.zabbix_user_directory: + state: absent + register: directory_delete_result + + - ansible.builtin.assert: + that: directory_delete_result.changed is sameas True + + - name: test - create new user directory with bind_password + community.zabbix.zabbix_user_directory: + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + bind_password: "password" + register: directory_result + + - ansible.builtin.assert: + that: directory_result.changed is sameas True + + - name: test - create new user directory with bind_password again + community.zabbix.zabbix_user_directory: + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + bind_password: "password" + register: directory_again_result + + - ansible.builtin.assert: + that: directory_again_result.changed is sameas True + + - name: test - update only host parameter in user directory + community.zabbix.zabbix_user_directory: + host: "test.ca" + register: directory_update_result + + - ansible.builtin.assert: + that: directory_update_result.changed is sameas True + + - name: test - update only host parameter in user directory again + community.zabbix.zabbix_user_directory: + host: "test.ca" + register: directory_update_again_result + + - ansible.builtin.assert: + that: directory_update_again_result.changed is sameas False when: zabbix_version is version('6.4', '<') @@ -111,327 +111,327 @@ name: TestUserDirectory block: - - name: test - create new LDAP user directory in check mode - zabbix_user_directory: - idp_type: ldap - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - check_mode: true - register: directory_check_result - - - assert: - that: directory_check_result.changed is sameas True - - - name: test - attempt to create new LDAP user directory with not all mandatory parameters - zabbix_user_directory: - idp_type: ldap - host: 'test.com' - port: 389 - ignore_errors: true - register: directory_expect_fail_result - - - assert: - that: directory_expect_fail_result.failed is sameas True - - - name: test - create new LDAP user directory withoud bind_password - zabbix_user_directory: - idp_type: ldap - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - register: directory_result - - - assert: - that: directory_result.changed is sameas True - - - name: test - create new LDAP user directory without bind_password again - zabbix_user_directory: - idp_type: ldap - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - register: directory_again_result - - - assert: - that: directory_again_result.changed is sameas False - - - name: test - delete LDAP user directory - zabbix_user_directory: - state: absent - register: directory_delete_result - - - assert: - that: directory_delete_result.changed is sameas True - - - name: test - create new LDAP user directory with bind_password - zabbix_user_directory: - idp_type: ldap - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - bind_password: 'password' - register: directory_result - - - assert: - that: directory_result.changed is sameas True - - - name: test - create new LDAP user directory with bind_password again - zabbix_user_directory: - idp_type: ldap - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - bind_password: 'password' - register: directory_again_result - - - assert: - that: directory_again_result.changed is sameas True - - - name: test - update host parameter in LDAP user directory - zabbix_user_directory: - idp_type: ldap - host: 'test.ca' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - register: directory_update_result - - - assert: - that: directory_update_result.changed is sameas True - - - name: test - update host parameter in LDAP user directory again - zabbix_user_directory: - idp_type: ldap - host: 'test.ca' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - register: directory_update_again_result - - - assert: - that: directory_update_again_result.changed is sameas False - - - name: test - add media type mapping with non-existing media type - zabbix_user_directory: - idp_type: ldap - host: 'test.ca' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - provision_status: True - provision_media: - - name: Media1 - mediatype: EmailX - attribute: email - provision_groups: - - name: idpname1 - role: Guest role - user_groups: - - Guests - ignore_errors: True - register: directory_update_media_fail_result - - - assert: - that: directory_update_media_fail_result.failed is sameas True - - - name: test - add mappings - zabbix_user_directory: - idp_type: ldap - host: 'test.ca' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - provision_status: True - group_name: cn - group_basedn: ou=Group,dc=example,dc=org - group_member: member - user_ref_attr: uid - group_filter: '(member=uid=%{ref},ou=Users,dc=example,dc=com)' - user_username: first_name - user_lastname: last_name - provision_media: - - name: Media1 - mediatype: Email - attribute: email1 - provision_groups: - - name: idpname1 - role: Guest role - user_groups: - - Guests - register: directory_update_media_result - - - assert: - that: directory_update_media_result.changed is sameas True - - - name: test - add mappings again - zabbix_user_directory: - idp_type: ldap - host: 'test.ca' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - provision_status: True - group_name: cn - group_basedn: ou=Group,dc=example,dc=org - group_member: member - user_ref_attr: uid - group_filter: '(member=uid=%{ref},ou=Users,dc=example,dc=com)' - user_username: first_name - user_lastname: last_name - provision_media: - - name: Media1 - mediatype: Email - attribute: email1 - provision_groups: - - name: idpname1 - role: Guest role - user_groups: - - Guests - register: directory_update_media_again_result - - - assert: - that: directory_update_media_again_result.changed is sameas False - - - name: test - delete LDAP user directory - zabbix_user_directory: - state: absent - - - name: test - create new SAML user directory in check mode - zabbix_user_directory: - idp_type: saml - idp_entityid: http://okta.com/xxxxx - sp_entityid: zabbix - sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 - username_attribute: usrEmail - check_mode: true - register: directory_check_result - - - assert: - that: directory_check_result.changed is sameas True - - - name: test - attempt to create new SAML user directory with not all mandatory parameters - zabbix_user_directory: - idp_type: saml - ignore_errors: true - register: directory_expect_fail_result - - - assert: - that: directory_expect_fail_result.failed is sameas True - - - name: test - create new SAML user directory - zabbix_user_directory: - idp_type: saml - idp_entityid: http://okta.com/xxxxx - sp_entityid: zabbix - sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 - username_attribute: usrEmail - register: directory_create_result - - - assert: - that: directory_create_result.changed is sameas True - - - name: test - update SAML user directory with all optional parameters - zabbix_user_directory: - idp_type: saml - idp_entityid: http://okta.com/xxxxx - sp_entityid: zabbix - sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 - username_attribute: usrEmail - slo_url: http://yyyy.okta.com - nameid_format: 'urn:oasis' - scim_status: true - encrypt_nameid: true - encrypt_assertions: true - sign_messages: true - sign_assertions: true - sign_authn_requests: true - sign_logout_requests: true - sign_logout_responses: true - register: directory_create_all_result - - - assert: - that: directory_create_all_result.changed is sameas True - - - name: test - update SAML user directory with all optional parameters again - zabbix_user_directory: - idp_type: saml - idp_entityid: http://okta.com/xxxxx - sp_entityid: zabbix - sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 - username_attribute: usrEmail - slo_url: http://yyyy.okta.com - nameid_format: 'urn:oasis' - scim_status: true - encrypt_nameid: true - encrypt_assertions: true - sign_messages: true - sign_assertions: true - sign_authn_requests: true - sign_logout_requests: true - sign_logout_responses: true - register: directory_create_all_again_result - - - assert: - that: directory_create_all_again_result.changed is sameas False - - - name: test - delete SAML user directory - zabbix_user_directory: - state: absent - - - name: test - create new SAML user directory with mappings - zabbix_user_directory: - idp_type: saml - idp_entityid: http://okta.com/xxxxx - sp_entityid: zabbix - sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 - username_attribute: usrEmail - provision_status: True - group_name: cn - user_username: first_name - user_lastname: last_name - provision_media: - - name: Media1 - mediatype: Email - attribute: email1 - provision_groups: - - name: idpname1 - role: Guest role - user_groups: - - Guests - register: directory_create_mappings_result - - - assert: - that: directory_create_mappings_result.changed is sameas True - - - name: test - create new SAML user directory with mappings again - zabbix_user_directory: - idp_type: saml - idp_entityid: http://okta.com/xxxxx - sp_entityid: zabbix - sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 - username_attribute: usrEmail - provision_status: True - group_name: cn - user_username: first_name - user_lastname: last_name - provision_media: - - name: Media1 - mediatype: Email - attribute: email1 - provision_groups: - - name: idpname1 - role: Guest role - user_groups: - - Guests - register: directory_create_mappings_again_result - - - assert: - that: directory_create_mappings_again_result.changed is sameas False + - name: test - create new LDAP user directory in check mode + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + check_mode: true + register: directory_check_result + + - ansible.builtin.assert: + that: directory_check_result.changed is sameas True + + - name: test - attempt to create new LDAP user directory with not all mandatory parameters + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.com" + port: 389 + ignore_errors: true + register: directory_expect_fail_result + + - ansible.builtin.assert: + that: directory_expect_fail_result.failed is sameas True + + - name: test - create new LDAP user directory withoud bind_password + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + register: directory_result + + - ansible.builtin.assert: + that: directory_result.changed is sameas True + + - name: test - create new LDAP user directory without bind_password again + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + register: directory_again_result + + - ansible.builtin.assert: + that: directory_again_result.changed is sameas False + + - name: test - delete LDAP user directory + community.zabbix.zabbix_user_directory: + state: absent + register: directory_delete_result + + - ansible.builtin.assert: + that: directory_delete_result.changed is sameas True + + - name: test - create new LDAP user directory with bind_password + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + bind_password: "password" + register: directory_result + + - ansible.builtin.assert: + that: directory_result.changed is sameas True + + - name: test - create new LDAP user directory with bind_password again + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + bind_password: "password" + register: directory_again_result + + - ansible.builtin.assert: + that: directory_again_result.changed is sameas True + + - name: test - update host parameter in LDAP user directory + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.ca" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + register: directory_update_result + + - ansible.builtin.assert: + that: directory_update_result.changed is sameas True + + - name: test - update host parameter in LDAP user directory again + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.ca" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + register: directory_update_again_result + + - ansible.builtin.assert: + that: directory_update_again_result.changed is sameas False + + - name: test - add media type mapping with non-existing media type + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.ca" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + provision_status: True + provision_media: + - name: Media1 + mediatype: EmailX + attribute: email + provision_groups: + - name: idpname1 + role: Guest role + user_groups: + - Guests + ignore_errors: True + register: directory_update_media_fail_result + + - ansible.builtin.assert: + that: directory_update_media_fail_result.failed is sameas True + + - name: test - add mappings + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.ca" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + provision_status: True + group_name: cn + group_basedn: ou=Group,dc=example,dc=org + group_member: member + user_ref_attr: uid + group_filter: "(member=uid=%{ref},ou=Users,dc=example,dc=com)" + user_username: first_name + user_lastname: last_name + provision_media: + - name: Media1 + mediatype: Email + attribute: email1 + provision_groups: + - name: idpname1 + role: Guest role + user_groups: + - Guests + register: directory_update_media_result + + - ansible.builtin.assert: + that: directory_update_media_result.changed is sameas True + + - name: test - add mappings again + community.zabbix.zabbix_user_directory: + idp_type: ldap + host: "test.ca" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + provision_status: True + group_name: cn + group_basedn: ou=Group,dc=example,dc=org + group_member: member + user_ref_attr: uid + group_filter: "(member=uid=%{ref},ou=Users,dc=example,dc=com)" + user_username: first_name + user_lastname: last_name + provision_media: + - name: Media1 + mediatype: Email + attribute: email1 + provision_groups: + - name: idpname1 + role: Guest role + user_groups: + - Guests + register: directory_update_media_again_result + + - ansible.builtin.assert: + that: directory_update_media_again_result.changed is sameas False + + - name: test - delete LDAP user directory + community.zabbix.zabbix_user_directory: + state: absent + + - name: test - create new SAML user directory in check mode + community.zabbix.zabbix_user_directory: + idp_type: saml + idp_entityid: http://okta.com/xxxxx + sp_entityid: zabbix + sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 + username_attribute: usrEmail + check_mode: true + register: directory_check_result + + - ansible.builtin.assert: + that: directory_check_result.changed is sameas True + + - name: test - attempt to create new SAML user directory with not all mandatory parameters + community.zabbix.zabbix_user_directory: + idp_type: saml + ignore_errors: true + register: directory_expect_fail_result + + - ansible.builtin.assert: + that: directory_expect_fail_result.failed is sameas True + + - name: test - create new SAML user directory + community.zabbix.zabbix_user_directory: + idp_type: saml + idp_entityid: http://okta.com/xxxxx + sp_entityid: zabbix + sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 + username_attribute: usrEmail + register: directory_create_result + + - ansible.builtin.assert: + that: directory_create_result.changed is sameas True + + - name: test - update SAML user directory with all optional parameters + community.zabbix.zabbix_user_directory: + idp_type: saml + idp_entityid: http://okta.com/xxxxx + sp_entityid: zabbix + sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 + username_attribute: usrEmail + slo_url: http://yyyy.okta.com + nameid_format: "urn:oasis" + scim_status: true + encrypt_nameid: true + encrypt_assertions: true + sign_messages: true + sign_assertions: true + sign_authn_requests: true + sign_logout_requests: true + sign_logout_responses: true + register: directory_create_all_result + + - ansible.builtin.assert: + that: directory_create_all_result.changed is sameas True + + - name: test - update SAML user directory with all optional parameters again + community.zabbix.zabbix_user_directory: + idp_type: saml + idp_entityid: http://okta.com/xxxxx + sp_entityid: zabbix + sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 + username_attribute: usrEmail + slo_url: http://yyyy.okta.com + nameid_format: "urn:oasis" + scim_status: true + encrypt_nameid: true + encrypt_assertions: true + sign_messages: true + sign_assertions: true + sign_authn_requests: true + sign_logout_requests: true + sign_logout_responses: true + register: directory_create_all_again_result + + - ansible.builtin.assert: + that: directory_create_all_again_result.changed is sameas False + + - name: test - delete SAML user directory + community.zabbix.zabbix_user_directory: + state: absent + + - name: test - create new SAML user directory with mappings + community.zabbix.zabbix_user_directory: + idp_type: saml + idp_entityid: http://okta.com/xxxxx + sp_entityid: zabbix + sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 + username_attribute: usrEmail + provision_status: True + group_name: cn + user_username: first_name + user_lastname: last_name + provision_media: + - name: Media1 + mediatype: Email + attribute: email1 + provision_groups: + - name: idpname1 + role: Guest role + user_groups: + - Guests + register: directory_create_mappings_result + + - ansible.builtin.assert: + that: directory_create_mappings_result.changed is sameas True + + - name: test - create new SAML user directory with mappings again + community.zabbix.zabbix_user_directory: + idp_type: saml + idp_entityid: http://okta.com/xxxxx + sp_entityid: zabbix + sso_url: http://xxxx.okta.com/app/xxxxxx_123dhu8o3 + username_attribute: usrEmail + provision_status: True + group_name: cn + user_username: first_name + user_lastname: last_name + provision_media: + - name: Media1 + mediatype: Email + attribute: email1 + provision_groups: + - name: idpname1 + role: Guest role + user_groups: + - Guests + register: directory_create_mappings_again_result + + - ansible.builtin.assert: + that: directory_create_mappings_again_result.changed is sameas False when: zabbix_version is version('6.4', '>=') diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_info/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_info/tasks/main.yml index 7228e12eb..1f1862586 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_info/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_info/tasks/main.yml @@ -1,170 +1,94 @@ --- -# New user create test from here -- when: zabbix_version is version('5.4', '<') - block: - - name: test - Create a new Zabbix user - zabbix_user: - alias: example - name: user name - surname: user surname - usrgrps: - - Guests - - Disabled - passwd: G$jd_79!jw - lang: en_US - theme: blue-theme - autologin: false - autologout: '0' - refresh: '30' - rows_per_page: '200' - after_login_url: '' - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: false - type: Zabbix super admin - state: present - register: create_zabbix_user_result - - - assert: - that: - - create_zabbix_user_result.changed is sameas true - - - name: test - Set definition_of_results variable of Zabbix 5.0 and lower - set_fact: - definition_of_results: - - get_user_info_result[user_info_key].alias == "example" - - get_user_info_result[user_info_key].autologin is defined - - get_user_info_result[user_info_key].autologout is defined - - get_user_info_result[user_info_key].lang is defined - - get_user_info_result[user_info_key].medias.0.active is defined - - get_user_info_result[user_info_key].medias.0.mediaid is defined - - get_user_info_result[user_info_key].medias.0.period is defined - - get_user_info_result[user_info_key].medias.0.sendto is defined - - get_user_info_result[user_info_key].medias.0.severity is defined - - get_user_info_result[user_info_key].medias.0.userid is defined - - get_user_info_result[user_info_key].name is defined - - get_user_info_result[user_info_key].refresh is defined - - get_user_info_result[user_info_key].rows_per_page is defined - - get_user_info_result[user_info_key].surname is defined - - get_user_info_result[user_info_key].theme is defined - - get_user_info_result[user_info_key].type is defined - - get_user_info_result[user_info_key].url is defined - - get_user_info_result[user_info_key].userid is defined - - get_user_info_result[user_info_key].users_status is defined - - get_user_info_result[user_info_key].usrgrps | length == 2 - - get_user_info_result[user_info_key].usrgrps.0.debug_mode is defined - - get_user_info_result[user_info_key].usrgrps.0.gui_access is defined - - get_user_info_result[user_info_key].usrgrps.0.name is defined - - get_user_info_result[user_info_key].usrgrps.0.users_status is defined - - get_user_info_result[user_info_key].usrgrps.0.usrgrpid is defined - - get_user_info_result[user_info_key].usrgrps.1.debug_mode is defined - - get_user_info_result[user_info_key].usrgrps.1.gui_access is defined - - get_user_info_result[user_info_key].usrgrps.1.name is defined - - get_user_info_result[user_info_key].usrgrps.1.users_status is defined - - get_user_info_result[user_info_key].usrgrps.1.usrgrpid is defined - -- when: zabbix_version is version('5.4', '>=') - block: - - name: test - Create a new Zabbix user - zabbix_user: - alias: example - name: user name - surname: user surname - usrgrps: - - Guests - - Disabled - passwd: G$jd_79!jw - lang: en_US - theme: blue-theme - autologin: false - autologout: '0' - refresh: '30' - rows_per_page: '200' - after_login_url: '' - user_medias: - - mediatype: Email - sendto: example@example.com - period: 1-7,00:00-24:00 - severity: - not_classified: false - information: true - warning: true - average: true - high: true - disaster: true - active: false - role_name: Super admin role - timezone: Asia/Tokyo - state: present - register: create_zabbix_user_result +- name: test - Create a new Zabbix user + community.zabbix.zabbix_user: + username: example + name: user name + surname: user surname + usrgrps: + - Guests + - Disabled + passwd: G$jd_79!jw + lang: en_US + theme: blue-theme + autologin: false + autologout: "0" + refresh: "30" + rows_per_page: "200" + after_login_url: "" + user_medias: + - mediatype: Email + sendto: example@example.com + period: 1-7,00:00-24:00 + severity: + not_classified: false + information: true + warning: true + average: true + high: true + disaster: true + active: false + role_name: Super admin role + timezone: Asia/Tokyo + state: present + register: create_zabbix_user_result - - assert: - that: - - create_zabbix_user_result.changed is sameas true +- ansible.builtin.assert: + that: + - create_zabbix_user_result.changed is sameas true - - name: test - Set definition_of_results variable of Zabbix 5.4 and higher - set_fact: - definition_of_results: - - get_user_info_result[user_info_key].alias == "example" - - get_user_info_result[user_info_key].autologin is defined - - get_user_info_result[user_info_key].autologout is defined - - get_user_info_result[user_info_key].lang is defined - - get_user_info_result[user_info_key].medias.0.active is defined - - get_user_info_result[user_info_key].medias.0.mediaid is defined - - get_user_info_result[user_info_key].medias.0.period is defined - - get_user_info_result[user_info_key].medias.0.sendto is defined - - get_user_info_result[user_info_key].medias.0.severity is defined - - get_user_info_result[user_info_key].medias.0.userid is defined - - get_user_info_result[user_info_key].name is defined - - get_user_info_result[user_info_key].refresh is defined - - get_user_info_result[user_info_key].rows_per_page is defined - - get_user_info_result[user_info_key].surname is defined - - get_user_info_result[user_info_key].theme is defined - - get_user_info_result[user_info_key].roleid is defined - - get_user_info_result[user_info_key].url is defined - - get_user_info_result[user_info_key].userid is defined - - get_user_info_result[user_info_key].users_status is defined - - get_user_info_result[user_info_key].timezone is defined - - get_user_info_result[user_info_key].usrgrps | length == 2 - - get_user_info_result[user_info_key].usrgrps.0.debug_mode is defined - - get_user_info_result[user_info_key].usrgrps.0.gui_access is defined - - get_user_info_result[user_info_key].usrgrps.0.name is defined - - get_user_info_result[user_info_key].usrgrps.0.users_status is defined - - get_user_info_result[user_info_key].usrgrps.0.usrgrpid is defined - - get_user_info_result[user_info_key].usrgrps.1.debug_mode is defined - - get_user_info_result[user_info_key].usrgrps.1.gui_access is defined - - get_user_info_result[user_info_key].usrgrps.1.name is defined - - get_user_info_result[user_info_key].usrgrps.1.users_status is defined - - get_user_info_result[user_info_key].usrgrps.1.usrgrpid is defined +- name: test - Set definition_of_results variable + ansible.builtin.set_fact: + definition_of_results: + - get_user_info_result[user_info_key].username == "example" + - get_user_info_result[user_info_key].autologin is defined + - get_user_info_result[user_info_key].autologout is defined + - get_user_info_result[user_info_key].lang is defined + - get_user_info_result[user_info_key].medias.0.active is defined + - get_user_info_result[user_info_key].medias.0.mediaid is defined + - get_user_info_result[user_info_key].medias.0.period is defined + - get_user_info_result[user_info_key].medias.0.sendto is defined + - get_user_info_result[user_info_key].medias.0.severity is defined + - get_user_info_result[user_info_key].medias.0.userid is defined + - get_user_info_result[user_info_key].name is defined + - get_user_info_result[user_info_key].refresh is defined + - get_user_info_result[user_info_key].rows_per_page is defined + - get_user_info_result[user_info_key].surname is defined + - get_user_info_result[user_info_key].theme is defined + - get_user_info_result[user_info_key].roleid is defined + - get_user_info_result[user_info_key].url is defined + - get_user_info_result[user_info_key].userid is defined + - get_user_info_result[user_info_key].users_status is defined + - get_user_info_result[user_info_key].timezone is defined + - get_user_info_result[user_info_key].usrgrps | length == 2 + - get_user_info_result[user_info_key].usrgrps.0.debug_mode is defined + - get_user_info_result[user_info_key].usrgrps.0.gui_access is defined + - get_user_info_result[user_info_key].usrgrps.0.name is defined + - get_user_info_result[user_info_key].usrgrps.0.users_status is defined + - get_user_info_result[user_info_key].usrgrps.0.usrgrpid is defined + - get_user_info_result[user_info_key].usrgrps.1.debug_mode is defined + - get_user_info_result[user_info_key].usrgrps.1.gui_access is defined + - get_user_info_result[user_info_key].usrgrps.1.name is defined + - get_user_info_result[user_info_key].usrgrps.1.users_status is defined + - get_user_info_result[user_info_key].usrgrps.1.usrgrpid is defined - name: "test - Get a zabbix user information" - zabbix_user_info: - alias: example + community.zabbix.zabbix_user_info: + username: example register: get_user_info_result - name: "test - Set key to user_info_key variable(This deals with the key being masked)" - set_fact: + ansible.builtin.set_fact: user_info_key: "{{ item }}" loop: "{{ get_user_info_result.keys() | list }}" when: - item | regex_search('_user') -- assert: +- ansible.builtin.assert: that: definition_of_results - - name: test - Create a new Zabbix user - zabbix_user: - alias: example2 + community.zabbix.zabbix_user: + username: example2 usrgrps: - Guests - Disabled @@ -172,28 +96,22 @@ state: present register: create_zabbix_user_result2 -- assert: +- ansible.builtin.assert: that: - create_zabbix_user_result2.changed is sameas true - name: "test - Get a zabbix user information" - zabbix_user_info: - alias: example2 + community.zabbix.zabbix_user_info: + username: example2 register: get_user_info_result2 - name: "test - Set key to user_info_key variable(This deals with the key being masked)" - set_fact: + ansible.builtin.set_fact: user_info_key: "{{ item }}" loop: "{{ get_user_info_result2.keys() | list }}" when: - item | regex_search('_user') -- assert: - that: - - get_user_info_result2[user_info_key].alias == "example2" - when: zabbix_version is version('5.4', '<') - -- assert: +- ansible.builtin.assert: that: - get_user_info_result2[user_info_key].username == "example2" - when: zabbix_version is version('5.4', '>=') diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_role/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_role/tasks/main.yml index 799bef30b..53e57a043 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_role/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_user_role/tasks/main.yml @@ -1,106 +1,103 @@ --- -# New user role create test from here, only 6.0 and higher -- when: zabbix_version is version('6.0', '>=') - block: - - name: test - Create a new Zabbix role - zabbix_user_role: - state: present - name: Operators - type: User - rules: - ui.default_access: 0 - ui: - - name: "monitoring.hosts" - status: 0 - - name: "monitoring.maps" - status: 1 - register: create_zabbix_user_role_result +- name: test - Create a new Zabbix role + community.zabbix.zabbix_user_role: + state: present + name: Operators + type: User + rules: + ui.default_access: 0 + ui: + - name: "monitoring.hosts" + status: 0 + - name: "monitoring.maps" + status: 1 + register: create_zabbix_user_role_result - - assert: - that: - - create_zabbix_user_role_result.changed is sameas true +- ansible.builtin.assert: + that: + - create_zabbix_user_role_result.changed is sameas true - # Check user role idempotency - - name: test - Update a Zabbix role with same rules - zabbix_user_role: - state: present - name: Operators - type: User - rules: - ui.default_access: 0 - ui: - - name: "monitoring.hosts" - status: 0 - - name: "monitoring.maps" - status: 1 - register: create_zabbix_user_role_result +# Check user role idempotency +- name: test - Update a Zabbix role with same rules + community.zabbix.zabbix_user_role: + state: present + name: Operators + type: User + rules: + ui.default_access: 0 + ui: + - name: "monitoring.hosts" + status: 0 + - name: "monitoring.maps" + status: 1 + register: create_zabbix_user_role_result - - assert: - that: - - create_zabbix_user_role_result.changed is sameas false +- ansible.builtin.assert: + that: + - create_zabbix_user_role_result.changed is sameas false - # Check user role change - - name: test - Update a Zabbix role with new rules - zabbix_user_role: - state: present - name: Operators - type: User - rules: - ui.default_access: 0 - ui: - - name: "monitoring.hosts" - status: 1 - - name: "monitoring.maps" - status: 0 - register: create_zabbix_user_role_result +# Check user role change +- name: test - Update a Zabbix role with new rules + community.zabbix.zabbix_user_role: + state: present + name: Operators + type: User + rules: + ui.default_access: 0 + ui: + - name: "monitoring.hosts" + status: 1 + - name: "monitoring.maps" + status: 0 + register: create_zabbix_user_role_result - - assert: - that: - - create_zabbix_user_role_result.changed is sameas true +- ansible.builtin.assert: + that: + - create_zabbix_user_role_result.changed is sameas true - # Check user role remove - - name: test - Remove Zabbix role - zabbix_user_role: - state: absent - name: Operators - register: create_zabbix_user_role_result +# Check user role remove +- name: test - Remove Zabbix role + community.zabbix.zabbix_user_role: + state: absent + name: Operators + register: create_zabbix_user_role_result - - assert: - that: - - create_zabbix_user_role_result.changed is sameas true +- ansible.builtin.assert: + that: + - create_zabbix_user_role_result.changed is sameas true - - name: test - Create a new Zabbix role type Admin - zabbix_user_role: - state: present - name: Admins - type: Admin - rules: - ui.default_access: 0 - register: create_zabbix_user_role_admin_result +- name: test - Create a new Zabbix role type Admin + community.zabbix.zabbix_user_role: + state: present + name: Admins + type: Admin + rules: + ui.default_access: 0 + register: create_zabbix_user_role_admin_result - - assert: - that: - - create_zabbix_user_role_admin_result.changed is sameas true +- ansible.builtin.assert: + that: + - create_zabbix_user_role_admin_result.changed is sameas true - - name: test - Remove Zabbix role type Admin - zabbix_user_role: - state: absent - name: Admins +- name: test - Remove Zabbix role type Admin + community.zabbix.zabbix_user_role: + state: absent + name: Admins - - name: test - Create a new Zabbix role type Super Admin - zabbix_user_role: - state: present - name: Super Admins - type: Super Admin - rules: - ui.default_access: 0 - register: create_zabbix_user_role_super_admin_result +- name: test - Create a new Zabbix role type Super Admin + community.zabbix.zabbix_user_role: + state: present + name: Super Admins + type: Super Admin + rules: + ui.default_access: 0 + register: create_zabbix_user_role_super_admin_result - - assert: - that: - - create_zabbix_user_role_super_admin_result.changed is sameas true +- ansible.builtin.assert: + that: + - create_zabbix_user_role_super_admin_result.changed is sameas true - - name: test - Remove Zabbix role type Super Admin - zabbix_user_role: - state: absent - name: Super Admins +- name: test - Remove Zabbix role type Super Admin + community.zabbix.zabbix_user_role: + state: absent + name: Super Admins diff --git a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_usergroup/tasks/main.yml b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_usergroup/tasks/main.yml index f7a6aa60e..d1922315b 100644 --- a/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_usergroup/tasks/main.yml +++ b/ansible_collections/community/zabbix/tests/integration/targets/test_zabbix_usergroup/tasks/main.yml @@ -1,278 +1,273 @@ --- -- name: test - do not run tests for Zabbix 3.0 - meta: end_play - when: zabbix_version is version('3.0', '=') - - name: test - Zabbix user group module_defaults: community.zabbix.zabbix_usergroup: name: ACME block: - - name: test - create new Zabbix user group - zabbix_usergroup: - state: present - register: usergroup_new - - - name: assert that user group was created - assert: - that: usergroup_new is changed - - - name: test - create new Zabbix user group (again) - zabbix_usergroup: - state: present - register: usergroup_again - - - name: assert that user group was created - assert: - that: not usergroup_again is changed - - - name: test - update Zabbix user group with disabled gui_access - zabbix_usergroup: - gui_access: disable - register: usergroup_updated - - - name: assert that user group was updated - assert: - that: usergroup_updated is changed - - - name: test - update Zabbix user group with disabled gui_access (again) - zabbix_usergroup: - gui_access: disable - register: usergroup_updated_again - - - name: assert that user group was updated - assert: - that: not usergroup_updated_again is changed - - - name: test - reset Zabbix user group to default - zabbix_usergroup: - register: usergroup_reset - - - name: assert that user group was created - assert: - that: usergroup_reset is changed - - - when: zabbix_version is version('6.2', '<') - block: - - name: test - update Zabbix user group with one right - zabbix_usergroup: - rights: - - host_group: Discovered hosts - permission: read-only - register: usergroup_updated_right + - name: test - create new Zabbix user group + community.zabbix.zabbix_usergroup: + state: present + register: usergroup_new - - name: assert that user group was updated - assert: - that: usergroup_updated_right is changed + - name: assert that user group was created + ansible.builtin.assert: + that: usergroup_new is changed - - name: test - update Zabbix user group with multiple rights - zabbix_usergroup: - rights: - - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - register: usergroup_updated_rights + - name: test - create new Zabbix user group (again) + community.zabbix.zabbix_usergroup: + state: present + register: usergroup_again - - name: assert that user group was updated - assert: - that: usergroup_updated_rights is changed + - name: assert that user group was created + ansible.builtin.assert: + that: not usergroup_again is changed - - name: test - update Zabbix user group with multiple rights (again) - zabbix_usergroup: - rights: - - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - register: usergroup_updated_rights_again - - - name: assert that user group was not updated - assert: - that: not usergroup_updated_rights_again is changed - - - when: zabbix_version is version('6.2', '>=') - block: - - name: test - update Zabbix user group with one hostgroup right - zabbix_usergroup: - hostgroup_rights: - - host_group: Discovered hosts - permission: read-only - register: usergroup_updated_hostgroup_right + - name: test - update Zabbix user group with disabled gui_access + community.zabbix.zabbix_usergroup: + gui_access: disable + register: usergroup_updated - name: assert that user group was updated - assert: - that: usergroup_updated_hostgroup_right is changed + ansible.builtin.assert: + that: usergroup_updated is changed - - name: test - update Zabbix user group with multiple hostgroup rights - zabbix_usergroup: - hostgroup_rights: - - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - register: usergroup_updated_hostgroup_rights + - name: test - update Zabbix user group with disabled gui_access (again) + community.zabbix.zabbix_usergroup: + gui_access: disable + register: usergroup_updated_again - name: assert that user group was updated - assert: - that: usergroup_updated_hostgroup_rights is changed - - - name: test - update Zabbix user group with multiple hostgroup rights (again) - zabbix_usergroup: - hostgroup_rights: - - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - register: usergroup_updated_hostgroup_rights_again - - - name: assert that user group was not updated - assert: - that: not usergroup_updated_hostgroup_rights_again is changed - - - name: test - update Zabbix user group with one template group right - zabbix_usergroup: - hostgroup_rights: + ansible.builtin.assert: + that: not usergroup_updated_again is changed + + - name: test - reset Zabbix user group to default + community.zabbix.zabbix_usergroup: + register: usergroup_reset + + - name: assert that user group was created + ansible.builtin.assert: + that: usergroup_reset is changed + + - when: zabbix_version is version('6.2', '<') + block: + - name: test - update Zabbix user group with one right + community.zabbix.zabbix_usergroup: + rights: + - host_group: Discovered hosts + permission: read-only + register: usergroup_updated_right + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_updated_right is changed + + - name: test - update Zabbix user group with multiple rights + community.zabbix.zabbix_usergroup: + rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + register: usergroup_updated_rights + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_updated_rights is changed + + - name: test - update Zabbix user group with multiple rights (again) + community.zabbix.zabbix_usergroup: + rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + register: usergroup_updated_rights_again + + - name: assert that user group was not updated + ansible.builtin.assert: + that: not usergroup_updated_rights_again is changed + + - when: zabbix_version is version('6.2', '>=') + block: + - name: test - update Zabbix user group with one hostgroup right + community.zabbix.zabbix_usergroup: + hostgroup_rights: + - host_group: Discovered hosts + permission: read-only + register: usergroup_updated_hostgroup_right + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_updated_hostgroup_right is changed + + - name: test - update Zabbix user group with multiple hostgroup rights + community.zabbix.zabbix_usergroup: + hostgroup_rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + register: usergroup_updated_hostgroup_rights + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_updated_hostgroup_rights is changed + + - name: test - update Zabbix user group with multiple hostgroup rights (again) + community.zabbix.zabbix_usergroup: + hostgroup_rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + register: usergroup_updated_hostgroup_rights_again + + - name: assert that user group was not updated + ansible.builtin.assert: + that: not usergroup_updated_hostgroup_rights_again is changed + + - name: test - update Zabbix user group with one template group right + community.zabbix.zabbix_usergroup: + hostgroup_rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + templategroup_rights: + - template_group: Templates + permission: read-only + register: usergroup_updated_templategroup_right + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_updated_templategroup_right is changed + + - name: test - update Zabbix user group with multiple template group rights + community.zabbix.zabbix_usergroup: + hostgroup_rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + templategroup_rights: + - template_group: Templates + permission: read-only + - template_group: Templates/Applications + permission: read-write + register: usergroup_updated_templategroup_rights + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_updated_templategroup_right is changed + + - name: test - update Zabbix user group with multiple template group rights (again) + community.zabbix.zabbix_usergroup: + hostgroup_rights: + - host_group: Discovered hosts + permission: read-only + - host_group: Zabbix servers + permission: read-write + templategroup_rights: + - template_group: Templates + permission: read-only + - template_group: Templates/Applications + permission: read-write + register: usergroup_updated_templategroup_rights_again + + - name: assert that user group was not updated + ansible.builtin.assert: + that: not usergroup_updated_templategroup_rights_again is changed + + - name: test - reset Zabbix user group to default + community.zabbix.zabbix_usergroup: + register: usergroup_reset + + - name: assert that user group was created + ansible.builtin.assert: + that: usergroup_reset is changed + + - name: test - update Zabbix user group with one tag_filter + community.zabbix.zabbix_usergroup: + tag_filters: - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - templategroup_rights: - - template_group: Templates - permission: read-only - register: usergroup_updated_templategroup_right + tag: Service + value: JIRA + register: usergroup_updated_tag_filter - name: assert that user group was updated - assert: - that: usergroup_updated_templategroup_right is changed + ansible.builtin.assert: + that: usergroup_updated_tag_filter is changed - - name: test - update Zabbix user group with multiple template group rights - zabbix_usergroup: - hostgroup_rights: + - name: test - update Zabbix user group with multiple tag_filters + community.zabbix.zabbix_usergroup: + tag_filters: - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - templategroup_rights: - - template_group: Templates - permission: read-only - - template_group: Templates/Applications - permission: read-write - register: usergroup_updated_templategroup_rights - - - name: assert that user group was updated - assert: - that: usergroup_updated_templategroup_right is changed - - - name: test - update Zabbix user group with multiple template group rights (again) - zabbix_usergroup: - hostgroup_rights: + tag: Service + value: JIRA - host_group: Discovered hosts - permission: read-only - - host_group: Zabbix servers - permission: read-write - templategroup_rights: - - template_group: Templates - permission: read-only - - template_group: Templates/Applications - permission: read-write - register: usergroup_updated_templategroup_rights_again - - - name: assert that user group was not updated - assert: - that: not usergroup_updated_templategroup_rights_again is changed - - - name: test - reset Zabbix user group to default - zabbix_usergroup: - register: usergroup_reset - - - name: assert that user group was created - assert: - that: usergroup_reset is changed - - - name: test - update Zabbix user group with one tag_filter - zabbix_usergroup: - tag_filters: - - host_group: Discovered hosts - tag: Service - value: JIRA - register: usergroup_updated_tag_filter - - - name: assert that user group was updated - assert: - that: usergroup_updated_tag_filter is changed - - - name: test - update Zabbix user group with multiple tag_filters - zabbix_usergroup: - tag_filters: - - host_group: Discovered hosts - tag: Service - value: JIRA - - host_group: Discovered hosts - tag: Service - value: Zabbix - register: usergroup_updated_tag_filters - - - name: assert that user group was updated - assert: - that: usergroup_updated_tag_filters is changed - - - name: test - reset Zabbix user group to default - zabbix_usergroup: - - - when: zabbix_version is version('6.2', '>=') - block: - - name: test - create new user directory - zabbix_user_directory: - name: LDAP infra 1 - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - when: zabbix_version is version('6.4', '<') - - - name: test - create new user directory - zabbix_user_directory: - name: LDAP infra 1 - idp_type: ldap - host: 'test.com' - port: 389 - base_dn: 'ou=Users,dc=example,dc=org' - search_attribute: 'uid' - when: zabbix_version is version('6.4', '>=') - - - name: test - update Zabbix user group with user directory - zabbix_usergroup: - userdirectory: LDAP infra 1 - register: usergroup_create_userdir + tag: Service + value: Zabbix + register: usergroup_updated_tag_filters - name: assert that user group was updated - assert: - that: usergroup_create_userdir is changed - - - name: test - update Zabbix user group with user directory (again) - zabbix_usergroup: - userdirectory: LDAP infra 1 - register: usergroup_create_userdir_again - - - name: assert that user group was not updated - assert: - that: not usergroup_create_userdir_again is changed - - - name: test - delete Zabbix user group - zabbix_usergroup: - state: absent - register: usergroup_delete - - - name: assert that Zabbix user group has been deleted - assert: - that: usergroup_delete is changed - - - - name: test - delete user directory - zabbix_user_directory: - name: LDAP infra 1 - host: 'test.com' - state: absent - when: zabbix_version is version('6.2', '>=') + ansible.builtin.assert: + that: usergroup_updated_tag_filters is changed + + - name: test - reset Zabbix user group to default + community.zabbix.zabbix_usergroup: + + - when: zabbix_version is version('6.2', '>=') + block: + - name: test - create new user directory + community.zabbix.zabbix_user_directory: + name: LDAP infra 1 + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + when: zabbix_version is version('6.4', '<') + + - name: test - create new user directory + community.zabbix.zabbix_user_directory: + name: LDAP infra 1 + idp_type: ldap + host: "test.com" + port: 389 + base_dn: "ou=Users,dc=example,dc=org" + search_attribute: "uid" + when: zabbix_version is version('6.4', '>=') + + - name: test - update Zabbix user group with user directory + community.zabbix.zabbix_usergroup: + userdirectory: LDAP infra 1 + register: usergroup_create_userdir + + - name: assert that user group was updated + ansible.builtin.assert: + that: usergroup_create_userdir is changed + + - name: test - update Zabbix user group with user directory (again) + community.zabbix.zabbix_usergroup: + userdirectory: LDAP infra 1 + register: usergroup_create_userdir_again + + - name: assert that user group was not updated + ansible.builtin.assert: + that: not usergroup_create_userdir_again is changed + + - name: test - delete Zabbix user group + community.zabbix.zabbix_usergroup: + state: absent + register: usergroup_delete + + - name: assert that Zabbix user group has been deleted + ansible.builtin.assert: + that: usergroup_delete is changed + + - name: test - delete user directory + community.zabbix.zabbix_user_directory: + name: LDAP infra 1 + host: "test.com" + state: absent + when: zabbix_version is version('6.2', '>=') diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.10.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.10.txt deleted file mode 100644 index 8854fcd2d..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.10.txt +++ /dev/null @@ -1,34 +0,0 @@ -scripts/inventory/zabbix.py future-import-boilerplate -scripts/inventory/zabbix.py metaclass-boilerplate -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements -plugins/doc_fragments/zabbix.py future-import-boilerplate -plugins/doc_fragments/zabbix.py metaclass-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_agent.py future-import-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_default.py future-import-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_agent.py metaclass-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_default.py metaclass-boilerplate
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.11.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.11.txt deleted file mode 100644 index 8854fcd2d..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.11.txt +++ /dev/null @@ -1,34 +0,0 @@ -scripts/inventory/zabbix.py future-import-boilerplate -scripts/inventory/zabbix.py metaclass-boilerplate -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements -plugins/doc_fragments/zabbix.py future-import-boilerplate -plugins/doc_fragments/zabbix.py metaclass-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_agent.py future-import-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_default.py future-import-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_agent.py metaclass-boilerplate -roles/zabbix_agent/molecule/with-server/tests/test_default.py metaclass-boilerplate
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.12.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.12.txt deleted file mode 100644 index 628f32ff1..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.12.txt +++ /dev/null @@ -1,26 +0,0 @@ -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.13.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.13.txt deleted file mode 100644 index 628f32ff1..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.13.txt +++ /dev/null @@ -1,26 +0,0 @@ -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.14.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.14.txt deleted file mode 100644 index 628f32ff1..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.14.txt +++ /dev/null @@ -1,26 +0,0 @@ -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.15.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.15.txt deleted file mode 100644 index 628f32ff1..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.15.txt +++ /dev/null @@ -1,26 +0,0 @@ -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements
\ No newline at end of file diff --git a/ansible_collections/community/zabbix/tests/sanity/ignore-2.9.txt b/ansible_collections/community/zabbix/tests/sanity/ignore-2.9.txt deleted file mode 100644 index 0b5abb56b..000000000 --- a/ansible_collections/community/zabbix/tests/sanity/ignore-2.9.txt +++ /dev/null @@ -1,30 +0,0 @@ -scripts/inventory/zabbix.py future-import-boilerplate -scripts/inventory/zabbix.py metaclass-boilerplate -plugins/modules/zabbix_action.py validate-modules:doc-choices-do-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-default-does-not-match-spec -plugins/modules/zabbix_action.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_action.py validate-modules:doc-required-mismatch -plugins/modules/zabbix_action.py validate-modules:invalid-argument-name -plugins/modules/zabbix_action.py validate-modules:missing-suboption-docs -plugins/modules/zabbix_action.py validate-modules:nonexistent-parameter-documented -plugins/modules/zabbix_action.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_action.py validate-modules:parameter-type-not-in-doc -plugins/modules/zabbix_action.py validate-modules:undocumented-parameter -plugins/modules/zabbix_group.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_group_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_group_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_host_info.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_host_info.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_maintenance.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_maintenance.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_mediatype.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_mediatype.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_template.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_template.py validate-modules:parameter-list-no-elements -plugins/modules/zabbix_user.py validate-modules:doc-elements-mismatch -plugins/modules/zabbix_user.py validate-modules:parameter-list-no-elements -plugins/doc_fragments/zabbix.py future-import-boilerplate -plugins/doc_fragments/zabbix.py metaclass-boilerplate
\ No newline at end of file |