
    VhD                        d dl mZ dZdZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZmZ d dlmZmZ d d	lmZ  G d
 de
      Zy)    )annotationsae  
    name: ini
    version_added: "2.4"
    short_description: Uses an Ansible INI file as inventory source.
    description:
        - INI file based inventory, sections are groups or group related with special C(:modifiers).
        - Entries in sections C([group_1]) are hosts, members of the group.
        - Hosts can have variables defined inline as key/value pairs separated by C(=).
        - The C(children) modifier indicates that the section contains groups.
        - The C(vars) modifier indicates that the section contains variables assigned to members of the group.
        - Anything found outside a section is considered an 'ungrouped' host.
        - Values passed in the INI format using the C(key=value) syntax are interpreted differently depending on where they are declared within your inventory.
        - When declared inline with the host, INI values are processed by Python's ast.literal_eval function
          (U(https://docs.python.org/3/library/ast.html#ast.literal_eval)) and interpreted as Python literal structures
         (strings, numbers, tuples, lists, dicts, booleans, None). If you want a number to be treated as a string, you must quote it.
          Host lines accept multiple C(key=value) parameters per line.
          Therefore they need a way to indicate that a space is part of a value rather than a separator.
        - When declared in a C(:vars) section, INI values are interpreted as strings. For example C(var=FALSE) would create a string equal to C(FALSE).
          Unlike host lines, C(:vars) sections accept only a single entry per line, so everything after the C(=) must be the value for the entry.
        - Do not rely on types set during definition, always make sure you specify type with a filter when needed when consuming the variable.
        - See the Examples for proper quoting to prevent changes to variable type.
    notes:
        - Enabled in configuration by default.
        - Consider switching to YAML format for inventory sources to avoid confusion on the actual type of a variable.
          The YAML inventory plugin processes variable values consistently and correctly.
a  # fmt: ini
# Example 1
[web]
host1
host2 ansible_port=222 # defined inline, interpreted as an integer

[web:vars]
http_port=8080 # all members of 'web' will inherit these
myvar=23 # defined in a :vars section, interpreted as a string

[web:children] # child groups will automatically add their hosts to parent group
apache
nginx

[apache]
tomcat1
tomcat2 myvar=34 # host specific vars override group vars
tomcat3 mysecret="'03#pa33w0rd'" # proper quoting to prevent value changes

[nginx]
jenkins1

[nginx:vars]
has_java = True # vars in child groups override same in parent

[all:vars]
has_java = False # 'all' is 'top' parent

# Example 2
host1 # this is 'ungrouped'

# both hosts have same IP but diff ports, also 'ungrouped'
host2 ansible_host=127.0.0.1 ansible_port=44
host3 ansible_host=127.0.0.1 ansible_port=45

[g1]
host4

[g2]
host4 # same host as above, but member of 2 groups, will inherit vars from both
      # inventory hostnames are unique
N)to_safe_group_name)BaseFileInventoryPlugin)AnsibleErrorAnsibleParserError)to_bytesto_text)shlex_splitc                       e Zd ZdZdZ ed      Z ed      Z fdZd fd	Z	d Z
d Zd	 Zd
 Zd Zd Z fdZed        Zd Z xZS )InventoryModulez
    Takes an INI-format inventory file and builds a list of groups and subgroups
    with their associated hosts and variable settings.
    ini);#)   ;   #c                F    t         t        |           i | _        d | _        y )N)superr   __init__patterns	_filename)self	__class__s    M/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/inventory/ini.pyr   zInventoryModule.__init__`   s    ot-/    c                t   t         t        |   |||       || _        	 | j                  r| j                  j                  |      \  }}n2t        |d      }t        |d      5 }|j                         }d d d        	 t        d      j                         }	| j                  ||	       y # 1 sw Y   8xY w# t        $ r[ g }	j                         D ]C  }
|
r#|
d   | j                  v r|	j                  d       (|	j                  t        |
d             E Y w xY w# t        $ r}t!        |      d }~ww xY w)Nsurrogate_or_stricterrorsrbr    )r   r   parser   loader_get_file_contentsr   openreadr	   
splitlinesUnicodeErrorb_COMMENT_MARKERSappend_parse	Exceptionr   )r   	inventoryr"   pathcacheb_dataprivateb_pathfhdatalineer   s               r   r!   zInventoryModule.parseg   s.   ot*9fdC	({{$(KK$B$B4$H!!$/DE&$' '2WWYF'Q v.CDOOQ KKd#)' '   Q"--/ QDQ4+A+A A C( GD9N$OPQQ  	($Q''	(sU   AD #B+4D =B7 D +B40D 7A!DD DD 	D7'D22D7c                P    t        d| j                  | j                  fz  |z         )Nz%s:%d: )r   r   lineno)r   messages     r   _raise_errorzInventoryModule._raise_error   s$    9'DDwNOOr   c           	        | j                          i }d}d}d| _        |D ]  }| xj                  dz  c_        |j                         }|r|d   | j                  v r=| j                  d   j                  |      }|r|j                         \  }}t        |      }|xs d}|dvr6dj                  |j                               }| j                  d|d	|       || j                  j                  vr?|d
k(  r||vrt        | j                  ||      ||<   | j                  j                  |       ||v r1|d
k7  r,||   d   dk(  r| j                  ||       n||   d   d
k(  r||= I|j                  d      r+|j                  d      r| j                  d|z  dz   dz          |dk(  r+| j!                  |      \  }	}
}| j#                  |	|||
       |d
k(  r3| j%                  |      \  }}| j                  j'                  |||       |dk(  r| j)                  |      }|| j                  j                  vr<||vrt        | j                  |||g      ||<   >||   d   j+                  |       W| j                  j-                  ||       u| j                  d|z          |D ][  }||   }|d   d
k(  rt/        d||d   |d   |d   fz        |d   dk(  s4t/        d||d   |d   j1                         |d   fz         y)zt
        Populates self.groups from the given array of lines. Raises an error on
        any parse failure.
        	ungroupedhostsr      section)r<   childrenvars:z	Section [z] has unknown type: r@   )r4   statenamerB   r?   []zFInvalid section entry: '%s'. Please make sure that there are no spaces zDin the section entry, and that there are no other invalid characters)r4   rB   rC   parentsrG   zEntered unhandled state: %sz:%s:%d: Section [%s:vars] not valid for undefined group: %sr4   rC   z9%s:%d: Section [%s:children] includes undefined group: %sN)_compile_patternsr7   strip_COMMENT_MARKERSr   matchgroupsr   joinr9   r,   dict	add_group_add_pending_children
startswithendswith_parse_host_definition_populate_host_vars_parse_variable_definitionset_variable_parse_group_namer)   	add_childr   pop)r   r-   linespending_declarations	groupnamerB   r4   mtitler<   port	variableskvchildgdecls                    r   r*   zInventoryModule._parse   s    	   "	 P	KDKK1K::<D47d&;&;;
 i(..t4A%&XXZ"E.y9	( ==HHQXXZ0E%%UTY&Z[ DNN$9$99 9<P+P:>DKKW\cl:m,Y7NN,,Y7  44&+I6w?:M229>RS-i8AVK0;%$--*<!!"jmq"qtw"w"h#i j )-)D)DT)J&tY((	9dK &88>A++Iq!< *$..t4 5 55$886:SX_doxny6z,U3,U3I>EEiPNN,,Y> !!"?5"IJaP	Kh & 	\A'*DG}&"#_cgimntiuw{  }C  xD  FJ  KQ  FR  cS  $S  T  Tg*,"#^bfhlmshtvz  |E  wF  wJ  wJ  wL  NR  SY  NZ  b[  $[  \  \	\r   c                    ||   d   D ]A  }| j                   j                  ||       ||v s$||   d   dk(  s0| j                  ||       C ||= y )NrG   rB   r?   )r,   rX   rP   )r   grouppendingparents       r   rP   z%InventoryModule._add_pending_children   s_    enY/ 	<FNN$$VU3 WV_W%=%K**67;	< ENr   c                    | j                   d   j                  |      }|r|j                  d      S | j                  d|z         y)z
        Takes a single line and tries to parse it as a group name. Returns the
        group name if successful, or raises an error.
        r\   r=   zExpected group name, got: %sN)r   rK   rg   r9   )r   r4   r]   s      r   rW   z!InventoryModule._parse_group_name  sB     MM+&,,T2771:8DABr   c                    d|v rD|j                  dd      D cg c]  }|j                          c}\  }}|| j                  |      fS | j                  d|z         yc c}w )z
        Takes a string and tries to parse it as a variable definition. Returns
        the key and value if successful, or raises an error.
        =r=   zExpected key=value, got: %sN)splitrI   _parse_valuer9   )r   r4   r5   ra   rb   s        r   rU   z*InventoryModule._parse_variable_definition  s_     $;)-C);<Aaggi<FQt((+,,74@A =s   Ac                J   	 t        |d      }| j                  d         \  }}i }|dd D ]C  }d|vr| j                  d	|z         |j	                  dd      \  }}	| j                  |	      ||<   E |||fS # t        $ r!}| j                  d|d|       Y d}~d}~ww xY w)
z
        Takes a single line and tries to parse it as a host definition. Returns
        a list of Hosts if successful, or raises an error.
        T)commentszError parsing host definition 'z': Nr   r=   rl   z4Expected key=value host variable assignment, got: %s)r
   
ValueErrorr9   _expand_hostpatternrm   rn   )
r   r4   tokensr5   	hostnamesr_   r`   tra   rb   s
             r   rS   z&InventoryModule._parse_host_definition  s     	T 5F !44VAY?D 	 	0A!|!!"X\]"^_WWS!_FQ,,Q/IaL		0 $	))  	T$PQRSS	Ts   A8 8	B"BB"c                    t         t        |   |      \  }}|j                         j	                  d      r|t        d|z        |D ]#  }|j                         dk(  st        d|z         ||fS )z=
        do some extra checks over normal processing
        rA   zoInvalid host pattern '%s' supplied, ending in ':' is not allowed, this character is reserved to provide a port.z---zQInvalid host pattern '%s' supplied, '---' is normally a sign this is a YAML file.)r   r   rr   rI   rR   r   )r   hostpatternrt   r_   patternr   s        r   rr   z#InventoryModule._expand_hostpattern?  s      J;W	4'',$  &W%0&1 2 2  	LG}}%'()|  @K  *K  L  L	L
 4  r   c                   	 t        j                         5  t        j                  dt               t	        j
                  |       } ddd       t        | dd      S # 1 sw Y   xY w# t        $ r Y %t        $ r Y /w xY w)z
        Attempt to transform the string value from an ini file into a basic python object
        (int, dict, list, unicode string, etc).
        ignoreNpassthrur   )	nonstringr   )	warningscatch_warningssimplefilterSyntaxWarningastliteral_evalrq   SyntaxErrorr	   )rb   s    r   rn   zInventoryModule._parse_valueQ  sx    	((* (%%h>$$Q'( qJ7LMM( (
  	 		s.   A( 0AA( A%!A( (	A>3A>=A>c                    t        j                  t        dd      t         j                        | j                  d<   t        j                  t        dd      t         j                        | j                  d<   y)z|
        Compiles the regular expressions required to parse the inventory and
        stores them in self.patterns.
        a  ^\[
                    ([^:\]\s]+)             # group name (see groupname below)
                    (?::(\w+))?             # optional : and tag name
                \]
                \s*                         # ignore trailing whitespace
                (?:\#.*)?                   # and/or a comment till the
                $                           # end of the line
            r   r   r>   z^
                ([^:\]\s]+)
                \s*                         # ignore trailing whitespace
                (?:\#.*)?                   # and/or a comment till the
                $                           # end of the line
            r\   N)recompiler	   Xr   )r   s    r   rH   z!InventoryModule._compile_patternse  sj     $&::  ./ 13	$
i   &(ZZ 
 ./
 13&
k"r   )T)__name__
__module____qualname____doc__NAME	frozensetrJ   r(   r   r!   r9   r*   rP   rW   rU   rS   rr   staticmethodrn   rH   __classcell__)r   s   @r   r   r   W   su     D .!,/"(HPj\X
CB"*B!$ N N&&
r   r   )
__future__r   DOCUMENTATIONEXAMPLESr   r   r}   ansible.inventory.groupr   ansible.plugins.inventoryr   ansible.errorsr   r   +ansible.module_utils.common.text.convertersr   r	   ansible.utils.shlexr
   r    r   r   <module>r      sB    #6)V  	  6 = ; I +t
- t
r   