在任务中访问 ansible.cfg 变量

Access ansible.cfg variable in task

如何在我的任务中引用 ansible.cfg 中定义的 remote_tmp(或任何其他)值?例如,在 my_task/defaults/main.yml:

file_ver: "1.5"
deb_file: "{{ defaults.remote_tmp }}/deb_file_{{ file_ver }}.deb"

产生错误:

fatal: [x.x.x.x]: FAILED! => {"failed": true, 
    "msg": "the field 'args' has an invalid value, 
            which appears to include a variable that is undefined. 
            The error was: {{ defaults.remote_tmp }}/deb_file_{{ file_ver }}.deb: 
           'defaults' is undefined\... }

你不能开箱即用。
您需要 action 插件或 vars 插件来读取不同的配置参数。
如果您采用动作插件方式,则必须调用新创建的动作来定义 remote_tmp
如果您选择 vars plugin 方式,remote_tmp 在库存初始化期间与其他主机 vars 一起定义。

示例./vars_plugins/tmp_dir.py

from ansible import constants as C

class VarsModule(object):

    def __init__(self, inventory):
        pass

    def run(self, host, vault_password=None):
        return dict(remote_tmp = C.DEFAULT_REMOTE_TMP)

请注意 vars_plugins 文件夹应该靠近您的 hosts 文件,或者您应该在 ansible.cfg.

中明确定义它

您现在可以使用以下方法对其进行测试:

$ ansible localhost -i hosts -m debug -a "var=remote_tmp"
localhost | SUCCESS => {
    "remote_tmp": "$HOME/.ansible/tmp"
}

您可以使用 lookup.

file_ver: "1.5"
deb_file: "{{ lookup('ini', 'remote_tmp section=defaults file=ansible.cfg' }}/deb_file_{{ file_ver }}.deb"

编辑

如果您不知道配置文件的路径,可以通过运行以下任务将其设置为事实。

- name: look for ansible.cfg, see http://docs.ansible.com/ansible/intro_configuration.html
  local_action: stat path={{ item }}
  register: ansible_cfg_stat
  when: (item | length) and not (ansible_cfg_stat is defined and ansible_cfg_stat.stat.exists)
  with_items:
    - "{{ lookup('env', 'ANSIBLE_CONFIG') }}"
    - ansible.cfg
    - "{{ lookup('env', 'HOME') }}/.ansible.cfg"
    - /etc/ansible/ansible.cfg

- name: set fact for later use
  set_fact:
    ansible_cfg: "{{ item.item }}"
  when: item.stat is defined and item.stat.exists
  with_items: "{{ ansible_cfg_stat.results }}"

然后你可以写:

file_ver: "1.5"
deb_file: "{{ lookup('ini', 'remote_tmp section=defaults file=' + ansible_cfg) }}/deb_file_{{ file_ver }}.deb"