hamayuzinの日記

ITベンチャーに新卒入社し、エンジニアとかデータサイエンティスト、とかやってます。あの時 あれやってたな的な備忘録にできれば。

【ansible/aws】ansibleで ec2にrbenvでrubyをinstall

リポジトリはこちら github.com

目次

構成

.
├── ec2-server.retry
├── hosts
│   └── ec2-servers
└── roles
    └── aws
        ├── rbenv
            └── tasks
                └── main.yml

やること

  • rbenv install
  • ruby install
  • railsに必要そうなものinstall

ec2-server.yml

変数を管理

- hosts: servers
  remote_user: ec2-user
  become: yes
  vars:
    rbenv_user: webmaster
    rbenv_ruby_version: 2.4.1
  roles:
    - aws/rbenv

roles/aws/rbenv/tasks/main.yml

---
- name: Install dependencies for rbenv
  yum: name={{ item }} state=latest
  with_items:
    - git

- name: Install rbenv
  become: yes
  become_user: "{{ rbenv_user }}"
  git: repo=https://github.com/sstephenson/rbenv.git dest=~/.rbenv

- name: Add ~.rbenv/bin to PATH
  become: yes
  become_user: "{{ rbenv_user }}"
  lineinfile: >
    dest="~/.bash_profile"
    line="export PATH=$HOME/.rbenv/bin:$PATH"

- name: Eval rbenv init in ~/.bash_profile
  become: yes
  become_user: "{{ rbenv_user }}"
  lineinfile: >
    dest="~/.bash_profile"
    line='eval "$(rbenv init -)"'

- name: Install dependencies for ruby-build (see. https://github.com/sstephenson/ruby-build/wiki)
  yum: name={{ item }} state=latest
  with_items:
    - gcc
    - openssl-devel
    - libyaml-devel
    - libffi-devel
    - readline-devel
    - zlib-devel
    - gdbm-devel
    - ncurses-devel

- name: Install ruby-build as rbenv plugin
  become: yes
  become_user: "{{ rbenv_user }}"
  git: repo=https://github.com/sstephenson/ruby-build.git dest=~/.rbenv/plugins/ruby-build

- name: Check if version is installed ruby
  shell: "sudo -iu {{ rbenv_user }} rbenv versions | grep {{ rbenv_ruby_version }}"
  register: rbenv_check_install
  changed_when: False
  ignore_errors: yes

- name: Install ruby
  command: "sudo -iu {{ rbenv_user }} rbenv install {{ rbenv_ruby_version }}"
  when: rbenv_check_install|failed

- name: Check if version is the default ruby version
  shell: "sudo -iu {{ rbenv_user }} rbenv version | grep {{ rbenv_ruby_version }}"
  register: rbenv_check_default
  changed_when: False
  ignore_errors: yes

- name: Set default ruby version
  command: "sudo -iu {{ rbenv_user }} rbenv global {{ rbenv_ruby_version }}"
  when: rbenv_check_default|failed

- name: Install packages
  yum: name={{ item }} state=latest
  with_items:
    - mysql-devel
    - gcc-c++
    - make
    - patch
    - libyaml-devel
    - libffi-devel
    - libicu-devel
    - libxml2
    - libxslt
    - libxml2-devel
    - libxslt-devel
    - zlib-devel
    - readline-devel
    - mysql
    - mysql-server
    - mysql-devel

- name: Install bundler
  become_user: "{{ rbenv_user }}"
  gem: name={{ item }} executable=.rbenv/shims/gem user_install=False
  with_items:
    - bundler