
    VhR0                    x    d dl mZ dZdZd dlZd dlmZ d dlmZm	Z	 d dl
mZ d dlmZ d d	lmZ  G d
 dee	      Zy)    )annotationsa  
name: icinga2
short_description: Icinga2 inventory source
version_added: 3.7.0
author:
  - Cliff Hults (@BongoEADGC6) <cliff.hults@gmail.com>
description:
  - Get inventory hosts from the Icinga2 API.
  - "Uses a configuration file as an inventory source, it must end in
    C(.icinga2.yml) or C(.icinga2.yaml)."
extends_documentation_fragment:
  - constructed
options:
  strict:
    version_added: 4.4.0
  compose:
    version_added: 4.4.0
  groups:
    version_added: 4.4.0
  keyed_groups:
    version_added: 4.4.0
  plugin:
    description: Name of the plugin.
    required: true
    type: string
    choices: ['community.general.icinga2']
  url:
    description: Root URL of Icinga2 API.
    type: string
    required: true
  user:
    description: Username to query the API.
    type: string
    required: true
  password:
    description: Password to query the API.
    type: string
    required: true
  host_filter:
    description:
      - An Icinga2 API valid host filter. Leave blank for no filtering
    type: string
    required: false
  validate_certs:
    description: Enables or disables SSL certificate verification.
    type: boolean
    default: true
  inventory_attr:
    description:
      - Allows the override of the inventory name based on different attributes.
      - This allows for changing the way limits are used.
      - The current default, V(address), is sometimes not unique or present. We recommend to use V(name) instead.
    type: string
    default: address
    choices: ['name', 'display_name', 'address']
    version_added: 4.2.0
  group_by_hostgroups:
    description:
      - Uses Icinga2 hostgroups as groups.
    type: boolean
    default: true
    version_added: 8.4.0
a  
# my.icinga2.yml
plugin: community.general.icinga2
url: http://localhost:5665
user: ansible
password: secure
host_filter: \"linux-servers\" in host.groups
validate_certs: false  # only do this when connecting to localhost!
inventory_attr: name
groups:
  # simple name matching
  webservers: inventory_hostname.startswith('web')

  # using icinga2 template
  databaseservers: "'db-template' in (icinga2_attributes.templates|list)"

compose:
  # set all icinga2 attributes to a host variable 'icinga2_attrs'
  icinga2_attrs: icinga2_attributes

  # set 'ansible_user' and 'ansible_port' from icinga2 host vars
  ansible_user: icinga2_attributes.vars.ansible_user
  ansible_port: icinga2_attributes.vars.ansible_port | default(22)
N)AnsibleParserError)BaseInventoryPluginConstructable)open_url)	HTTPError)make_unsafec                  p     e Zd ZdZdZ fdZ fdZd ZddZddZ	d Z
d	 Zd
 Zd Zd Zd fd	Z xZS )InventoryModulez< Host inventory parser for ansible using Icinga2 as source. zcommunity.general.icinga2c                    t         t        |           d | _        d | _        d | _        d | _        d | _        d | _        d | _	        d | _
        d | _        y N)superr   __init__icinga2_urlicinga2_usericinga2_password
ssl_verifyhost_filterinventory_attrgroup_by_hostgroups	cache_key	use_cache)self	__class__s    o/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/inventory/icinga2.pyr   zInventoryModule.__init__q   sW    ot-/    $"#'     c                    d}t         t        |   |      r0|j                  d      rd}|S | j                  j                  d       |S )NF)zicinga2.yamlzicinga2.ymlTzOSkipping due to inventory source not ending in "icinga2.yaml" nor "icinga2.yml")r   r   verify_fileendswithdisplayvvv)r   pathvalidr   s      r   r   zInventoryModule.verify_file   sJ    $3D9}}<=    !rsr   c                    ddd| _         | j                   d}| j                   | j                  | j                  | j                  d}t        |fi | y )Nzansible-icinga2-invzapplication/json)z
User-AgentAcceptz/statusheadersurl_usernameurl_passwordvalidate_certs)r'   r   r   r   r   r   )r   api_status_urlrequest_argss      r   _api_connectzInventoryModule._api_connect   s\    /(
 !,,-W5|| -- 11"oo	
 	0<0r   c                   | j                   j                  d|        | j                  | j                  | j                  | j
                  d}|t        j                  |      |d<   | j                   j                  d|        	 t        |fi |}|j                         }t        j                  |j                  d            }| j                   j                  dt        j                  |dd              d|j"                  cxk  rdk  r|S  |j"                  dk(  r&|d   dk(  rt!        d|j"                   d|d          |j"                  dk(  rt!        d|j"                   d|d          |j"                  dk(  rt!        d|d    d|d          t!        d|d    d|d          # t        $ r}	 t        j                  |j                         j                               }| j                   j                  d|        n# t        $ r dd i}Y nw xY w|j                  dk(  r|j                  d      dk(  rt!        d	      t!        d
| d|       d }~ww xY w)NzRequested URL: r&   datazRequest Args: zError returned: statusi  zNo objects found.zLHost filter returned no data. Please confirm your host_filter value is validzUnexpected data returned: z -- zutf-8zReturned Data:    T)indent	sort_keys   i+  z"API returned no data -- Response: z - i  z.API was unable to complete query -- Response: i  zAPI Response - errorszUnexpected data returned - )r    r!   r'   r   r   r   jsondumpsr   r   loadsreaddecode	Exceptioncodegetr   r0   )	r   request_urlr/   r,   responsee
error_bodyresponse_body	json_datas	            r   _post_requestzInventoryModule._post_request   s|   ?;-89|| -- 11"oo	
 #'::d#3L >,89
	W<|<H !JJ}33G<=	?4::iUY+Z*[\](//(S( )??c!i&9=P&P$4X__4ESS[I\H]^` `??c!$@@QQTU^_gUhTijl l??c!$!)H"5!6c)H:M9NOQ Q ))H*=)>c)HBUAVWY 	Y1  	W.!ZZ(9:
  #3J<!@A .&-
.vv}!9=P!P()wxx$'A!D%UVV	Ws8   F2 2	I#<AHIHIHAII#c                   | j                    d}d| j                  d<   t               }|r||d<   |||d<   |||d<   |0|j                  dd      |d	<   | j                  j                  |       | j                  ||      }|d
   S )Nz/objects/hostsGETzX-HTTP-Method-Overridehostsattrsjoinsz\""filterresults)r   r'   dictreplacer    r!   rD   )r   rG   rH   rI   r   query_hosts_url	data_dict	host_dicts           r   _query_hostszInventoryModule._query_hosts   s    !--.n=16-.F	!&Ig!&Ig!&Ig""-"5"5fd"CIhLL[)&&	B	##r   c                    | j                   j                  d       dg di}| j                  | j                  |d<    | j                  di |}| j	                  |      }|S )zQuery for all hosts zQuerying Icinga2 for inventoryrH   )
addressaddress6namedisplay_name
state_typestate	templatesgroupsvarszoner    )r    r!   r   rR   _convert_inv)r   
query_argsresults_jsonansible_invs       r   get_inventory_from_icingaz)InventoryModule.get_inventory_from_icinga   sn    9:  C

 '(,(8(8J}%(t((6:6''5r   c                    | j                  d      }| j                  | j                  d      |||       | j                  | j                  d      |||       | j                  | j                  d      |||       y )Nstrictr[   )re   keyed_groupscompose)
get_option_add_host_to_composed_groups_add_host_to_keyed_groups_set_composite_vars)r   rV   	variablesre   s       r   _apply_constructablez$InventoryModule._apply_constructable   su    *))$//(*CYPT]c)d&&t~'F	SW`f&g  !;YU[ \r   c                D    | j                  | j                               }|S r   )_to_jsonrc   )r   r[   s     r   	_populatezInventoryModule._populate   s    t==?@r   c                2    t        j                  |dd      S )zConvert dictionary to JSONT   )r3   r2   )r6   r7   )r   in_dicts     r   ro   zInventoryModule._to_json   s    zz'T!<<r   c           
     6   ddi ii}|D ]  }t        |d         }| j                  dk(  rt        |j                  d            }| j                  dk(  rJ|j                  dd      dk7  rt        |j                  d            }nt        |j                  d            }| j                  dk(  r|j                  d      }|d   d	k(  rd
|d<   nd|d<   | j                  j	                         | j
                  ru|j                  d      }|D ]_  }|| j                  j                  j                         vr| j                  j                  |       | j                  j                  ||       a |j                  d      dk7  r,| j                  j                  |d|j                  d             | j                  j                  |dt        |j                  d                   | j                  j                  |d|j                  d             | j                  j                  |d|d          | j                  j                  |d|d          t        | j                  j                  |      j                               }||d<   | j                  ||        |S )z3Convert Icinga2 API data to JSON format for Ansible_metahostvarsrH   rV   rT    rW   rY   r   onoffr[   ansible_hosthostnamerX   icinga2_attributes)r	   r   r=   	inventoryadd_hostr   r[   keys	add_group	add_childset_variablerM   get_hostget_varsrm   )	r   rC   groups_dictentry
host_attrs	host_namehost_groupsgroupconstruct_varss	            r   r_   zInventoryModule._convert_inv   sL   R 01 #	AE$U7^4J""f,'		&(9:	""i/>>)R0B6 +JNN9,E FI +EIIf,= >I""n4&NN>:	'"a'&*
7#&+
7#NN##I.''(nnX6( ?EDNN$9$9$>$>$@@007NN,,UI>?
 ~~i(B.++I~z~~V_G`aNN''	:{599U[K\?]^NN''	>:>>R`CabNN''	7(27(;=NN''	<(2<(@B "$.."9"9)"D"M"M"OPN3=N/0%%i@G#	AH r   c                   t         t        |   |||       | j                  |       | j	                  d      | _        | j	                  d      | _        | j	                  d      | _        | j	                  d      | _        | j	                  d      | _	        | j	                  d      | _
        | j	                  d      | _        | j                  j                  | j
                        r,| j                  j                  | j
                  d	      | _        | j                  j                  | j                        r,| j                  j                  | j                  d	      | _        | j                  j                  | j                        r,| j                  j                  | j                  d	      | _        | j
                  j                  d
       d| _        | j!                          | j#                          y )Nurluserpasswordr*   r   r   r   F)variabledisable_lookups/z/v1)r   r   parse_read_config_datarh   r   r   r   r   r   r   r   templaris_templatetemplaterstripr-   rp   )r   r}   loaderr"   cacher   s        r   r   zInventoryModule.parse  s   ot*9fdC 	t$  ??51 OOF3 $
 ;//*:;??=9"oo.>?#'??3H#I <<##D$4$45#||44d>N>N`e4fD<<##D$5$56 $ 5 5t?P?Pbg 5 hD<<##D$9$9:$(LL$9$94CXCXjo$9$pD!"..55c:;3? 	 	r   r   )NNNN)T)__name__
__module____qualname____doc__NAMEr   r   r-   rD   rR   rc   rm   rp   ro   r_   r   __classcell__)r   s   @r   r   r   l   sK    F&D 1&YP$ ]='R! !r   r   )
__future__r   DOCUMENTATIONEXAMPLESr6   ansible.errorsr   ansible.plugins.inventoryr   r   ansible.module_utils.urlsr   +ansible.module_utils.six.moves.urllib.errorr   Aansible_collections.community.general.plugins.plugin_utils.unsafer	   r   r^   r   r   <module>r      s>    #>@2  - H . A YJ)= Jr   