モチベーション
最近,複数の計算機にRをインストールする場面がありました.その際に1回ずつ計算機に接続をしてRをインストールするのは面倒だと思い,一度にインストールをするためにAnsibleを使いました.
Ansibleとは
Ansibleは,サーバーの設定管理・自動化ツールです.
特徴
- エージェントレス: ノード側に特別なソフトウェア不要(SSHのみ)
- 冪等性: 何度実行しても同じ結果になる
- YAML形式: 人間が読みやすい設定ファイル
- Python製: 多くのLinuxで標準的に動作
構成要素
- コントロールノード: Ansibleを実行するマシン
- マネージドノード: 管理対象のマシン
- インベントリ: 管理対象のリスト
- Playbook: 自動化の手順書(YAML形式)
- モジュール: 実行する処理の単位(apt,copy,serviceなど)
詳しくは,公式のWebサイトや以下の記事を見てください.
環境
コントロールノード:macOS Sequoia 15.7.2 x86_64
マネージドノード:Ubuntu 24.04.3 LTS(Nobel Numbat)
Ansibleのインストール
マスターノード(mac)実行
# homebrewからインストール
brew install ansible
# インストール確認
ansible --version
環境の準備
任意ですが,SSH接続の認証を鍵認証にしておきます(パスワード認証でもAnsibleは利用できますが,鍵認証のほうが個人的には快適です).
SSH鍵の準備
# 鍵がない場合は作成
ssh-keygen -t ras -b 4096
# ノードに公開鍵をコピー
# ホスト名とIPは自身の環境に合わせてください
ssh-copy-id ubuntu@172.16.200.10
Task failed: failed to connect to the host via ssh: Host key verification failedみたいなエラーが出たら各ノードに一度手動で接続してフィンガープリントを登録しておきましょう.
SSH接続テスト
パスワードの入力が不要になるはずです.
ssh ubuntu@192.168.1.10
インベントリファイルの作成
inventory.iniを作成
[ubuntu_nodes]
node1 ansible_host=172.16.200.10 ansible_user=hoge
node2 ansible_host=172.16.200.11 ansible_user=hoge
[ubuntu_nodes:vars]
ansible_python_interpreter=/usr/bin/python3
-
ubuntu_nodes: ホストグループ名 -
node1: ホストの別名 -
ansible_host: 実際のIPアドレス -
ansible_user: SSH接続ユーザー -
ansible_python_interpreter: Pythonのパス
pingモジュールで接続確認
うまくいったらSUCCESSみたいな感じのログが表示されると思います.
ansible -i inventory.ini ubuntu_nodes -m ping
Rのインストール
今回はCRANリポジトリからインストールします.
---
- name: Install Latest R from CRAN
hosts: ubuntu_nodes
become: yes
tasks:
- name: Update aot cache
apt:
update_cache: yes
- name: Install dependencies
apt:
name:
- software-properties-common
- dirmngr
- wget
- gnupg
state: present
update_cache: yes
- name: Add CRAN GPG key
apt_key:
url: https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc
state: present
- name: Add CRAN repo for Ubuntu 24.04
apt_repository:
repo: "deb https://cloud.r-project.org/bin/linux/ubuntu noble-cran40/"
state: present
filename: cran
- name: Update apt update_cache
apt:
update_cache: yes
- name: Install R base and dev tools
apt:
name:
- r-base
- r-base-dev
state: present
- name: Verify R installation
command: R --version
register: r_version
changed_when: false
- name: Display R version
debug:
msg: "Installed: {{ r_version.stdout_lines[0] }}"
- name: Test R can execute simple command
shell: echo "print('Hello from R')" | R --no-save --quiet
register: r_test
changed_when: false
- name: Show R test output
debug:
msg: "{{ r_test.stdout }}"
-
debug: メッセージやデータを表示 -
register: コマンド結果を変数に保存 -
become: yes: sudo権限で実行 -
apt モジュール-
update_cache: apt updateを実行 -
name: インストールするパッケージ名 -
state: present: インストールを保証
-
-
apt_key モジュール: GPG鍵の追加 -
apt_repository モジュール: 外部リポジトリの追加
実行:
ansible-playbook -i inventory.ini install_r_full.yml --ask-become-pass
これで完了です.