o nnhs@shddlmZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m ZddlmZmZmZddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZdd l m!Z!ddl"m#Z#ddl$m%Z%ddl&m'Z'e#Z(gdZ)ddej*DZ+ddej,DZ-e.d/e)e+e-Z0e.dej1Z2ddZ3ddZ4Gddde5Z6dS)) annotationsN) attrgetter)shuffle) constants) AnsibleErrorAnsibleOptionsErrorAnsibleParserError) InventoryData) string_types)to_bytesto_text) parse_address)inventory_loader)deduplicate_list) unfrackpath)Display) combine_vars)get_vars_from_inventory_sources)s^\.s ^host_vars$s ^group_vars$s^vars_plugins$cCsg|]}t|qS)r .0xrrD/usr/local/lib/python3.10/dist-packages/ansible/inventory/manager.py /srcCsg|] }dtt|qS)s%s$)r reescaperrrrr0s|a>^ (.+) # A pattern expression ending with... \[(?: # A [subscript] expression comprising: (-?[0-9]+)| # A single positive or negative number ([0-9]+)([:-]) # Or an x:y or x: range. ([0-9]*) )\] $ cCspg}g}g}|D]"}|s q|ddkr||q|ddkr%||q||q|gkr2dg}|||S)zS takes a list of patterns and reorders them by modifier to apply them consistently r!&all)append)patternspattern_regularpattern_intersectionpattern_excludeprrrorder_patternsAs      r&cCst|trdd|D}ttj|St|tst|dd}d|vr)|d}n!z t|dd\}}|g}Wnt yIt td|t j }Ynwd d |DS) a Takes a string containing host patterns separated by commas (or a list thereof) and returns a list of single patterns (which may not contain commas). Whitespace is ignored. Also accepts ':' as a separator for backwards compatibility, but it is not recommended due to the conflict with IPv6 addresses and host ranges. Example: 'a,b[1], c[2:3] , d' -> ['a', 'b[1]', 'c[2:3]', 'd'] css|]}t|VqdSN)split_host_patternrr%rrr jz%split_host_pattern..surrogate_or_stricterrors,T) allow_rangesaJ(?: # We want to match something comprising: [^\s:\[\]] # (anything other than whitespace or ':[]' | # ...or... \[[^\]]*\] # a single complete bracketed expression) )+ # occurring once or more cSsg|] }|r|qSr)stripr)rrrrz&split_host_pattern..) isinstancelist itertoolschain from_iterabler r splitr ExceptionrfindallX)patternresultsr!baseportrrrr(]s"       r(c@seZdZdZd@ddZeddZedd Zed d ZdAd d Z ddZ ddZ ddZ ddZ ddZdBddZdBddZddZdd Zd!d"ZdCd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/ZdDd0d1Zd2d3Zd4d5Zd6d7Zd8d9Zd:d;Zdd?Z!dS)EInventoryManagerz Creates and manages inventory NTcCsp||_t|_d|_d|_i|_i|_|durg|_n t|t r%|g|_n||_|r0|j |dg|_ g|_ dS)Ncache) _loaderr _inventory _restriction_subset_hosts_patterns_cache_pattern_cache_sourcesr3r parse_sources_cached_dynamic_hosts_cached_dynamic_grouping)selfloadersourcesparserBrrr__init__s    zInventoryManager.__init__cCs |jdS)N localhostrDget_hostrMrrrrRs zInventoryManager.localhostcC|jjSr')rDgroupsrUrrrrWzInventoryManager.groupscCrVr')rDhostsrUrrrrYrXzInventoryManager.hostscCs|j|||Sr')rDadd_host)rMhostgroupr?rrrrZszInventoryManager.add_hostcC |j|Sr')rD add_group)rMr\rrrr^ zInventoryManager.add_groupcCs |jSr')rDget_groups_dictrUrrrr` z InventoryManager.get_groups_dictcCs||jSr') clear_cachesrDreconcile_inventoryrUrrrrcs z$InventoryManager.reconcile_inventorycCr]r'rS)rMhostnamerrrrTr_zInventoryManager.get_hostcCsRtdg}tjD]}t|}|r||q td|q |s'td|S)z, sets up loaded inventory plugins for usage zsetting up inventory pluginsz,Failed to load inventory plugin, skipping %sz^No inventory plugins available to generate inventory, make sure you have at least one enabled.) displayvvvvCINVENTORY_ENABLEDrgetr warningr)rMpluginsnamepluginrrr_fetch_inventory_pluginss    z)InventoryManager._fetch_inventory_pluginsFcCsd}|jD]}|r d|vrt|dd}|j||d}|r |s d}q|r)|jntjr0tdtjr8t d|j D]}t |jt|j|j|gd|_q=|j D]}t |jt|j|j|gd|_qTd S) zA iterate over inventory sources and parse each one to populate itFr/)followrATzENo inventory was parsed, please check your configuration and options.z=No inventory was parsed, only implicit localhost is available inventoryN)rIr parse_sourcerDrcrgINVENTORY_UNPARSED_IS_FAILEDrINVENTORY_UNPARSED_WARNINGrerjrWvaluesrvarsrrCrY)rMrBparsedsourcerPr\r[rrrrJs(      zInventoryManager.parse_sourcesc Csd}g}td|t|}tj|rStd|tt|D].}td|t |r2q#t tj ||dd}|j ||d}td||f|sQ|}q#n||j _|D]} t t| d t| d d } td | | jfz t| |} Wn tyd} Ynw| rz)| j|j |j||dz| Wn tyYnwd }td|| fWnnty} z%td|| fd ttd} ||| | | dWYd} ~ q[d} ~ wty} z'td| |fd ttd} ||| t | | dWYd} ~ q[d} ~ wwtd| |fq[|r0|j j!|j jnH|dks.csg|] }|jvr|qSrrrh) subset_uuidsrrrz.InventoryManager.get_hosts..csg|] }|jjvr|qSr)rlrErrUrrrr2)rreverse_sortedrlr)keyreversereverse_inventoryr)Nrpz1Invalid 'order' specified for inventory hosts: %s)r3r4rFextendrEtuplerGr(_evaluate_patternssetrrrrr) rMr< ignore_limitsignore_restrictionsorderrY pattern_list pattern_hashr!r)rMrr get_hostsss@         $  zInventoryManager.get_hostscst|}g}|D]T}||jjvr||j|q|||ddkr3tfdd|D}q|ddkrGtfdd|D}qtdd|D|fd dDq|S) z Takes a list of patterns and returns a list of matching host names, taking into account any negative and intersection patterns. rrcsg|]}|vr|qSrrrthatrrrz7InventoryManager._evaluate_patterns..rcsg|]}|vr|qSrrrrrrrrcsrr'rl)ryrrrr*rz6InventoryManager._evaluate_patterns..csg|] }|jvr|qSrrr)existing_hostsrrrr)r&rDrYr rT_match_one_patternrr)rMr!rYr%r)rrrrs    z#InventoryManager._evaluate_patternscCsz|ddvr |dd}||jvr8||\}}||}z|||}Wn ty2td|w||j|<|j|S)a Takes a single pattern and returns a list of matching host names. Ignores intersection (&) and exclusion (!) specifiers. The pattern may be: 1. A regex starting with ~, e.g. '~[abc]*' 2. A shell glob pattern with ?/*/[chars]/[!chars], e.g. 'foo*' 3. An ordinary word that matches itself only, e.g. 'foo' The pattern is matched using the following rules: 1. If it's 'all', it matches all hosts in all groups. 2. Otherwise, for each known group name: (a) if it matches the group name, the results include all hosts in the group or any of its children. (b) otherwise, if it matches any hosts in the group, the results include the matching hosts. This means that 'foo*' may match one or more groups (thus including all hosts therein) but also hosts in other groups. The built-in groups 'all' and 'ungrouped' are special. No pattern can match these group names (though 'all' behaves as though it matches, as described above). The word 'ungrouped' can match a host of that name, and patterns like 'ungr*' and 'al*' can match either hosts or groups other than all and ungrouped. If the pattern matches one or more group names according to these rules, it may have an optional range suffix to select a subset of the results. This is allowed only if the pattern is not a regex, i.e. '~foo[1]' does not work (the [1] is interpreted as part of the regex), but 'foo*[1]' would work if 'foo*' matched the name of one or more groups. Duplicate matches are always eliminated from the results. r)rrrNz-No hosts matched the subscripted pattern '%s')rH_split_subscript_enumerate_matches_apply_subscript IndexErrorr)rMr<exprslicerYrrrrs &       z#InventoryManager._match_one_patterncCs|ddkr |dfSd}t|}|r=|\}}}}}|r(t|df}||fS|s,d}t|t|f}|dkr=td||fS)aa Takes a pattern, checks if it has a subscript, and returns the pattern without the subscript and a (start,end) tuple representing the given subscript (or None if there is no subscript). Validates that the subscript is in the right syntax, but doesn't make sure the actual indices make sense in context. rrNr-zFUse [x:y] inclusive subscripts instead of [x-y] which has been removed)PATTERN_WITH_SUBSCRIPTrrWintrerj)rMr< subscriptmidxstartsependrrrrs    z!InventoryManager._split_subscriptcCsF|r|s|S|\}}|r|dkrt|d}|||dS||gS)z Takes a list of hosts and a (start,end) tuple and returns the subset of hosts based on the subscript (which may be None to return all hosts). rr)len)rMrYrrrrrrrs  z!InventoryManager._apply_subscriptc sg}||jj}|r|D] }||jj|q|r/ddks/tfdddDrG||jj}|rG|D] }||jj|q;|s[tj vr[|j }|r[|||s|sdkrd}t |tj dkrxt ||Stj d krt||S) z Returns a list of host names matching the given pattern according to the rules explained above in _match_one_pattern. rrc3s|]}|vVqdSr'r)rspecialr<rrr*;r+z6InventoryManager._enumerate_matches..).?*[rz3Could not match supplied host pattern, ignoring: %srjerror)rrDrWrranyrYr rg LOCALHOSTrTrerHOST_PATTERN_MISMATCHrjr) rMr<r=matching_groups groupnamematching_hostsrdimplicitmsgrrrr-s.&      z#InventoryManager._enumerate_matchescCs*||}t|dkr|tjvr|g}|S)z* return a list of hostnames for a pattern r)rrrgr)rMr<rrrr list_hostsTs zInventoryManager.list_hostscCst|jjSr')rrDrWkeysrUrrr list_groups_szInventoryManager.list_groupscCs4|durdSt|ts|g}tdd|D|_dS)z Restrict list operations to the hosts given in restriction. This is used to batch serial operations in main playbook code, don't use this for other reasons. Ncss|]}t|jVqdSr')r rlrrrrr*msz5InventoryManager.restrict_to_hosts..)r3r4rrE)rM restrictionrrrrestrict_to_hostscs  z"InventoryManager.restrict_to_hostsc Cs|dur d|_dSt|}g}|D]V}|sq|ddkr`t|dd}tj|s0td|tj|s. )rFr(r rrrrisfileopenrreadr8r r )rMsubset_patternsubset_patternsr=r b_limit_filefdrrrsubsetos&         zInventoryManager.subsetcCs d|_dS)z! Do not restrict list operations N)rErUrrrremove_restrictions z#InventoryManager.remove_restrictioncCs i|_dSr')rHrUrrrclear_pattern_cacheraz$InventoryManager.clear_pattern_cachec Csd}|ds |j||rq|d}||jvr!||dd}|j|}|}t||dt}||kr>||_d}|dg}|D]} | |j vrU|j | } d}|j | } | |j|rdd}qF|rk| ||d<d Sd S) zX Helper function to add a new host to inventory based on a task result. Fr host_namerT host_varsrWchangedN) rirKr rYrZget_varsrdictrurWrDr^rc) rM host_info result_itemrrnew_host new_host_varsnew_host_combined_vars new_groups group_name new_grouprrrrs6           z!InventoryManager.add_dynamic_hostc Cs,d}|ds|j||f|j|j}|dur3|j|jjkr%|j}n|ds1td|jdS|d}|dg}||jvrH||}|D]}||jvrX||d}qJ|j j|}|D]} |j| } | |} | rs|ssd}qa|| vr| |}|| vr||}|r|||d<dS) z Helper function to add a group (if it does not exist), and to assign the specified host to that group. FrNz!%s cannot be matched in inventoryr^ parent_groupsTr)rirLr rYrlrRrrWr^rDadd_child_grouprrZ get_groupsrc) rMr[rr real_hostr parent_group_namesrlr\parent_group_name parent_groupnewrrrrsB                z"InventoryManager.add_dynamic_group)NTT)NN)F)rFFN)r)"__name__ __module__ __qualname____doc__rQpropertyrRrWrYrZr^r`rcrTrnrJrqrbrrrrrrrrrrrrrrrrrrrrr@sD       \ 94! '   (r@)7 __future__rrrrrr5roperatorrrandomransiblerrgansible.errorsrrransible.inventory.datar ansible.module_utils.sixr +ansible.module_utils.common.text.convertersr r ansible.parsing.utils.addressesr ansible.plugins.loaderransible.utils.helpersransible.utils.pathransible.utils.displayransible.utils.varsransible.vars.pluginsrreIGNORED_ALWAYSINVENTORY_IGNORE_PATTERNSIGNORED_PATTERNSINVENTORY_IGNORE_EXTS IGNORED_EXTSrrrr;rr&r(objectr@rrrrsB              .