3

I have 2 machines for my two environments.

The first one hosts a staging environment. It needs to have NODE_ENV set to dev.

The second one hosts a production environment. It needs to have NODE_ENV set to prod.

I provision my servers with Ansible.

How can I do this ?

Raphaël
  • 1,924
  • 2
  • 18
  • 22

2 Answers2

5

Another option is set NODE_ENV at /etc/environment file.

In ansible tasks:

- lineinfile: dest=/etc/environment line="NODE_ENV=dev"

João Maia
  • 91
  • 1
  • 3
  • The issue I have with this answer is that it will append NODE_ENV=dev every time the playbook is run. Which can ultimately lead to a large environment file – Joseph Bisaillon Jan 20 '17 at 21:00
3

I solved the problem like so.

In roles/node-env/tasks/main.yml :

---
- name: Configure NODE_ENV
  lineinfile: dest=/etc/environment regexp="^NODE_ENV=" line="NODE_ENV={{ node_env }}"
  when: node_env is defined

In hosts/staging:

[webserver]
staging-server-hostname

[webserver:vars]
node_env=dev

In hosts/production:

[webserver]
production-server-hostname

[webserver:vars]
node_env=prod

In playbook.yml:

---
- name: Provision web server
  hosts: webserver
  sudo: true
  roles:
    - { role: Stouts.nodejs, tags: nodejs }
    - ...
    - { role: node-env, tags: nodejs }

Then I provision my staging environment with:

ansible-playbook -i hosts/staging playbook.yml

And my production environment with:

ansible-playbook -i hosts/production playbook.yml

Note that I stored my environment variable in /etc/environment because I wanted this variable set one for all and for every users.

This can also be stored in ~/.profile or in /etc/profile.d according to your needs. See this answer for more information.

It might be overkill, but it's flexible. If anyone has a simplier suggestion don't hesitate to share!

Community
  • 1
  • 1
Raphaël
  • 1,924
  • 2
  • 18
  • 22