问题
How can I refer remote_tmp
(or any other) value defined in ansible.cfg
in my tasks? For example, in the my_task/defaults/main.yml
:
file_ver: "1.5"
deb_file: "{{ defaults.remote_tmp }}/deb_file_{{ file_ver }}.deb"
produces an error:
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\... }
回答1:
You can't do this out of the box.
You either need action plugin or vars plugin to read different configuration parameters.
If you go action plugin way, you'll have to call your newly created action to get remote_tmp
defined.
If you choose vars plugin way, remote_tmp
is defined with other host vars during inventory initialization.
Example ./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)
Note that vars_plugins
folder should be near your hosts
file or you should explicitly define it in your ansible.cfg.
You can now test it with:
$ ansible localhost -i hosts -m debug -a "var=remote_tmp"
localhost | SUCCESS => {
"remote_tmp": "$HOME/.ansible/tmp"
}
回答2:
You can use lookup
.
file_ver: "1.5"
deb_file: "{{ lookup('ini', 'remote_tmp section=defaults file=ansible.cfg' }}/deb_file_{{ file_ver }}.deb"
EDIT
In case you don't know the path to the configuration file, you can set that to a fact by running the following tasks.
- 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 }}"
You can then write:
file_ver: "1.5"
deb_file: "{{ lookup('ini', 'remote_tmp section=defaults file=' + ansible_cfg) }}/deb_file_{{ file_ver }}.deb"
来源:https://stackoverflow.com/questions/40246768/access-ansible-cfg-variable-in-task