Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read environment from a file

Tags:

ansible

I would like to supply Ansible with my environment variables, either through a YAML file that Ansible reads, or through an inventory file. The goal is to let the user -- who has control over either the inventory file or the new YAML file -- supply whatever environment variables that they see fit to the (host-specific) environment. Something like the following is what I'm shooting for:

# start/provision.yml
- hosts: app1server
  vars:
    include: ../env_vars.yml
  roles:
    - python27
    - app1
  environment: env_vars

where env_vars.yml lives in start/ and has the following sort of layout:

---
# file: start/env_vars.yml
env_vars:
    PATH: /usr/local/nonsense
    http_proxy: http://aplacenothere

and where the filename env_vars.yml would itself be a parameter in the inventory file.

Is there an easy fix to the above? What are my options for feeding environment arbitrary variables for each host?

like image 927
snl Avatar asked Mar 14 '23 12:03

snl


1 Answers

I think the code snippets you posted are already very close. So close I'm not sure If your question is how to archive the goal or if you ask why it doesn't work.

The only thing that IMHO is not correct is how you try to include the variables. Instead of vars you should use vars_files on the playbook level:

- hosts: app1server
  vars_files:
    - "{{ env_file }}"
  roles:
    - python27
    - app1
  environment: env_vars

Then you would call ansible with --extra-vars="env_file=some/file.yml"

I'm not 100% sure the environment on playbook level works. According to the docs it should. But I recently read a question here on SO where someone was asking why it did not.

If it really does not work, that's a bug. Try to upgrade Ansible to the latest version then. If it still does not work, you should report it as a bug on github. The only possible workaround then would be to apply environment to to all your roles:

roles:
  - role: python27
    environment: env_vars
  - role: app1
    environment: env_vars

And if it still does not work, apply it to every single task inside the roles.


Found the other question, which in the meantime was answered. So that was a bug in a very old version. It should work in the latest 1.9.x or 2.x versions.

like image 101
udondan Avatar answered Mar 16 '23 00:03

udondan