
    Vh-                         d dl mZmZmZ eZdZdZd dlm	Z	 	 d dl
Z
d dlmZ dZd d	lmZ dZd
 Zd Zd Zd Zd Zd Zd Zd Zd Zedk(  r e        yy# e$ r dZY :w xY w)    )absolute_importdivisionprint_functiona  
module: consul_kv
short_description: Manipulate entries in the key/value store of a Consul cluster
description:
  - Allows the retrieval, addition, modification and deletion of key/value entries in a Consul cluster using the agent. The
    entire contents of the record, including the indices, flags and session are returned as C(value).
  - If the O(key) represents a prefix then note that when a value is removed, the existing value if any is returned as part
    of the results.
  - See http://www.consul.io/docs/agent/http.html#kv for more details.
requirements:
  - python-consul
  - requests
author:
  - Steve Gargan (@sgargan)
  - Colin Nolan (@colin-nolan)
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  state:
    description:
      - The action to take with the supplied key and value. If the state is V(present) and O(value) is set, the key contents
        will be set to the value supplied and C(changed) will be set to V(true) only if the value was different to the current
        contents. If the state is V(present) and O(value) is not set, the existing value associated to the key will be returned.
        The state V(absent) will remove the key/value pair, again C(changed) will be set to V(true) only if the key actually
        existed prior to the removal. An attempt can be made to obtain or free the lock associated with a key/value pair with
        the states V(acquire) or V(release) respectively. A valid session must be supplied to make the attempt C(changed)
        will be V(true) if the attempt is successful, V(false) otherwise.
    type: str
    choices: [absent, acquire, present, release]
    default: present
  key:
    description:
      - The key at which the value should be stored.
    type: str
    required: true
  value:
    description:
      - The value should be associated with the given key, required if O(state) is V(present).
    type: str
  recurse:
    description:
      - If the key represents a prefix, each entry with the prefix can be retrieved by setting this to V(true).
    type: bool
  retrieve:
    description:
      - If the O(state) is V(present) and O(value) is set, perform a read after setting the value and return this value.
    default: true
    type: bool
  session:
    description:
      - The session that should be used to acquire or release a lock associated with a key/value pair.
    type: str
  token:
    description:
      - The token key identifying an ACL rule set that controls access to the key value pair.
    type: str
  cas:
    description:
      - Used when acquiring a lock with a session. If the O(cas) is V(0), then Consul will only put the key if it does not
        already exist. If the O(cas) value is non-zero, then the key is only set if the index matches the ModifyIndex of that
        key.
    type: str
  flags:
    description:
      - Opaque positive integer value that can be passed when setting a value.
    type: str
  host:
    description:
      - Host of the Consul agent.
    type: str
    default: localhost
  port:
    description:
      - The port on which the Consul agent is running.
    type: int
    default: 8500
  scheme:
    description:
      - The protocol scheme on which the Consul agent is running.
    type: str
    default: http
  validate_certs:
    description:
      - Whether to verify the tls certificate of the Consul agent.
    type: bool
    default: true
  datacenter:
    description:
      - The name of the datacenter to query. If unspecified, the query will default to the datacenter of the Consul agent
        on O(host).
    type: str
    version_added: 10.0.0
a  
# If the key does not exist, the value associated to the "data" property in `retrieved_key` will be `None`
# If the key value is empty string, `retrieved_key["data"]["Value"]` will be `None`
- name: Retrieve a value from the key/value store
  community.general.consul_kv:
    key: somekey
  register: retrieved_key

- name: Add or update the value associated with a key in the key/value store
  community.general.consul_kv:
    key: somekey
    value: somevalue

- name: Remove a key from the store
  community.general.consul_kv:
    key: somekey
    state: absent

- name: Add a node to an arbitrary group using Consul inventory (see consul.ini)
  community.general.consul_kv:
    key: ansible/groups/dc1/somenode
    value: top_secret

- name: Register a key/value pair with an associated session
  community.general.consul_kv:
    key: stg/node/server_birthday
    value: 20160509
    session: "{{ sessionid }}"
    state: acquire
)to_textN)ConnectionErrorTF)AnsibleModulec                     | j                   j                  |      \  }}|s|dfS 	 t        |d   d      |k7  }||fS # t        $ r |dfcY S w xY w)a  
    Uses the given Consul client to determine if the value associated to the given key is different to the given target
    value.
    :param consul_client: Consul connected client
    :param key: key in Consul
    :param target_value: value to be associated to the key
    :return: tuple where the first element is the value of the "X-Consul-Index" header and the second is `True` if the
    value has changed (i.e. the stored value is not the target value)
    TValuesurrogate_or_strict)errors)kvgetr   UnicodeError)consul_clientkeytarget_valueindexexistingchangeds         o/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/consul_kv.py_has_value_changedr      sj     $&&**3/OE8d{(7+4IJlZg~ d{s   = AAc                 0   | j                   j                  d      }|dk(  s|dk(  rt        | |       y |dk(  r9| j                   j                  d      t        u rt	        |        y t        |        y |dk(  rt        |        y | j                  d|       y )	NstateacquirereleasepresentvalueabsentzUnsupported state: msg)paramsr   lockNOT_SET	get_value	set_valueremove_value	exit_json)moduler   s     r   executer)      s    MMg&E	Ui/VU	)	==W%0ff	(	V@A    c           	         t        |       }| j                  j                  d      }| j                  j                  d      }| j                  j                  d      }|s| j                  |d|d       t	        |||      \  }}|r| j
                  s|dk(  rS|j                  j                  ||| j                  j                  d      || j                  j                  d	      
      }nR|j                  j                  ||| j                  j                  d      || j                  j                  d	            }| j                  |||       y )Nsessionr   r   z of lock for z" requested but no session suppliedr   r   casflags)r-   r   r.   )r-   r   r.   )r   r   r   )	get_consul_apir!   r   failr   
check_moder   putr'   )r(   r   
consul_apir,   r   r   r   r   s           r   r"   r"      s6   'Jmm	*G
--

E
"CMMg&EC 	 	 (
C?NE7v((I mm''U,2MM,=,=e,D07.4mm.?.?.H ( JG
 !mm''U,2MM,=,=e,D07.4mm.?.?.H ( JG
 W   r*   c                     t        |       }| j                  j                  d      }|j                  j                  || j                  j                  d            \  }}| j	                  d||       y )Nr   recurser5   F)r   r   data)r/   r!   r   r   r'   )r(   r3   r   r   existing_values        r   r$   r$      sb    'J
--

E
"C&MM--c6==;L;LY;W-XE>
U%nEr*   c                 0   t        |       }| j                  j                  d      }| j                  j                  d      }|t        u rt	        d|z        t        |||      \  }}|r]| j                  sQ|j                  j                  ||| j                  j                  d      | j                  j                  d            }d }| j                  j                  d      r|j                  j                  |      \  }}| j                  ||||       y )	Nr   r   z%Cannot set value of "%s" to `NOT_SET`r-   r.   )r-   r.   retriever   r   r   r7   )
r/   r!   r   r#   AssertionErrorr   r1   r   r2   r'   )r(   r3   r   r   r   r   storeds          r   r%   r%      s    'J
--

E
"CMMg&EDsJKK'
C?NE7v((--##C(.(9(9%(@*0--*;*;G*D $ F F}}$"))#.v
W    "r*   c                 z   t        |       }| j                  j                  d      }|j                  j                  || j                  j                  d            \  }}|du}|rA| j                  s5|j                  j                  || j                  j                  d             | j                  ||||       y)z remove the value associated with the given key. if the recurse parameter
     is set then any key prefixed with the given key will be removed. r   r5   r6   Nr;   )r/   r!   r   r   r1   deleter'   )r(   r3   r   r   r   r   s         r   r&   r&   	  s      'J
--

E
"C mm''V]]&&y1 ( 3OE8 d"Gv((S&--"3"3I">?
W "  $r*   c           
      d   t        j                  | j                  j                  d      | j                  j                  d      | j                  j                  d      | j                  j                  d      | j                  j                  d      | j                  j                  d            S )Nhostportschemevalidate_certstoken
datacenter)rA   rB   rC   verifyrE   dc)consulConsulr!   r   r(   s    r   r/   r/     s    ==fmm//7$mm//7 & 1 1( ; & 1 12B C%}}009"MM--l;= =r*   c                 6    t         s| j                  d       y y )Nzhpython-consul required for this module. see https://python-consul.readthedocs.io/en/latest/#installationr   )python_consul_installed	fail_jsonrK   s    r   test_dependenciesrO   &  s"    " ` 	a #r*   c                     t        t        t        d      t        dd       t        d      t        ddd      t        dd      t        dd      t        d	d      t        d
d      t        d	      t        d	d      t        ddg d      t        dd      t        dt              t        d            d      } t        |        	 t	        |        y # t
        $ rW}| j                  d| j                  j                  d      d| j                  j                  d      d|       Y d }~y d }~wt        $ r%}| j                  t        |             Y d }~y d }~ww xY w)Nstr)type)rR   defaultTF)rR   requiredno_log	localhosthttpboolinti4!  r   )r   r   r   r   )rR   rS   choices)rR   rU   )r-   rF   r.   r   rA   rC   rD   rB   r5   r:   r   rE   r   r,   )argument_specsupports_check_modez%Could not connect to consul agent at rA   :rB   z, error was r   )r   dictr#   rO   r)   r   rN   r!   r   	ExceptionrQ   )r(   es     r   mainra   ,  s-   % 5E"%$u=5+6UF3VT:5$/f%vt4E9>ijE$/E73e$
  !#F( f% FMMf%v}}'8'8'@!E 	F 	F %SV$$%s%   C 	E'$AD66E'E""E'__main__)
__future__r   r   r   rR   __metaclass__DOCUMENTATIONEXAMPLES+ansible.module_utils.common.text.convertersr   rI   requests.exceptionsr   rM   ImportErroransible.module_utils.basicr   r#   r   r)   r"   r$   r%   r&   r/   rO   ra   __name__ r*   r   <module>rm      s    A @aH> @$3" 5
 *B @F"4$(=a%B zF o  $#$s   A AA