
    VhH                         d dl mZmZmZ eZdZdZd dlm	Z	 d dl
mZ d dlmc mc mc mc mZ  G d de      Zd	 Zed
k(  r e        yy)    )absolute_importdivisionprint_functiona  
---
module: zabbix_discoveryrule
short_description: Create/delete Zabbix low-level discovery (LLD) rules
description:
   - Create discoveryrules if they do not exist.
   - Delete existing discoveryrules if they exist.
author:
    - "Andrew Lathrop (@aplathrop)"
requirements:
    - "python >= 2.6"

options:
    state:
        description:
            - Create or delete discovery rule.
        required: false
        type: str
        default: "present"
        choices: [ "present", "absent" ]
    name:
        description:
            - Name of discovery rule to create or delete.
        required: true
        type: str
    host_name:
        description:
            - Name of host to add discovery rule to.
            - Required when I(template_name) is not used.
            - Mutually exclusive with I(template_name).
        required: false
        type: str
    template_name:
        description:
            - Name of template to add discovery rule to.
            - Required when I(host_name) is not used.
            - Mutually exclusive with I(host_name).
        required: false
        type: str
    params:
        description:
            - Parameters to create/update discovery rule with.
            - Required if state is "present".
            - Parameters as defined at https://www.zabbix.com/documentation/current/en/manual/api/reference/discoveryrule/object
            - Additionally supported parameters are below
        required: false
        type: dict
        suboptions:
            key:
                description:
                    - LLD rule key.
                    - Alias for "key_" in API docs
                required: false
                type: str
            interval:
                description:
                    - Update interval of the LLD rule.
                    - Alias for "delay" in API docs
                required: false
                type: str
            status:
                description:
                    - Status of the LLD rule.
                required: false
                type: str
                choices: [ "enabled", "disabled" ]
            enabled:
                description:
                    - Status of the LLD rule.
                    - Overrides "status" in API docs
                required: false
                type: bool
            type:
                description:
                    - Type of the LLD rule.
                    - Required if state is "present".
                required: false
                type: str
                choices:
                    - zabbix_agent
                    - zabbix_trapper
                    - simple_check
                    - zabbix_internal
                    - zabbix_agent_active
                    - web_item
                    - external_check
                    - database_monitor
                    - ipmi_agent
                    - ssh_agent
                    - telnet_agent
                    - calculated
                    - jmx_agent
                    - snmp_trap
                    - dependent_item
                    - http_agent
                    - snmp_agent
                    - script
            new_name:
                description:
                    - New name for LLD rule.
                required: false
                type: str
            preprocessing:
                description:
                    - discovery rules preprocessing options.
                    - Parameters as defined at https://www.zabbix.com/documentation/current/en/manual/api/reference/discoveryrule/object#lld-rule-preprocessing
                    - Additionally supported parameters are below
                required: false
                type: list
                elements: dict
                suboptions:
                    type:
                        description:
                            - The preprocessing option type.
                        required: true
                        type: str
                        choices:
                            - xml_xpath
                            - jsonpath
                            - does_not_match_regular_expression
                            - not_match_regex
                            - check_for_error_in_json
                            - check_for_json_error
                            - check_for_error_in_xml
                            - check_for_xml_error
                            - discard_unchanged_with_heartbeat
                            - javascript
                            - prometheus_to_json
                            - csv_to_json
                            - replace
                            - xml_to_json
                            - snmp_walk_value
                            - snmp_walk_to_json
                    error_handler:
                        description:
                            - Action type used in case of preprocessing step failure.
                        required: false
                        type: str
                        choices:
                            - zabbix_server
                            - discard
                            - set_custom_value
                            - set_custom_error_message

extends_documentation_fragment:
- community.zabbix.zabbix
ao  

# 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

# Create LLD rule on example_host
- name: create rule
  # 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_discoveryrule:
    name: mounted_filesystem_discovery
    host_name: example_host
    params:
        type: zabbix_agent
        key: 'vfs.fs.discovery'
        interval: 1h
        enabled: True
    state: present

# Create LLD rule on example_template
- name: create rule
  # 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_discoveryrule:
    name: mounted_filesystem_discovery
    template_name: example_template
    params:
        type: zabbix_agent
        key: 'vfs.fs.discovery'
        interval: 1h
        enabled: True
    state: present

# Change interval for existing Zabbix LLD rule
- name: update rule
  # 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_discoveryrule:
    name: mounted_filesystem_discovery
    template_name: example_template
    params:
        interval: 2h
    state: present

# Delete LLD rule
- name: delete rule
  # 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_discoveryrule:
    name: mounted_filesystem_discovery
    template_name: example_template
    state: absent

- name: Rename Zabbix LLD rule
  # 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_discoveryrule:
    name: mounted_filesystem_discovery
    template_name: example_template
    params:
      new_name: new_mounted_filesystem_discovery
    state: present
)AnsibleModule)
ZabbixBaseNc                       e Zd Zi ddddddddd	d
dddddddddddddddddddddd d!d"d#d$iZi d%dd&dd'dd(dd)dd*dd+dd,dd-dd.d"d/d$d0d1d2d3d4d5d6d7d8d9d:d;Zdd<ddd=Zd> Zd? Zd@ ZdA Z	dB Z
dC ZdD ZyE)FDiscoveryrulezabbix_agentr   zabbix_trapper   simple_check   zabbix_internal   zabbix_agent_active   web_item	   external_check
   database_monitor   
ipmi_agent   	ssh_agent   telnet_agent   
calculated   	jmx_agent   	snmp_trap   dependent_item   
http_agent   
snmp_agent   script   regex	xml_xpathjsonpath!does_not_match_regular_expressionnot_match_regexcheck_for_error_in_jsoncheck_for_json_errorcheck_for_error_in_xmlcheck_for_xml_error discard_unchanged_with_heartbeat
javascriptprometheus_to_json   csv_to_json   replace   xml_to_json   snmp_walk_value   snmp_walk_to_json      )zabbix_serverdiscardset_custom_valueset_custom_error_messagec                    |*	 | j                   j                  j                  dd|ii      S 	 | j                   j                  j                  dd|ii      S # t        $ r)}| j                  j                  d|z         Y d }~y d }~ww xY w# t        $ r)}| j                  j                  d|z         Y d }~y d }~ww xY w)NfilterhostzFailed to get host: %smsgzFailed to get template: %s)_zapirK   get	Exception_module	fail_jsontemplate)self	host_nametemplate_namees       y/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/zabbix/plugins/modules/zabbix_discoveryrule.pyget_hosts_templatesz!Discoveryrule.get_hosts_templates;  s     Izz**Hvy6I+JKKMzz**..6=:Q/RSS	  I&&+Ca+G&HHI
  M&&+G!+K&LLMs.   (A (B 	B	 BB		B>B99B>c                     ||}n|}g }	 | j                   j                  j                  d||di      }|S # t        $ r*}| j                  j                  d|z         Y d }~|S d }~ww xY w)NrJ   )namerK   z!Failed to get discovery rules: %srL   rN   discoveryrulerO   rP   rQ   rR   )rT   discoveryrule_namerU   rV   rK   discoveryrulesrW   s          rX   get_discoveryrulesz Discoveryrule.get_discoveryrulesG  s     D D	P!ZZ55998N`jnEo:pqN   	PLL""'JQ'N"OO	Ps   *7 	A* A%%A*c                    ||d<   d|v r|d   |d<   |j                  d       d|v r| j                  |d      }||d<   d|v r|d   |d<   |j                  d       d|v r!|d   rd|d<   nd	|d<   |j                  d       d|v r:|d   }|dk(  rd
|d<   n*|d	k(  rd|d<   n| j                  j                  d|z         d|v r>|d   D ]5  }| j                  |d      }||d<   d|v s| j
                  |d      }||d<   7 y y )Nr[   keykey_typeintervaldelayenabledstatusdisabledr   rD   z.Status must be 'enabled' or 'disabled', got %srL   preprocessingerror_handler)pop
ITEM_TYPESrQ   rR   PREPROCESSING_TYPESPREPROCESSING_ERROR_HANDLERS)rT   r[   paramsitem_type_intrh   parampreprocess_type_interror_handler_ints           rX   sanitize_paramszDiscoveryrule.sanitize_paramsS  sZ   vF?#E]F6NJJuV OOF6N;M*F6N$Z0F7OJJz"i #,x #-x JJy!vH%F"#$x :%#$x &&+[^d+d&ef$0 ?&*&>&>uV}&M# 3f"e+(,(I(I%P_J`(a%->E/*? %    c                 "   | j                   j                  r| j                   j                  d       	 | j                  j                  j                  |      }|S # t        $ r*}| j                   j                  d|z         Y d }~S d }~ww xY w)NTchangedz"Failed to create discoveryrule: %srL   )rQ   
check_mode	exit_jsonrN   r]   createrP   rR   rT   rp   resultsrW   s       rX   add_discoveryrulezDiscoveryrule.add_discoveryrulet      <<""LL""4"0	Qjj..55f=G   	QLL""'Ka'O"PP	Q   %A 	B$B		Bc                 "   | j                   j                  r| j                   j                  d       	 | j                  j                  j                  |      }|S # t        $ r*}| j                   j                  d|z         Y d }~S d }~ww xY w)NTrx   z"Failed to update discoveryrule: %srL   )rQ   rz   r{   rN   r]   updaterP   rR   r}   s       rX   update_discoveryrulez"Discoveryrule.update_discoveryrule}  r   r   c                     	 | j                   j                  j                  dd|d   z  i      d   }||k7  S # t        $ r-}| j                  j                  d|z         Y d }~|k7  S d }~ww xY w)Nitemidsz%sitemidr   zFailed to get discoveryrule: %srL   r\   )rT   old_discoveryrulenew_discoveryrulerW   s       rX   check_discoveryrule_changedz)Discoveryrule.check_discoveryrule_changed  s    	N $

 8 8 < <iPabjPkIk=l mno p !$555  	NLL""'H1'L"MM $555	Ns   07 	A- A((A-c                 "   | j                   j                  r| j                   j                  d       	 | j                  j                  j                  |      }|S # t        $ r*}| j                   j                  d|z         Y d }~S d }~ww xY w)NTrx   z"Failed to delete discoveryrule: %srL   )rQ   rz   r{   rN   r]   deleterP   rR   )rT   discoveryrule_idr~   rW   s       rX   delete_discoveryrulez"Discoveryrule.delete_discoveryrule  s    <<""LL""4"0	Qjj..556FGG   	QLL""'Ka'O"PP	Qr   N)__name__
__module____qualname__rm   rn   ro   rY   r`   ru   r   r   r   r    rv   rX   r	   r	     s    .!  "A  !  $Q  (	 
 a  #B  %b    r  !"    r  r  #B     ! " B# J&47A 4&4%r4 ?4 -b	4
 5b4 224 4R4 1"4 >r4 (4 04 )"4 %b4 )"4 -b4  /!4$ 67/089@A$C 

M
?B6rv   r	   c                     t        j                         } | j                  t        t        dd      t        dd      t        dd      t        dd      t        ddddg      	             t	        | d
dggd
dggdddgggd      }|j
                  d   }|j
                  d
   }|j
                  d   }|j
                  d   }|j
                  d   }t        |      }|dk(  rw|j                  |||      }t        |      dk(  r|j                  dd       y g }	|D ]  }
|	j                  |
d           |j                  |	      }|j                  d|       y |dk(  r|j                  ||       |j                  |||      }d|v rA|j                  |d   ||      }t        |      dkD  r|j                  dd|d   d   gig       g }t        |      dk(  rd|v r|j                  d|z         |j                  ||      }|D ]N  }d|v r	|d   |d<   nd|v r	|d   |d<   n|j                  d       |j                  |j                  |             P |j                  d|       y d}|D ]]  }
|
d   |d<   d|v r|d   |d<   |j!                  d       |j                  |j#                  |             |j%                  |
      }|s\d}_ |j                  ||       y y )NstrT)rd   requiredFdictpresentabsent)rd   defaultchoices)r[   rU   rV   rp   staterU   rV   r   rp   )argument_specrequired_one_ofmutually_exclusiverequired_ifsupports_check_moder[   r   zNo discoveryrule to delete.)ry   resultr   new_namer   z-Cannot rename discoveryrule:  %s is not foundhostid
templateidzhost/template did not return idrL   )zabbix_utilszabbix_common_argument_specr   r   r   rp   r	   r`   lenr{   appendr   ru   rR   rY   r   rl   r   r   )r   moduler[   rU   rV   rp   r   r]   r_   
delete_idsdr~   new_name_discoveryrulehosts_templateshost_templatery   changed_rules                    rX   mainr     sN    <<>Mut,EE26%0y9h:OP  #/*
 /*
 i(,
 !F == Dk*IMM/2M]]8$FMM'"E!&)M&99$	=Y~!#U3PQJ# /!!!H+./#88DGT':	)	%%dF3&99$	=Y%2%E%EfZFXZcer%s")*Q.  E[\]E^_gEhDi8j7k l~!#V#  !PSW!WX+??	=YO!0 H},'4X'>F8$!]2'4\'BF8$$$)J$K}>>vFGH T':G# ##$X;x '%+J%7F6NJJz*}AA&IJ,HHK"G# WW=A 
rv   __main__)
__future__r   r   r   rd   __metaclass__DOCUMENTATIONEXAMPLESansible.module_utils.basicr   >ansible_collections.community.zabbix.plugins.module_utils.baser   Aansible_collections.community.zabbix.plugins.module_utils.helpers	communityzabbixpluginsmodule_utilshelpersr   r	   r   r   r   rv   rX   <module>r      s`    A @RhjX 5 U X X XDJ DNJ>Z zF rv   