访问任务中的ansible.cfg变量

访问任务中的ansible.cfg变量,ansible,ansible-playbook,ansible-2.x,Ansible,Ansible Playbook,Ansible 2.x,如何在任务中引用ansible.cfg中定义的remote\u 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

如何在任务中引用
ansible.cfg
中定义的
remote\u 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插件来读取不同的配置参数。
如果您使用action插件,则必须调用新创建的action来定义
remote\u tmp

如果您选择vars插件方式,
remote\u tmp
将在资源清册初始化期间与其他主机VAR一起定义

示例
/vars\u plugins/tmp\u 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\u plugins
文件夹应该在您的
hosts
文件附近,或者您应该在ansible.cfg中明确定义它

现在,您可以使用以下工具进行测试:

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

您可以使用
查找

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"

你有没有试过
{{remote\u tmp}
?@sircapsalot,当然,
'remote\u tmp'是未定义的
。这让我相信
ansible.cfg
文件没有被正确读取。你的cfg文件在哪里?项目根?@sircapsalot,我有自己的
ansible.cfg
位于我的项目目录的根目录中,只有一个条目
[默认值]\nroles\u path=/home/deploy/devops/ansible/roles
。哦,我的错误。你说得对。如果我注意到了什么,我会让你知道,如果当前目录中没有ansible.cfg怎么办?Ivan写道,“我有我自己的ansible.cfg,位于我的项目目录的根目录中”,这种方法在这种情况下有效。我更新了我的答案,以便它与任何
ansible.cfg
位置一起工作。这不是一种非常可靠的方法。它在某些配置中会失败(安装了自制Python的macOS,可能是一些Python虚拟机)。确定使用的配置文件的一种方法是运行
ansible playbook--version
并解析输出。但它可能不会给出与当前进程相同的结果。最重要的是,如果设置不存在,这将失败。