
    Vh'                         d dl mZmZmZ eZd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 d Zd	 Zd
 Z G d de      Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona  
---
module: zabbix_valuemap
short_description: Create/update/delete Zabbix value maps
description:
    - This module allows you to create, modify and delete Zabbix value maps.
author:
    - "Ruben Tsirunyan (@rubentsirunyan)"
requirements:
    - "python >= 3.9"
options:
    name:
        type: "str"
        description:
            - Name of the value map.
        required: true
    state:
        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"
    mappings:
        type: "list"
        elements: dict
        description:
            - List of value mappings for the value map.
            - Required when I(state=present).
        suboptions:
            value:
                type: "str"
                description: Original value.
                required: true
            map_to:
                type: "str"
                description: Value to which the original value is mapped to.
                required: true

extends_documentation_fragment:
- community.zabbix.zabbix


a  
# 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 a value map
  # 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_valuemap:
    name: Numbers
    mappings:
      - value: 1
        map_to: one
      - value: 2
        map_to: two
    state: present
)AnsibleModule)
ZabbixBaseNc                      | d   t        | d         S t        | d   | d   D cg c]  }t        |d   |d          c}      S c c}w )zTranslates data to a format suitable for Zabbix API

    Args:
        **kwargs: Arguments passed to the module.

    Returns:
        A dictionary of arguments in a format that is understandable by Zabbix API.
    mappingsnamer   valuemap_to)r   newvaluer   r
   )dict)kwargsmappings     t/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/zabbix/plugins/modules/zabbix_valuemap.pyconstruct_parametersr   b   sr     j!
 	
 F^
 $J/	
  g& *
 
s   A
c                 X    i }i }|D ]  }| |   ||<   ||   d||<   ||   ||<    ||dS )a  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}
        with filtered empty values.
     )beforeafter )existingnewr   r   keys        r   diffr   {   sW     FE "smss8E#JSE#J" u--    c                 x    i }t        | d   d       t        |d   d       k7  r|d   |d<   |t        | |      fS )a  Filters only the parameters that are different and need to be updated.

    Args:
        existing_valuemap (dict): Existing valuemap.
        **kwargs: Parameters for the new valuemap.

    Returns:
        A tuple where the first element is a dictionary of parameters
        that need to be updated and the second one is a dictionary
        returned by diff() function with
        existing valuemap data and new params passed to it.
    r
   c                     | d   S Nr   r   ks    r   <lambda>z#get_update_params.<locals>.<lambda>   s
    1W: r   )r   c                     | d   S r"   r   r#   s    r   r%   z#get_update_params.<locals>.<lambda>   s    stu|s} r   )sortedr   )existing_valuemapr   params_to_updates      r   get_update_paramsr*      sR     
+1EF&QWXbQci}J~~'-j'9$T"3V<<<r   c                   $    e Zd Zd Zd Zd Zd Zy)ValuemapModulec                    	 | j                   j                  j                  ddd|gid      }t        |      dk  ryd|d   fS # t        $ r7}| j
                  j                  dj                  ||	      
       Y d}~yd}~ww xY w)a  Checks if value map exists.

        Args:
            name: Zabbix valuemap name

        Returns:
            tuple: First element is True if valuemap exists and False otherwise.
                Second element is a dictionary of valuemap object if it exists.
        extendr   )outputselectMappingsfilter   )FNTr   z.Failed to get ID of the valuemap '{name}': {e}r   emsgN)_zapivaluemapgetlen	Exception_module	fail_jsonformat)selfr   valuemap_listr4   s       r   check_if_valuemap_existsz'ValuemapModule.check_if_valuemap_exists   s    	p JJ//33""*!D6*5 M
 =!A%"]1--- 	pLL""'W'^'^dhlm'^'n"oo	ps   :A A 	B-A??Bc                     	 | j                   j                  j                  |g      S # t        $ r7}| j                  j                  dj                  ||             Y d }~y d }~ww xY w)Nz&Failed to delete valuemap '{_id}': {e}_idr4   r5   )r7   r8   deleter;   r<   r=   r>   )r?   valuemap_idr4   s      r   rE   zValuemapModule.delete   sb    	n::&&--{m<< 	nLL""'O'V'V[fjk'V'l"mm	ns   %( 	A(-A##A(c                     	 | j                   j                  j                  |       y # t        $ r:}| j                  j                  dj                  |d   |             Y d }~y d }~ww xY w)Nz&Failed to update valuemap '{_id}': {e}
valuemapidrC   r5   )r7   r8   updater;   r<   r=   r>   r?   r   r4   s      r   rI   zValuemapModule.update   sc    	wJJ&&v. 	wLL""'O'V'V[abn[ost'V'u"vv	w   %( 	A+0A&&A+c                     	 | j                   j                  j                  |       y # t        $ r:}| j                  j                  dj                  |d   |             Y d }~y d }~ww xY w)Nz'Failed to create valuemap '{name}': {e}descriptionr3   r5   )r7   r8   creater;   r<   r=   r>   rJ   s      r   rN   zValuemapModule.create   sc    	zJJ&&v. 	zLL""'P'W'W]cdq]rvw'W'x"yy	zrK   N)__name__
__module____qualname__rA   rE   rI   rN   r   r   r   r,   r,      s    p.nwzr   r,   c                     t        j                         } | j                  t        t        dd      t        ddddg      t        ddt        t        dd      t        dd      	      
                   t	        | ddddggg      }t        |      }|j                  d   }|j                  d   }|j                  d   }|j                  |      \  }}t        ||      }|r|d   }	|dk(  rf|j                  r$|j                  ddj                  ||	             |j                  |	      }	|j                  ddj                  ||	             y t        |fi |\  }
}|
i k(  r$|j                  ddj                  |             y |j                  r%|j                  d|dj                  ||	              |j                  dd|	i|
}	|j                  d|dj                  ||	             y |dk(  r|j                  d       y |j                  r$|j                  ddj                  |	              |j                  di |}	|j                  ddj                  ||	             y ) NstrT)typerequiredpresentabsent)rT   defaultchoiceslistr   )r   r   )rT   elementsoptions)r   stater
   r]   r
   )argument_specsupports_check_moderequired_ifr   r   rH   z:Value map would have been deleted. Name: {name}, ID: {_id})r   rD   )changedr6   z*Value map deleted. Name: {name}, ID: {_id}FzValue map is up to date: {name}r   z:Value map would have been updated. Name: {name}, ID: {_id})ra   r   r6   z*Value map updated. Name: {name}, ID: {_id})ra   z:Value map would have been created. Name: {name}, ID: {_id}z$Value map created: {name}, ID: {_id}r   )zabbix_utilszabbix_common_argument_specrI   r   r   r,   paramsrA   r   
check_mode	exit_jsonr>   rE   r*   rN   )r^   modulevmr   r]   r
   valuemap_existsvaluemap_object
parametersrF   r)   r   s               r   mainrl      s    <<>Mut,y9h:OP56
  # i*.
F 
	B== DMM'"E}}Z(H')'B'B4'H$O_%J
 %l3H     T[[!' \  !  ))K0K@GG# H    &7%U*%U"d2%  !9@@d@K ! 
 $$$$ $!X__!% + `  %  (biiS;SBRS   DKK!' L  !  HU+     T[[!' \  !  $"))1j1K:AA# B   r   __main__)
__future__r   r   r   rT   __metaclass__DOCUMENTATIONRETURN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helpersrb   r   r   r*   r,   rl   rO   r   r   r   <module>r{      st    A @+Z
B 5 U X X X2..=((zZ (zVcL zF r   