设为首页 收藏本站
查看: 1082|回复: 0

[经验分享] Ansible源码解析Inventory总管概念__init__.py

[复制链接]

尚未签到

发表于 2018-7-29 08:52:04 | 显示全部楼层 |阅读模式
class Inventory(object):  """
  Host inventory for ansible.
  """
  __slots__ = [ 'host_list', 'groups', '_restriction', '_also_restriction', '_subset',
  'parser', '_vars_per_host', '_vars_per_group', '_hosts_cache', '_groups_list',
  '_pattern_cache', '_vault_password', '_vars_plugins', '_playbook_basedir']
  def __init__(self, host_list=C.DEFAULT_HOST_LIST, vault_password=None):
  # the host file file, or script path, or list of hosts
  # if a list, inventory data will NOT be loaded
  # 就是这个host_list非常关键,我们要获取inventory按照格式给一个script就行
  # 注意加载中文的时候加一个.decode("utf-8")
  self.host_list = host_list
  self._vault_password=vault_password
  # caching to avoid repeated calculations, particularly with
  # external inventory scripts.
  # 这里做一些缓存,避免重复计算,但是指同一个实例。
  self._vars_per_host  = {}
  self._vars_per_group = {}
  self._hosts_cache    = {}
  self._groups_list    = {}
  self._pattern_cache  = {}
  # to be set by calling set_playbook_basedir by playbook code
  self._playbook_basedir = None
  # the inventory object holds a list of groups
  self.groups = []
  # a list of host(names) to contain current inquiries to
  self._restriction = None
  self._also_restriction = None
  self._subset = None
  # 条件1,如果是字符串并且,在字符串中,进行赋值
  # 注意这个if与下面的if不是一个逻辑,这是先行逻辑
  if isinstance(host_list, basestring):
  if "," in host_list:
  host_list = host_list.split(",")
  host_list = [ h for h in host_list if h and h.strip() ]
  # 注意这里会输出一个列表
  if host_list is None:
  self.parser = None
  # 接着上面的处理, 匹配IPV6,使用host类实例化主机名然后添加主机
  elif isinstance(host_list, list):
  self.parser = None
  all = Group('all')
  self.groups = [ all ]
  ipv6_re = re.compile('\[([a-f:A-F0-9]*[%[0-z]+]?)\](?::(\d+))?')
  for x in host_list:
  m = ipv6_re.match(x)
  if m:
  all.add_host(Host(m.groups()[0], m.groups()[1]))
  else:
  if ":" in x:
  tokens = x.rsplit(":", 1)
  # if there is ':' in the address, then this is an ipv6
  if ':' in tokens[0]:
  all.add_host(Host(x))
  else:
  all.add_host(Host(tokens[0], tokens[1]))
  else:
  all.add_host(Host(x))
  # 如果这个文件名存在,即走文件名方式,判断是否是目录,是目录调dir解析
  # 是文件就是脚本解析,即我们讲的动态inventory,走不通这个就走ini配置文件解析
  # 这里的判断点就是SheBang(#!)
  elif os.path.exists(host_list):
  if os.path.isdir(host_list):
  # Ensure basedir is inside the directory
  self.host_list = os.path.join(self.host_list, "")
  self.parser = InventoryDirectory(filename=host_list) # 目录解析
  self.groups = self.parser.groups.values()
  else: # 动态inventory
  # check to see if the specified file starts with a
  # shebang (#!/), so if an error is raised by the parser

  #>  shebang_present = False
  try:
  inv_file = open(host_list)
  first_line = inv_file.readlines()[0]
  inv_file.close()
  if first_line.startswith('#!'):
  shebang_present = True
  except:
  pass
  if utils.is_executable(host_list):
  try:
  self.parser = InventoryScript(filename=host_list) # 脚本解析
  self.groups = self.parser.groups.values()
  except:
  if not shebang_present:
  raise errors.AnsibleError("The file %s is marked as executable, but failed to execute correctly. " % host_list + \
  "If this is not supposed to be an executable script, correct this with `chmod -x %s`." % host_list)
  else:
  raise
  else:
  try:
  self.parser = InventoryParser(filename=host_list) # 文件解析
  self.groups = self.parser.groups.values()
  except:
  if shebang_present:
  raise errors.AnsibleError("The file %s looks like it should be an executable inventory script, but is not marked executable. " % host_list + \
  "Perhaps you want to correct this with `chmod +x %s`?" % host_list)
  else:
  raise
  utils.plugins.vars_loader.add_directory(self.basedir(), with_subdir=True)
  else:
  raise errors.AnsibleError("Unable to find an inventory file, specify one with -i ?")
  self._vars_plugins = [ x for x in utils.plugins.vars_loader.all(self) ]
  # get group vars from group_vars/ files and vars plugins
  for group in self.groups:
  group.vars = utils.combine_vars(group.vars, self.get_group_variables(group.name, vault_password=self._vault_password))
  # get host vars from host_vars/ files and vars plugins
  for host in self.get_hosts():
  host.vars = utils.combine_vars(host.vars, self.get_host_variables(host.name, vault_password=self._vault_password))

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-542815-1-1.html 上篇帖子: ansible 的Playbook-13147015 下篇帖子: Ansible源码解析Inventory动态inventory脚本解析script.py
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表