2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ansible基礎完全ガイド - インベントリからプレイブックまで初心者でもわかる自動化の仕組み

Posted at

はじめに

この記事では、IT自動化ツール「Ansible」の基本概念から実践的な使用方法まで、初心者にもわかりやすく解説します。
「インベントリって何?」「プレイブックってどう書くの?」といった疑問を持つ方でも、この記事を読めばAnsibleの全体像が理解できるようになります。

目次

  1. Ansibleとは
  2. Ansibleの基本アーキテクチャ
  3. 主要コンポーネントの詳細解説
  4. 実践編:簡単なプレイブックを作ってみよう
  5. よく使われるモジュール
  6. ベストプラクティス
  7. まとめ
  8. 参考文献

Ansibleとは

Ansibleは、Red Hat社が開発したオープンソースの構成管理・自動化ツールです。

主な特徴

  • エージェントレス: 管理対象サーバーに専用ソフトウェアをインストール不要
  • SSH接続: 標準的なSSH接続でリモートサーバーを管理
  • YAML記法: 人間が読みやすい設定ファイル
  • べき等性: 同じ操作を何度実行しても同じ結果になる

なぜAnsibleを使うのか?

手動作業の場合:
サーバー1台目 → SSH接続 → コマンド実行 → 設定変更
サーバー2台目 → SSH接続 → コマンド実行 → 設定変更
サーバー3台目 → SSH接続 → コマンド実行 → 設定変更
...繰り返し(ミスが発生しやすい)

Ansibleの場合:
プレイブック作成 → 一度の実行で全サーバーに適用
✓ 設定内容が標準化される
✓ 作業時間が大幅短縮
✓ ヒューマンエラーが減る

Ansibleの基本アーキテクチャ

┌─────────────────────────┐           ┌─────────────────────────┐
│   コントロールノード        │           │     管理対象ノード         │
│  (Ansibleを実行)         │           │   (構築されるサーバー)      │
│                        │           │                        │
│  ┌─────────────────┐    │    SSH    │  ┌─────────────────┐    │
│  │ ・Ansible本体    │    │◄─────────►│  │ ・Python        │    │
│  │ ・プレイブック   │    │   接続    │  │ ・SSH Daemon    │    │
│  │ ・インベントリ   │    │          │  │                │    │
│  │ ・設定ファイル   │    │          │  │  実行結果        │    │
│  └─────────────────┘    │          │  └─────────────────┘    │
└─────────────────────────┘          └─────────────────────────┘

実行フロー

  1. コントロールノードでAnsibleコマンドを実行
  2. インベントリから対象ホストを特定
  3. プレイブックの内容を読み込み
  4. SSH経由で管理対象ノードに接続
  5. モジュール(小さなPythonプログラム)を送信・実行
  6. 実行結果をコントロールノードに返却

主要コンポーネントの詳細解説

1. インベントリ(Inventory)

インベントリは「どのサーバーを管理するか」を定義するファイルです。

基本的なINI形式の例

# inventory/hosts
[webservers]
web1.example.com
web2.example.com
web3.example.com

[databases]
db1.example.com
db2.example.com

[webservers:vars]
http_port=80
max_clients=200

[databases:vars]
mysql_port=3306

YAML形式の例

# inventory/hosts.yml
all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
        web3.example.com:
      vars:
        http_port: 80
        max_clients: 200
    databases:
      hosts:
        db1.example.com:
        db2.example.com:
      vars:
        mysql_port: 3306

動的インベントリ

クラウド環境では、動的インベントリスクリプトを使用してリアルタイムでホスト情報を取得できます。

# AWS EC2の例
ansible-playbook -i aws_ec2.yml playbook.yml

2. プレイブック(Playbook)

プレイブックは「何をするか」を定義するYAMLファイルです。

プレイブックの基本構造

---
- name: WebサーバーのセットアップPLAY
  hosts: webservers    # 対象ホストグループ
  become: true         # sudo権限で実行
  vars:               # 変数定義
    package_name: nginx
  
  tasks:              # 実行するタスク一覧
    - name: パッケージキャッシュの更新
      apt:
        update_cache: yes
    
    - name: Nginxのインストール
      apt:
        name: "{{ package_name }}"
        state: present
    
    - name: Nginxサービスの開始
      systemd:
        name: nginx
        state: started
        enabled: yes
      notify: restart nginx  # ハンドラーを呼び出し
  
  handlers:           # 変更があった場合のみ実行
    - name: restart nginx
      systemd:
        name: nginx
        state: restarted

プレイブックの主要要素

要素 説明
name タスクの説明 - name: Nginxのインストール
hosts 対象ホスト hosts: webservers
become 権限昇格 become: true
vars 変数定義 package_name: nginx
tasks 実行タスク - name: ...
handlers 条件付き実行 notify: restart nginx

3. モジュール(Module)

モジュールは実際の作業を行う部品です。Ansibleには数千のモジュールが用意されています。

よく使われるモジュール

# ファイル・ディレクトリ操作
- name: ディレクトリ作成
  file:
    path: /var/www/html
    state: directory
    owner: www-data
    group: www-data
    mode: '0755'

# ファイルコピー
- name: 設定ファイルのコピー
  copy:
    src: nginx.conf
    dest: /etc/nginx/nginx.conf
    backup: yes
  notify: restart nginx

# テンプレートファイル
- name: テンプレートから設定ファイル生成
  template:
    src: site.conf.j2
    dest: /etc/nginx/sites-available/{{ site_name }}

# パッケージ管理
- name: パッケージインストール
  package:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - mysql-server
    - php-fpm

# サービス管理
- name: サービス開始・自動起動設定
  systemd:
    name: nginx
    state: started
    enabled: yes

# コマンド実行
- name: カスタムコマンド実行
  command: /usr/local/bin/custom-setup.sh
  args:
    creates: /var/log/setup.completed

4. タスク(Task)

タスクはプレイブック内の個別の作業単位です。

タスクの詳細例

- name: MySQLの設定
  mysql_user:
    name: webapp
    password: "{{ db_password }}"
    priv: "webapp.*:ALL"
    state: present
  when: ansible_os_family == "Debian"  # 条件分岐
  tags:
    - database
    - security
  register: mysql_result  # 結果を変数に保存
  
- name: 設定結果の表示
  debug:
    msg: "MySQL user creation result: {{ mysql_result }}"

5. ハンドラー(Handler)

ハンドラーは変更があった場合にのみ実行される特別なタスクです。

tasks:
  - name: Apache設定ファイル更新
    template:
      src: httpd.conf.j2
      dest: /etc/httpd/conf/httpd.conf
    notify:
      - restart apache
      - reload firewall

handlers:
  - name: restart apache
    systemd:
      name: httpd
      state: restarted
  
  - name: reload firewall
    command: firewall-cmd --reload

6. 変数(Variables)

Ansibleでは様々な方法で変数を定義・使用できます。

変数の優先順位(高い順)

  1. コマンドライン(-eオプション)
  2. プレイブック内のvars
  3. インベントリ変数
  4. ホスト変数
  5. グループ変数
# プレイブック内での変数使用例
---
- name: 変数の使用例
  hosts: webservers
  vars:
    app_name: mywebapp
    app_version: 1.2.3
    app_port: 8080
  
  tasks:
    - name: アプリケーションディレクトリ作成
      file:
        path: "/opt/{{ app_name }}"
        state: directory
    
    - name: 設定ファイル配置
      template:
        src: app.conf.j2
        dest: "/opt/{{ app_name }}/config.conf"
      vars:
        app_debug: false  # タスクレベル変数

ファクト変数

Ansibleは自動的にシステム情報を収集します(ファクト変数)。

- name: システム情報の表示
  debug:
    msg: |
      OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
      CPU: {{ ansible_processor_cores }}コア
      Memory: {{ ansible_memtotal_mb }}MB
      IP: {{ ansible_default_ipv4.address }}

実践編:簡単なプレイブックを作ってみよう

プロジェクト構成

ansible-project/
├── ansible.cfg          # Ansible設定ファイル
├── inventory/
│   └── hosts           # インベントリファイル
├── playbooks/
│   └── webserver.yml   # プレイブック
├── templates/
│   └── index.html.j2   # テンプレートファイル
└── vars/
    └── main.yml        # 変数ファイル

1. 設定ファイル(ansible.cfg)

[defaults]
inventory = inventory/hosts
host_key_checking = False
deprecation_warnings = False
gathering = smart
fact_caching = memory

[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
pipelining = True

2. インベントリファイル(inventory/hosts)

[webservers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11

[webservers:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa

3. 変数ファイル(vars/main.yml)

---
app_name: mywebsite
app_port: 80
document_root: /var/www/html
website_title: "Ansibleで構築したWebサイト"

4. テンプレートファイル(templates/index.html.j2)

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ website_title }}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .info { background: #f0f0f0; padding: 20px; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>{{ website_title }}</h1>
    <div class="info">
        <h2>サーバー情報</h2>
        <ul>
            <li>ホスト名: {{ ansible_hostname }}</li>
            <li>OS: {{ ansible_distribution }} {{ ansible_distribution_version }}</li>
            <li>IPアドレス: {{ ansible_default_ipv4.address }}</li>
            <li>構築日時: {{ ansible_date_time.iso8601 }}</li>
        </ul>
    </div>
    <p>このページは{{ app_name }}によって自動生成されました。</p>
</body>
</html>

5. プレイブック(playbooks/webserver.yml)

---
- name: Webサーバーの自動構築
  hosts: webservers
  become: true
  vars_files:
    - ../vars/main.yml
  
  pre_tasks:
    - name: システム情報の収集
      setup:
      tags: always
  
  tasks:
    - name: パッケージキャッシュの更新
      apt:
        update_cache: yes
        cache_valid_time: 3600
      tags: packages
    
    - name: 必要パッケージのインストール
      apt:
        name:
          - nginx
          - ufw
        state: present
      tags: packages
    
    - name: Webディレクトリの作成
      file:
        path: "{{ document_root }}"
        state: directory
        owner: www-data
        group: www-data
        mode: '0755'
      tags: setup
    
    - name: HTMLファイルの配置
      template:
        src: index.html.j2
        dest: "{{ document_root }}/index.html"
        owner: www-data
        group: www-data
        mode: '0644'
      notify: restart nginx
      tags: content
    
    - name: Nginxの開始と自動起動設定
      systemd:
        name: nginx
        state: started
        enabled: yes
      tags: services
    
    - name: ファイアウォール設定(HTTP許可)
      ufw:
        rule: allow
        port: "{{ app_port }}"
        proto: tcp
      tags: security
    
    - name: Webサーバーの動作確認
      uri:
        url: "http://{{ ansible_default_ipv4.address }}"
        method: GET
        status_code: 200
      delegate_to: localhost
      tags: verify
  
  handlers:
    - name: restart nginx
      systemd:
        name: nginx
        state: restarted
  
  post_tasks:
    - name: 構築完了メッセージ
      debug:
        msg: |
          Webサーバー構築完了!
          アクセスURL: http://{{ ansible_default_ipv4.address }}
      tags: always

6. 実行方法

# 接続テスト
ansible webservers -m ping

# プレイブック実行(全て)
ansible-playbook playbooks/webserver.yml

# 特定のタグのみ実行
ansible-playbook playbooks/webserver.yml --tags "packages,setup"

# ドライラン(実際には実行しない)
ansible-playbook playbooks/webserver.yml --check

# 詳細出力
ansible-playbook playbooks/webserver.yml -v

よく使われるモジュール

システム管理

モジュール 用途
package パッケージ管理 name: nginx, state: present
systemd サービス管理 name: nginx, state: started
user ユーザー管理 name: webapp, shell: /bin/bash
group グループ管理 name: developers, state: present
cron cron設定 name: backup, minute: 0, hour: 2

ファイル操作

モジュール 用途
copy ファイルコピー src: file.txt, dest: /tmp/
template テンプレート展開 src: config.j2, dest: /etc/app/
file ファイル・ディレクトリ操作 path: /tmp/dir, state: directory
lineinfile 行レベル編集 path: /etc/hosts, line: '192.168.1.1 server'
replace 文字列置換 path: /etc/config, regexp: 'old', replace: 'new'

ネットワーク・セキュリティ

モジュール 用途
uri HTTP/HTTPS要求 url: http://example.com, method: GET
get_url ファイルダウンロード url: http://..., dest: /tmp/
firewalld ファイアウォール(RHEL系) service: http, permanent: yes
ufw ファイアウォール(Ubuntu) rule: allow, port: 80

ベストプラクティス

1. ディレクトリ構成

ansible-project/
├── ansible.cfg
├── inventory/
│   ├── production/
│   │   ├── hosts
│   │   └── group_vars/
│   └── staging/
│       ├── hosts
│       └── group_vars/
├── playbooks/
├── roles/
│   └── webserver/
│       ├── tasks/main.yml
│       ├── handlers/main.yml
│       ├── templates/
│       ├── files/
│       └── vars/main.yml
├── group_vars/
└── host_vars/

2. 変数の命名規則

# 良い例
web_server_port: 80
database_max_connections: 100
app_environment: production

# 避けるべき例
port: 80          # 何のポートか不明
max: 100          # 何の最大値か不明
env: prod         # 省略しすぎ

3. タスクの書き方

# 良い例
- name: Nginxの設定ファイルを更新
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: '0644'
    backup: yes
  notify: restart nginx
  tags: 
    - configuration
    - nginx

# 避けるべき例
- template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx

4. セキュリティのベストプラクティス

# パスワードはvaultで暗号化
- name: データベースユーザー作成
  mysql_user:
    name: webapp
    password: "{{ vault_db_password }}"  # ansible-vault暗号化
    priv: "webapp.*:ALL"

# 機密ファイルの権限制限
- name: SSL証明書の配置
  copy:
    src: server.key
    dest: /etc/ssl/private/server.key
    owner: root
    group: root
    mode: '0600'  # rootのみ読み取り可能

5. Ansible Vault の使用

# 暗号化ファイル作成
ansible-vault create secrets.yml

# 既存ファイルの暗号化
ansible-vault encrypt vars/database.yml

# 暗号化ファイルの編集
ansible-vault edit secrets.yml

# 暗号化ファイルを使用してプレイブック実行
ansible-playbook playbook.yml --ask-vault-pass

6. ロール(Role)の活用

# playbook.yml
---
- name: Webサーバー構築
  hosts: webservers
  roles:
    - common      # 共通設定
    - security    # セキュリティ設定
    - webserver   # Webサーバー設定
    - monitoring  # 監視設定

まとめ

Ansibleは学習コストが比較的低く、強力な自動化機能を提供するツールです。

学習のステップ

  1. 基本概念の理解: インベントリ、プレイブック、モジュール
  2. 簡単なタスクから始める: ファイルコピー、パッケージインストール
  3. テンプレートと変数の活用: 動的な設定ファイル生成
  4. ロールの作成: 再利用可能な構成要素
  5. 本格運用: CI/CD統合、大規模環境での活用

次のステップ

  • Ansible Tower/AWX: Web UIでのプレイブック管理
  • Ansible Collections: 特定用途に特化したモジュール集
  • CI/CDとの統合: GitLab CI、Jenkins等との連携
  • テスト自動化: Molecule、testinfraを使用したインフラテスト

参考文献

公式ドキュメント

  1. Ansible Documentation - Ansible公式ドキュメント
  2. Ansible Galaxy - 公式ロール・コレクション集
  3. Red Hat Ansible Automation - Red Hat公式サイト

学習リソース

  1. Learning Ansible basics - Red Hat
  2. Ansible の使い方 - Zenn
  3. はじめてAnsibleを使う人が知っておきたい7つのモジュール|インフィニットループ

この記事が、Ansibleを始める皆さんの参考になれば幸いです。
質問やフィードバックがあれば、コメント欄でお気軽にお声かけください!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?