
    Vh8                        d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlmZmZ d dlmZ d dlmZ d d	lmZ 	 d d
lmZmZmZmZmZ dZdZdZ e       Z ej@                  e	jB                         G d de"             Z# G d de#      Z$ G d de#      Z% G d de      Z&y# e$ r4 	 d d
lmZmZmZmZmZ dZdZdZn# e$ r dZdZdZdZdZdZdZdZY nw xY wY w xY w)    )absolute_importdivisionprint_functiona  
name: tss
author: Adam Migus (@amigus) <adam@migus.org>
short_description: Get secrets from Thycotic Secret Server
version_added: 1.0.0
description:
  - Uses the Thycotic Secret Server Python SDK to get Secrets from Secret Server using token authentication with O(username)
    and O(password) on the REST API at O(base_url).
  - When using self-signed certificates the environment variable E(REQUESTS_CA_BUNDLE) can be set to a file containing the
    trusted certificates (in C(.pem) format).
  - For example, C(export REQUESTS_CA_BUNDLE='/etc/ssl/certs/ca-bundle.trust.crt').
requirements:
  - python-tss-sdk - https://pypi.org/project/python-tss-sdk/
options:
  _terms:
    description: The integer ID of the secret.
    required: true
    type: list
    elements: int
  secret_path:
    description: Indicate a full path of secret including folder and secret name when the secret ID is set to 0.
    required: false
    type: str
    version_added: 7.2.0
  fetch_secret_ids_from_folder:
    description:
      - Boolean flag which indicates whether secret IDs are in a folder is fetched by folder ID or not.
      - V(true) then the terms will be considered as a folder IDs. Otherwise (default), they are considered as secret IDs.
    required: false
    type: bool
    version_added: 7.1.0
  fetch_attachments:
    description:
      - Boolean flag which indicates whether attached files will get downloaded or not.
      - The download will only happen if O(file_download_path) has been provided.
    required: false
    type: bool
    version_added: 7.0.0
  file_download_path:
    description: Indicate the file attachment download location.
    required: false
    type: path
    version_added: 7.0.0
  base_url:
    description: The base URL of the server, for example V(https://localhost/SecretServer).
    type: string
    env:
      - name: TSS_BASE_URL
    ini:
      - section: tss_lookup
        key: base_url
    required: true
  username:
    description: The username with which to request the OAuth2 Access Grant.
    type: string
    env:
      - name: TSS_USERNAME
    ini:
      - section: tss_lookup
        key: username
  password:
    description:
      - The password associated with the supplied username.
      - Required when O(token) is not provided.
    type: string
    env:
      - name: TSS_PASSWORD
    ini:
      - section: tss_lookup
        key: password
  domain:
    default: ""
    description:
      - The domain with which to request the OAuth2 Access Grant.
      - Optional when O(token) is not provided.
      - Requires C(python-tss-sdk) version 1.0.0 or greater.
    type: string
    env:
      - name: TSS_DOMAIN
    ini:
      - section: tss_lookup
        key: domain
    required: false
    version_added: 3.6.0
  token:
    description:
      - Existing token for Thycotic authorizer.
      - If provided, O(username) and O(password) are not needed.
      - Requires C(python-tss-sdk) version 1.0.0 or greater.
    type: string
    env:
      - name: TSS_TOKEN
    ini:
      - section: tss_lookup
        key: token
    version_added: 3.7.0
  api_path_uri:
    default: /api/v1
    description: The path to append to the base URL to form a valid REST API request.
    type: string
    env:
      - name: TSS_API_PATH_URI
    required: false
  token_path_uri:
    default: /oauth2/token
    description: The path to append to the base URL to form a valid OAuth2 Access Grant request.
    type: string
    env:
      - name: TSS_TOKEN_PATH_URI
    required: false
z
_list:
  description:
    - The JSON responses to C(GET /secrets/{id}).
    - See U(https://updates.thycotic.net/secretserver/restapiguide/TokenAuth/#operation--secrets--id--get).
  type: list
  elements: dict
a.  
- hosts: localhost
  vars:
    secret: >-
      {{
        lookup(
          'community.general.tss',
          102,
          base_url='https://secretserver.domain.com/SecretServer/',
          username='user.name',
          password='password'
        )
      }}
  tasks:
    - ansible.builtin.debug:
        msg: >
          the password is {{
            (secret['items']
              | items2dict(key_name='slug',
                           value_name='itemValue'))['password']
          }}

- hosts: localhost
  vars:
    secret: >-
      {{
        lookup(
          'community.general.tss',
          102,
          base_url='https://secretserver.domain.com/SecretServer/',
          username='user.name',
          password='password',
          domain='domain'
        )
      }}
  tasks:
    - ansible.builtin.debug:
        msg: >
          the password is {{
            (secret['items']
              | items2dict(key_name='slug',
                           value_name='itemValue'))['password']
          }}

- hosts: localhost
  vars:
    secret_password: >-
      {{
        ((lookup(
          'community.general.tss',
          102,
          base_url='https://secretserver.domain.com/SecretServer/',
          token='thycotic_access_token',
        ) | from_json).get('items') | items2dict(key_name='slug', value_name='itemValue'))['password']
      }}
  tasks:
    - ansible.builtin.debug:
        msg: the password is {{ secret_password }}

# Private key stores into certificate file which is attached with secret.
# If fetch_attachments=True then private key file will be download on specified path
# and file content will display in debug message.
- hosts: localhost
  vars:
    secret: >-
      {{
        lookup(
          'community.general.tss',
          102,
          fetch_attachments=True,
          file_download_path='/home/certs',
          base_url='https://secretserver.domain.com/SecretServer/',
          token='thycotic_access_token'
        )
      }}
  tasks:
    - ansible.builtin.debug:
        msg: >
          the private key is {{
            (secret['items']
              | items2dict(key_name='slug',
                           value_name='itemValue'))['private-key']
          }}

# If fetch_secret_ids_from_folder=true then secret IDs are in a folder is fetched based on folder ID
- hosts: localhost
  vars:
    secret: >-
      {{
        lookup(
          'community.general.tss',
          102,
          fetch_secret_ids_from_folder=true,
          base_url='https://secretserver.domain.com/SecretServer/',
          token='thycotic_access_token'
        )
      }}
  tasks:
    - ansible.builtin.debug:
        msg: >
          the secret id's are {{
              secret
          }}

# If secret ID is 0 and secret_path has value then secret is fetched by secret path
- hosts: localhost
  vars:
    secret: >-
      {{
        lookup(
          'community.general.tss',
          0,
          secret_path='\folderName\secretName'
          base_url='https://secretserver.domain.com/SecretServer/',
          username='user.name',
          password='password'
        )
      }}
  tasks:
    - ansible.builtin.debug:
        msg: >-
          the password is {{
            (secret['items']
              | items2dict(key_name='slug',
                           value_name='itemValue'))['password']
          }}
N)AnsibleErrorAnsibleOptionsError)six)
LookupBase)Display)SecretServerSecretServerErrorPasswordGrantAuthorizerDomainPasswordGrantAuthorizerAccessTokenAuthorizerTFc                   N    e Zd Zd Zed        Zd Zd Zed        Zed        Z	y)	TSSClientc                     d | _         y )N)_client)selfs    h/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/lookup/tss.py__init__zTSSClient.__init__&  s	        c                  :    t         rt        di | S t        di | S )N )HAS_TSS_AUTHORIZERTSSClientV1TSSClientV0server_parameterss    r   from_paramszTSSClient.from_params)  s#    3!2333!233r   c           
         t         j                  d|        | j                  |      }|dk(  r|rd}t         j                  d|        nd}t         j                  d|        |r|r| j                  j                  ||      }n| j                  j                  ||      }|d   D ]  }|rt        j                  j                  |      rk|d   s*	 |d	   j                  }	t        t        j                  j                  ||d
    d|d          d      5 }
|
j                  |	       d d d        d|d	<   t        d       |S |r| j                  j                  |d      S | j                  j%                  |      S # 1 sw Y   VxY w# t        $ r t        d|d          t         $ r t         j#                  d|d           Y w xY w# d|d	<   w xY w)Ntss_lookup term: r   Tz)Secret Server lookup of Secret with path Fz'Secret Server lookup of Secret with ID itemsisFile	itemValueid_slugwbzFailed to download z Could not read file content for z*** Not Valid For Display ***z!File download path does not exist)displaydebug_term_to_secret_idvvvr   get_secret_by_path
get_secretospathisdircontentopenjoinwrite
ValueErrorr   AttributeErrorwarningget_secret_json)r   termsecret_pathfetch_file_attachmentsfile_download_path	secret_idfetch_secret_by_pathobjifile_contentfs              r   r.   zTSSClient.get_secret0  s   )$01++D1	>k#' KKCK=QR#( KKA)MN!#ll55kCYZll--i9OP\ S%"''--8J*K{	M+,[>+A+AL!%bggll3E#d)TUVWX^V_U`Ga&bdh!i 6mn ! 56 .MAkN-.QRRS J#||66{EJJ||33I>>6 6) Y"58KAfI;6W"XX- \#OO.NqQWyk,Z[\ .MAkNs=   AF
E>)F
>F	F

=G
G	G

GGc                     t         j                  d|        | j                  |      }t         j                  d|        | j                  j                  |      S )Nr!   z3Secret Server lookup of Secret id's with Folder ID )r)   r*   _term_to_folder_idr,   r   get_secret_ids_by_folderid)r   r:   	folder_ids      r   rF   z$TSSClient.get_secret_ids_by_folderidU  sO    )$01++D1	I)UV||66yAAr   c                 J    	 t        |       S # t        $ r t        d      w xY w)NzSecret ID must be an integerintr6   r   r:   s    r   r+   zTSSClient._term_to_secret_id\  /    	Ft9 	F%&DEE	F   
 "c                 J    	 t        |       S # t        $ r t        d      w xY w)NzFolder ID must be an integerrI   rK   s    r   rE   zTSSClient._term_to_folder_idc  rL   rM   N)
__name__
__module____qualname__r   staticmethodr   r.   rF   r+   rE   r   r   r   r   r   $  sS     4 4#?JB F F F Fr   r   c                        e Zd Z fdZ xZS )r   c                     t         t        |           |j                  d      rt	        d      t        |d   |d   |d   |d   |d         | _        y )NdomainzFThe 'domain' option requires 'python-tss-sdk' version 1.0.0 or greaterbase_urlusernamepasswordapi_path_uritoken_path_uri)superr   r   getr   r   r   )r   r   	__class__s     r   r   zTSSClientV0.__init__l  s_    k4)+  *ghh#j)j)j)n-./
r   )rO   rP   rQ   r   __classcell__r]   s   @r   r   r   k  s    
 
r   r   c                   .     e Zd Z fdZed        Z xZS )r   c                 ~    t         t        |            | j                  di |}t	        |d   ||d         | _        y )NrV   rY   r   )r[   r   r   _get_authorizerr   r   )r   r   
authorizerr]   s      r   r   zTSSClientV1.__init__|  sD    k4)+)T))>,=>
#j):7H7X
r   c                      | j                  d      rt        | d         S | j                  d      rt        | d   | d   | d   | d   | d         S t        | d   | d   | d   | d         S )NtokenrU   rV   rW   rX   rZ   )r\   r   r   r   r   s    r   rb   zTSSClientV1._get_authorizer  s      )(!'*    *0!*-!*-!(+!*-!"23  'j)j)j)./	
 	
r   )rO   rP   rQ   r   rR   rb   r^   r_   s   @r   r   r   {  s    
 
 
r   r   c                       e Zd Zd Zy)LookupModulec                    t         st        d      | j                  ||       t        j	                  | j                  d      | j                  d      | j                  d      | j                  d      | j                  d      | j                  d      | j                  d	      
      }	 | j                  d      r0t        r|D cg c]  }|j                  |       c}S t        d      |D cg c]C  }|j                  || j                  d      | j                  d      | j                  d            E c}S c c}w c c}w # t        $ r}t        d|j                         d }~ww xY w)Nz3python-tss-sdk must be installed to use this plugin)var_optionsdirectrV   rW   rX   rU   re   rY   rZ   )rV   rW   rX   rU   re   rY   rZ   fetch_secret_ids_from_folderz:latest python-tss-sdk must be installed to use this pluginr;   fetch_attachmentsr=   zSecret Server lookup failure: )HAS_TSS_SDKr   set_optionsr   r   
get_optionHAS_DELINEA_SS_SDKrF   r.   r   message)r   terms	variableskwargstssr:   errors          r   runzLookupModule.run  sS   TUUYv>##__Z0__Z0__Z0??8,//'*8??+;< $ 
	Q=>%MRSTC::4@SS&'cdd !&  NN6(;<(<=	 	 T ! 	Q!?OPP	Qs=   +E D;E !E 0AE 8E ;
E 	E+E&&E+N)rO   rP   rQ   rw   r   r   r   rg   rg     s    !Qr   rg   )'
__future__r   r   r   type__metaclass__DOCUMENTATIONRETURNEXAMPLESabcr/   ansible.errorsr   r   ansible.module_utilsr   ansible.plugins.lookupr	   ansible.utils.displayr
   delinea.secrets.serverr   r   r   r   r   rm   rp   r   ImportErrorthycotic.secrets.serverr)   add_metaclassABCMetaobjectr   r   r   rg   r   r   r   <module>r      s6  
 A @n`
~@  	 < $ - )# V  VK& ) 3;;CF CF  CFL
) 
 
) 
B"Q: "Q[  ## 	[  	["! # ""&(,% $"##s5   B C#B87C8CCCCC