ansibleでnvmを管理する


ansibleでnvmを管理する

nodejsのバージョンを最新にしておきたいということでyumではなくnvmを入れてnodejsを入れます。
サーバはansibleで全てを管理しているのでnvmもansibleで入れるんですが

  • 既存のものはユーザごとにインストールする系しかない -> システム共通で入れたい
  • command:でもshell:でもそのままだとnvmが実行できない

ことからredhat系で手直し版を作ったところ、わりかし面倒だったのでまとめときます。

を参考にしてます。

問題点

まずシステム全体にnvmコマンドを置くためにnvm.shは/etc/profile.d/以下としたいところですが、インストールを行ったディレクトリにバイナリが配置されるので直接置くと残念なことになります。

そのため、インストール用のディレクトリ{{nvm_install_dir}}を用意した上で、/etc/profile.d/nvm.shからそこを参照させるようにしました。

また、nvmは実体のあるコマンドではないので、command:だと実行がこけてしまう上、ansibleは/etc/profileをデフォルトは見ないということもあり、nvm実行はすべてsource /etc/profileをした上でshell:で実行させています。
nvm実行はこのroleからしか行わないので割り切ってます。

最後に、/etc/profileを読み込まない問題はnodenpmにも及ぶので、/usr/binにリンクを貼ってしまうことで解決しansibleのモジュールnpm:npmがそのまま使えるようにします。

nvm_node_versionを変えたらnvmのdefaultのnodeが変わり、which nodewhich npmも変わるのでバージョンが差し代わることになります。

roles/nvm

tasks/main.yml
- name: install requirements nvm
  yum: name={{item}} state=installed
  with_items: [ "gcc", "gcc-c++", "make", "openssl-devel", "zlib-devel", "gyp", "glibc-devel" ]

- name: create nvm directoryc
  file: dest={{nvm_install_dir}} state=directory
  tags: nvm

- name: install nvm
  get_url: url=https://raw.githubusercontent.com/creationix/nvm/{{nvm_version}}/nvm.sh dest={{nvm_install_dir}}/nvm.sh
  tags: nvm

- name: set profile
  template: src=nvm.sh.j2 dest=/etc/profile.d/nvm.sh
  tags: nvm

- name: Install {{ nvm_node_version }}
  shell: source /etc/profile && nvm install {{ nvm_node_version }}
  register: nvm_install_result
  changed_when: "'is already installed.' not in nvm_install_result.stdout"
  tags: nvm

- name: Check if {{ nvm_node_version }} is the default node version
  shell: source /etc/profile && nvm ls | grep -e 'default -> {{ nvm_node_version }}'
  register: nvm_check_default
  changed_when: False
  ignore_errors: True
  tags: nvm

- name: Set default node version to {{ nvm_node_version }}
  shell: source /etc/profile &&  nvm alias default {{ nvm_node_version }}
  when: nvm_check_default|failed
  tags: nvm

- name: which node
  shell: source /etc/profile &&  which node
  register: nvm_node_install_path
  changed_when: false
  tags: nvm

- name: link bin node
  file: src="{{nvm_node_install_path.stdout}}" dest=/usr/bin/node state=link force=yes
  when: nvm_node_install_path.stdout is defined

- name: which npm
  shell: source /etc/profile &&  which npm
  register: nvm_npm_install_path
  changed_when: false
  tags: nvm

- name: link bin npm
  file: src="{{nvm_npm_install_path.stdout}}" dest=/usr/bin/npm state=link force=yes
  when: nvm_npm_install_path.stdout is defined
templates/nvm.sh.j2
#!/bin/sh

source {{nvm_install_dir}}/nvm.sh
defaults/main.yml
nvm_version: v0.4.0
nvm_install_dir: /opt/nvm
nvm_node_version: "0.10"