Raphaël
Raphaël

Reputation: 2051

How can I set NODE_ENV permanently with ansible?

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 ?

Upvotes: 3

Views: 2220

Answers (2)

João Maia
João Maia

Reputation: 91

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

In ansible tasks:

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

Upvotes: 5

Raphaël
Raphaël

Reputation: 2051

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!

Upvotes: 3

Related Questions