Ansible - Set environment path as inventory variable

和自甴很熟 提交于 2021-01-28 12:20:02

问题


Osmc media player needs a specific path for playbooks https://github.com/osmc/osmc/issues/319

environment:
  PATH: "{{ ansible_env.PATH }}:/sbin:/usr/sbin"

I was wondering whether I can set this as an environmental variable in the inventory for those machines, rather than have it in every playbook or create separate playbooks.

In common usage - is that path likely to cause problems for general *nix machines if it is implemented on non-osmc installations?

If you can't set this an an inventory variable: Is that just because it's no implemented/ useful to most? Or because the inventory has no relation to path - e.g. it's not invoked at that point?

Or is a better way for all of this to have it as a machine specific variable/ task in a role? How would that look please?

New to ansible and still trying to get my head round some of the concepts.


回答1:


As said, the environment keyword can be used only at task or playbook level.

You will be able to use an standard playbook just adding the following:

---
- name: Environment
  hosts: localhost
  connection: local
  gather_facts: False

  tasks:

  - name: Setup
    setup:
      gather_subset:
        - "!all"

or

---
- name: Environment
  hosts: localhost
  connection: local
  gather_facts: True
  gather_subset:
    - "!all"

If you debug the variable:

---
- name: Environment
  hosts: localhost
  connection: local
  gather_facts: False

  tasks:

  - name: Setup
    setup:
      gather_subset:
        - "!all"

  - name: Debug
    debug:
      var: ansible_env.PATH

You will get something like:

TASK [Setup] *******************************************************************************************************************************************************
ok: [localhost]

TASK [Debug] *******************************************************************************************************************************************************
ok: [localhost] => {
    "ansible_env.PATH": "/Users/imjoseangel/source/venv/ansible/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
}

And what if you want to pass that variable to another play with different inventory?

Just do hostvars.localhost.ansible_env.PATH

- name: Environment2
  hosts: windows
  connection: local
  gather_facts: False


  tasks:

  - name: Debug
    debug:
      var: hostvars.localhost.ansible_env.PATH

So the

environment:
  PATH: "{{ ansible_env.PATH }}:/sbin:/usr/sbin"

Will be valid only with gather_facts or setup module under the defined inventory but you don't need to split playbooks.



来源:https://stackoverflow.com/questions/52060350/ansible-set-environment-path-as-inventory-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!