在AnsibleAPI2.9中相对于2.7少了extend_vars方法
通过对源码的分析发现在ansible.utils.vars中的load_extra_vars函数中把所有的参数添加进去
def load_extra_vars(loader): extra_vars = {} for extra_vars_opt in context.CLIARGS.get('extra_vars', tuple()): data = None extra_vars_opt = to_text(extra_vars_opt, errors='surrogate_or_strict') if extra_vars_opt.startswith(u"@"): # Argument is a YAML file (JSON is a subset of YAML) data = loader.load_from_file(extra_vars_opt[1:]) elif extra_vars_opt and extra_vars_opt[0] in u'[{': # Arguments as YAML data = loader.load(extra_vars_opt) else: # Arguments as Key-value data = parse_kv(extra_vars_opt) if isinstance(data, MutableMapping): extra_vars = combine_vars(extra_vars, data) else: raise AnsibleOptionsError("Invalid extra vars data supplied. '%s' could not be made into a dictionary" % extra_vars_opt) return extra_vars
在参数管理类VariableManager的初始化中调用了load_options_vars函数并赋值给_extra_vars
class VariableManager: _ALLOWED = frozenset(['plugins_by_group', 'groups_plugins_play', 'groups_plugins_inventory', 'groups_inventory', 'all_plugins_play', 'all_plugins_inventory', 'all_inventory']) def __init__(self, loader=None, inventory=None, version_info=None): self._nonpersistent_fact_cache = defaultdict(dict) self._vars_cache = defaultdict(dict) self._extra_vars = defaultdict(dict) self._host_vars_files = defaultdict(dict) self._group_vars_files = defaultdict(dict) self._inventory = inventory self._loader = loader self._hostvars = None self._omit_token = '__omit_place_holder__%s' % sha1(os.urandom(64)).hexdigest() self._options_vars = load_options_vars(version_info) # If the basedir is specified as the empty string then it results in cwd being used. # This is not a safe location to load vars from. basedir = self._options_vars.get('basedir', False) self.safe_basedir = bool(basedir is False or basedir) # load extra vars self._extra_vars = load_extra_vars(loader=self._loader) # load fact cache try: self._fact_cache = FactCache() except AnsibleError as e: # bad cache plugin is not fatal error # fallback to a dict as in memory cache display.warning(to_text(e)) self._fact_cache = {}
解决办法是新建VariableManagerExtra类并继承VariableManager类,在里面定义extend_vars方法用于添加额外的参数(如默认的账号密码)
class VariableManagerExtra(VariableManager): def extend_vars(self,extra_vars): self._extra_vars.update(extra_vars)
至此完成了对AnsibleAPI2.9添加默认账号密码的功能开发