1. 程式人生 > 實用技巧 >ansibleAPI設定預設使用者及密碼

ansibleAPI設定預設使用者及密碼

在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新增預設賬號密碼的功能開發