
    Vh2              
       h   d dl mZmZmZ d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 eZ G d de      Z G d de      Zd Z ej4                         Zej9                   edd       edd       eddd       edd       edd             d Zd Ze dk(  r e        yy)    )absolute_importdivisionprint_functionu  
---
module: grafana_team
author:
  - Rémi REY (@rrey)
version_added: "1.0.0"
short_description: Manage Grafana Teams
description:
  - Create/update/delete Grafana Teams through the Teams API.
  - Also allows to add members in the team (if members exists).
requirements:
  - The Teams API is only available starting Grafana 5 and the module will fail if the server version is lower than version 5.
options:
  name:
    description:
      - The name of the Grafana Team.
    required: true
    type: str
  email:
    description:
      - The mail address associated with the Team.
    required: true
    type: str
  members:
    description:
      - List of team members (emails).
      - The list can be enforced with C(enforce_members) parameter.
    type: list
    elements: str
  state:
    description:
      - Delete the members not found in the C(members) parameters from the
      - list of members found on the Team.
    default: present
    type: str
    choices: ["present", "absent"]
  enforce_members:
    description:
      - Delete the members not found in the C(members) parameters from the
      - list of members found on the Team.
    default: false
    type: bool
  skip_version_check:
    description:
      - Skip Grafana version check and try to reach api endpoint anyway.
      - This parameter can be useful if you enabled C(hide_version) in grafana.ini
    required: False
    type: bool
    default: false
    version_added: "1.2.0"
extends_documentation_fragment:
- community.grafana.basic_auth
- community.grafana.api_key
a  
---
- name: Create a team
  community.grafana.grafana_team:
      url: "https://grafana.example.com"
      grafana_api_key: "{{ some_api_token_value }}"
      name: "grafana_working_group"
      email: "foo.bar@example.com"
      state: present

- name: Create a team with members
  community.grafana.grafana_team:
      url: "https://grafana.example.com"
      grafana_api_key: "{{ some_api_token_value }}"
      name: "grafana_working_group"
      email: "foo.bar@example.com"
      members:
          - john.doe@example.com
          - jane.doe@example.com
      state: present

- name: Create a team with members and enforce the list of members
  community.grafana.grafana_team:
      url: "https://grafana.example.com"
      grafana_api_key: "{{ some_api_token_value }}"
      name: "grafana_working_group"
      email: "foo.bar@example.com"
      members:
          - john.doe@example.com
          - jane.doe@example.com
      enforce_members: true
      state: present

- name: Delete a team
  community.grafana.grafana_team:
      url: "https://grafana.example.com"
      grafana_api_key: "{{ some_api_token_value }}"
      name: "grafana_working_group"
      email: "foo.bar@example.com"
      state: absent
aM  
---
team:
    description: Information about the Team
    returned: On success
    type: complex
    contains:
        avatarUrl:
            description: The url of the Team avatar on Grafana server
            returned: always
            type: str
            sample:
                - "/avatar/a7440323a684ea47406313a33156e5e9"
        email:
            description: The Team email address
            returned: always
            type: str
            sample:
                - "foo.bar@example.com"
        id:
            description: The Team email address
            returned: always
            type: int
            sample:
                - 42
        memberCount:
            description: The number of Team members
            returned: always
            type: int
            sample:
                - 42
        name:
            description: The name of the team.
            returned: always
            type: str
            sample:
                - "grafana_working_group"
        members:
            description: The list of Team members
            returned: always
            type: list
            sample:
                - ["john.doe@exemple.com"]
        orgId:
            description: The organization id that the team is part of.
            returned: always
            type: int
            sample:
                - 1
N)AnsibleModule)	fetch_urlbasic_auth_header)to_text)base)quotec                       e Zd Zy)GrafanaErrorN)__name__
__module____qualname__     r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/grafana/plugins/modules/grafana_team.pyr   r      s    r   r   c                   P    e Zd Zd ZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zy)GrafanaTeamInterfacec                    || _         ddi| _        |j                  j                  dd       r d|j                  d   z  | j                  d<   n3t	        |j                  d   |j                  d         | j                  d<   t        j                  |j                  j                  d            | _        |j                  j                  d	      d
u r8	 | j                         }d   dk  r| j                   j                  dd       y y y # t        $ r0}| j                   j                  dt        |             Y d }~\d }~ww xY w)NzContent-Typezapplication/jsongrafana_api_keyz	Bearer %sAuthorizationurl_usernameurl_passwordurlskip_version_checkFTfailedmsgmajor   z*Teams API is available starting Grafana v5)_moduleheadersparamsgetr   r
   	clean_urlgrafana_urlget_versionr   	fail_jsonr	   )selfmodulegrafana_versiones       r   __init__zGrafanaTeamInterface.__init__   s-   &(:;==.5fmm,=>> LL) ->n-v}}^/L-DLL)  >>&--*;*;E*BC==12e;D"&"2"2"4 w'!+&&%Q '  , <   D&&d
&CCDs   D	 		E&D==ENc                 D   |t        j                  |d      }|sg }dj                  | j                  |      }t	        | j
                  ||||      \  }}|d   }|dk(  ry |dk(  r%| j
                  j                  dd	|d
|d       nt|dk(  r| j
                  j                  dd       nQ|dk(  r| j
                  j                  dd       n.|dk(  r)| j
                  j                  |j                               S | j
                  j                  dd|z         y )NT)	sort_keysz{grafana_url}{path})r'   pathdatar#   methodstatusi  i  z Unauthorized to perform action 'z' on ''r   i  zPermission Deniedi  zTeam name is taken   z'Grafana Teams API answered with HTTP %d)	jsondumpsformatr'   r   r"   r)   	from_jsonread)	r*   r   r3   r#   r4   full_urlrespinfostatus_codes	            r   _send_requestz"GrafanaTeamInterface._send_request   s    ::dd3DG(//D<L<LSV/WLL(wv

d 8n#CLL""EKXV #  CLL""$4G"HCLL""$4H"IC<<))$))+66FT 	 	
r   c                     d}| j                  |d | j                  d      }|j                  d      }|6|j                  d      \  }}}t	        |      t	        |      t	        |      dS t        d|z        )Nz/api/healthGETr2   version.)r    minorrevz$Failed to retrieve version from '%s')rA   r#   r%   splitintr   )r*   r   responserD   r    rF   rG   s          r   r(   z GrafanaTeamInterface.get_version   s~    %%dDLL & 
 ,,y) 'c 2E5# Z#e*SXNNACGHHr   c                 b    d}t        ||      }| j                  ||| j                  d      }|S )Nz
/api/teamsemailnamePOSTr2   )dictrA   r#   )r*   rN   rM   r   teamrJ   s         r   create_teamz GrafanaTeamInterface.create_team   s<    %d+%%dDLL & 
 r   c                 "   dj                  t        |            }| j                  || j                  d      }|j	                  d      dk  st        d|d   z        t        |j	                  d            d	k(  ry |j	                  d      d	   S )
Nz/api/teams/search?name={team})rQ   rC   r#   r4   
totalCount   zExpected 1 team, got %dteamsr   )r:   r   rA   r#   r%   AssertionErrorlen)r*   rN   r   rJ   s       r   get_teamzGrafanaTeamInterface.get_team  s    -44%+4F%%c4<<%N||L)Q. !:Xl=S!STTx||G$%*||G$Q''r   c                     dj                  |      }t        ||      }| j                  ||| j                  d      }|S )N/api/teams/{team_id}team_idrL   PUTr2   )r:   rP   rA   r#   )r*   r^   rN   rM   r   rQ   rJ   s          r   update_teamz GrafanaTeamInterface.update_team  sJ    $++G+<%d+%%dDLL & 
 r   c                 f    dj                  |      }| j                  || j                  d      }|S )Nr\   r]   DELETErT   )r:   rA   r#   )r*   r^   r   rJ   s       r   delete_teamz GrafanaTeamInterface.delete_team  s5    $++G+<%%c4<<%Qr   c                     dj                  |      }| j                  || j                  d      }|D cg c]  }|j                  d       }}|S c c}w )N/api/teams/{team_id}/membersr]   rC   rT   rM   )r:   rA   r#   r%   )r*   r^   r   rJ   itemmemberss         r   get_team_membersz%GrafanaTeamInterface.get_team_members  sV    ,33G3D%%c4<<%N19:488G$:: ;s   Ac                     dj                  |      }d| j                  |      i}| j                  ||| j                  d       y )Nre   r]   userIdrO   r2   )r:   get_user_id_from_mailrA   r#   )r*   r^   rM   r   r3   s        r   add_team_memberz$GrafanaTeamInterface.add_team_member  sE    ,33G3D$44U;<3T4<<Or   c                     | j                  |      }dj                  ||      }| j                  || j                  d       y )Nz&/api/teams/{team_id}/members/{user_id})r^   user_idrb   rT   )rk   r:   rA   r#   )r*   r^   rM   rn   r   s        r   delete_team_memberz'GrafanaTeamInterface.delete_team_member#  sG    ,,U36==W > 
 	3XFr   c                     dj                  t        |            }| j                  || j                  d      }| | j                  j                  dd|z         |j                  d      S )	Nz&/api/users/lookup?loginOrEmail={email})rM   rC   rT   TzUser '%s' does not existsr   id)r:   r   rA   r#   r"   r)   r%   )r*   rM   r   users       r   rk   z*GrafanaTeamInterface.get_user_id_from_mail*  se    6==E%L=Q!!#t||E!J<LL""$4ORW4W"Xxx~r   )NNrC   )r   r   r   r.   rA   r(   rR   rZ   r`   rc   rh   rl   ro   rk   r   r   r   r   r      s<    0
8	I(
P
Gr   r   c                  t    t        t        dt        j                         t        j                               } | S )NF)argument_specsupports_check_moderequired_togethermutually_exclusive)r   rt   r
   grafana_required_togethergrafana_mutually_exclusive)r+   s    r   setup_module_objectrz   2  s1    #!88:::<	F Mr   strT)typerequiredlistF)r|   elementsr}   bool)r|   default)rN   rM   rg   enforce_membersr   c                     t               } | j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }t        |       }d}|dk(  r#|j                  |      }|%|j	                  ||       |j                  |      }d}||j                  |j                  d	            }	t        ||	      }
|
j                  d
      D ]%  }|j                  |j                  d	      |       d}' |r9|
j                  d      D ]%  }|j                  |j                  d	      |       d}' |j                  |      }|j                  |j                  d	            |d<   | j                  d||       y |dk(  rk|j                  |      }|| j                  ddd       |j                  |j                  d	            }| j                  dd|j                  d             y y )NstaterN   rM   rg   r   FpresentTrq   to_addto_del)r   changedrQ   absentzNo team found)r   r   messager   )rz   r$   r   rZ   rR   rh   r%   diff_membersrl   ro   	exit_jsonrc   )r+   r   rN   rM   rg   r   grafana_ifacer   rQ   cur_membersplanmemberresults                r   mainr   F  s    "FMM'"E== DMM'"EmmI&Gmm$56O(0MG	%%d+<%%dE2 ))$/DG'88$HK5D((8, --dhhtnfE "hhx0 #F!44TXXd^VL"G# !))$/D'88$HYwTB	(	%%d+<E5/R**488D>:tVZZ	=RS 
r   c                     g g d}| D ]  }||vs|d   j                  |        |D ]  }|| vs|d   j                  |        |S )N)r   r   r   r   )append)targetcurrentdiffr   s       r   r   r   l  sg    B'D * N!!&)*  *N!!&)* Kr   __main__)!
__future__r   r   r   DOCUMENTATIONEXAMPLESRETURNr8   ansible.module_utils.basicr   ansible.module_utils.urlsr   r   ansible.module_utils._textr	   :ansible_collections.community.grafana.plugins.module_utilsr
   +ansible.module_utils.six.moves.urllib.parser   r|   __metaclass__	Exceptionr   objectr   rz   grafana_argument_specrt   updaterP   r   r   r   r   r   r   <module>r      s   ( A @5n(T1
f  4 B . K =	9 	v6 vr +**,   	54	(
ED
)fuu=fe47  #TL zF r   