T-CREATOR

Ansible Inventory 初期構築:静的/動的の基本とベストプラクティス

Ansible Inventory 初期構築:静的/動的の基本とベストプラクティス

Ansible を活用してインフラストラクチャを自動化する際、最初に設定するのが Inventory です。Inventory はターゲットとなるサーバーやホストを定義するファイルで、Ansible がどのホストに対して処理を実行するかを決定します。

この記事では、Ansible Inventory の基本から、静的 Inventory と動的 Inventory の違い、そして実務で活用できるベストプラクティスまでを詳しく解説していきます。初めて Ansible を触る方でも、Inventory の設計から運用まで一貫して理解できる内容になっています。

背景

Ansible Inventory とは何か

Ansible Inventory は、構成管理の対象となるホスト(サーバー、ネットワーク機器、クラウドインスタンスなど)を一覧化したファイルです。Ansible は Playbook を実行する際、この Inventory を参照してどのホストに対して処理を行うかを決定します。

Inventory には以下のような情報を定義できます。

  • ホスト名や IP アドレス
  • グループ化されたホスト群
  • ホスト固有の変数(ポート番号、認証情報など)
  • グループ固有の変数

以下の図は、Ansible が Inventory を参照して複数のホストに対して処理を実行する基本的なフローを示しています。

mermaidflowchart LR
  user["運用者"] -->|ansible-playbook 実行| ansible["Ansible<br/>コントロールノード"]
  ansible -->|Inventory 参照| inv["Inventory<br/>ファイル"]
  inv -->|ホスト情報| ansible
  ansible -->|SSH 接続| web1["Web サーバー 1"]
  ansible -->|SSH 接続| web2["Web サーバー 2"]
  ansible -->|SSH 接続| db1["DB サーバー"]

図の要点

  • Ansible は Inventory ファイルを参照してターゲットホストを特定します
  • SSH 経由で各ホストに接続し、Playbook で定義されたタスクを実行します
  • Inventory の管理方法が運用の効率性を左右します

静的 Inventory と動的 Inventory の必要性

従来、Inventory は静的ファイル(INI 形式や YAML 形式)として管理されていました。しかし、クラウド環境やコンテナ環境の普及により、ホストの数や構成が動的に変化するようになりました。

この変化に対応するため、Ansible は動的 Inventory という仕組みを提供しています。動的 Inventory は、外部システム(AWS、Azure、GCP、VMware など)から自動的にホスト情報を取得し、リアルタイムで Inventory を生成します。

#項目静的 Inventory動的 Inventory
1ファイル形式INI、YAMLスクリプト、プラグイン
2更新方法手動編集自動取得
3適用環境固定インフラクラウド、コンテナ
4メンテナンス負荷高い低い
5柔軟性低い高い

課題

静的 Inventory の運用課題

静的 Inventory を使用する場合、以下のような運用課題が発生します。

手動メンテナンスの負担

ホストの追加や削除のたびに Inventory ファイルを手動で編集する必要があります。インフラの規模が大きくなるほど、この作業負荷は増大していきます。

情報の不整合リスク

実際のインフラ構成と Inventory ファイルの内容が乖離するリスクがあります。特に複数の担当者が Inventory を管理している場合、更新漏れや誤った情報が記載される可能性が高まります。

スケーラビリティの限界

クラウド環境でオートスケーリングを活用している場合、インスタンスが動的に増減するため、静的 Inventory では対応できません。

以下の図は、静的 Inventory における課題の流れを示しています。

mermaidflowchart TD
  start["インフラ構成変更"] -->|手動| edit["Inventory ファイル編集"]
  edit -->|更新漏れ| mismatch["実環境と<br/>Inventory の不一致"]
  edit -->|誤記入| error["Playbook 実行<br/>エラー"]
  mismatch -->|影響| fail["意図しないホストへの<br/>適用漏れ"]
  error -->|デバッグ| rework["修正作業"]
  rework -->|再実行| edit

図で理解できる要点

  • 手動編集がエラーや不整合の原因となります
  • 更新漏れや誤記入がトラブルの起点になります
  • デバッグと修正の繰り返しで運用負荷が増大します

動的 Inventory の導入障壁

一方、動的 Inventory を導入する際にも以下の課題があります。

初期設定の複雑さ

動的 Inventory を利用するには、外部システムとの連携設定やプラグインのインストールが必要です。クラウドプロバイダーごとに設定方法が異なるため、学習コストが発生します。

認証情報の管理

AWS や Azure などのクラウド環境にアクセスするため、API キーやアクセストークンなどの認証情報を安全に管理する必要があります。

パフォーマンスの考慮

動的 Inventory は実行時に外部 API を呼び出すため、ネットワーク遅延や API のレート制限によってパフォーマンスが低下する可能性があります。

解決策

静的 Inventory の基本構成

まずは静的 Inventory の基本的な構成方法を理解しましょう。静的 Inventory は小規模な環境や、ホスト構成が頻繁に変わらない環境で有効です。

INI 形式の Inventory

INI 形式は最もシンプルで、テキストエディタで直接編集できるため、初心者にも扱いやすい形式です。

以下は、基本的な INI 形式の Inventory ファイルの例です。

ini# Web サーバーのグループ定義
[webservers]
web1.example.com
web2.example.com
web3.example.com

# DB サーバーのグループ定義
[dbservers]
db1.example.com ansible_host=192.168.1.10
db2.example.com ansible_host=192.168.1.11

ポイント

  • [グループ名] でホストをグループ化します
  • ansible_host でホスト名と異なる IP アドレスを指定できます

グループ内で共通の変数を定義する場合は、:vars セクションを使用します。

ini[webservers:vars]
ansible_user=deploy
ansible_port=22
http_port=80

ポイント

  • [グループ名:vars] でグループ全体に適用される変数を定義します
  • SSH 接続情報やアプリケーション固有の設定値を記載できます

親グループを定義して、複数のグループをまとめることもできます。

ini# 親グループの定義
[production:children]
webservers
dbservers

# 親グループに対する変数
[production:vars]
env=production
backup_enabled=true

ポイント

  • :children で子グループを含む親グループを作成できます
  • 環境ごと(production、staging など)にグループを整理すると管理しやすくなります

YAML 形式の Inventory

YAML 形式は INI 形式よりも構造的で、ネストした変数や複雑なデータ構造を表現しやすいという特徴があります。

以下は、YAML 形式での同等の Inventory 定義です。

yaml# グループとホストの定義
all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
        web3.example.com:
      vars:
        ansible_user: deploy
        ansible_port: 22
        http_port: 80

ポイント

  • all は全ホストを含むルートグループです
  • children でサブグループを定義します
  • hosts でグループ内のホストを列挙します
  • vars でグループ変数を定義します

個別ホストに固有の変数を定義する場合は、以下のように記述します。

yamldbservers:
  hosts:
    db1.example.com:
      ansible_host: 192.168.1.10
      mysql_port: 3306
      backup_schedule: '0 2 * * *'
    db2.example.com:
      ansible_host: 192.168.1.11
      mysql_port: 3306
      backup_schedule: '0 3 * * *'
  vars:
    ansible_user: dbadmin
    env: production

ポイント

  • ホスト名の下にインデントして、ホスト固有の変数を定義します
  • バックアップスケジュールなど、ホストごとに異なる設定値を記載できます

親グループの定義も YAML で表現できます。

yamlall:
  children:
    production:
      children:
        webservers:
        dbservers:
      vars:
        env: production
        backup_enabled: true

ポイント

  • children の中に他のグループ名を列挙することで、親子関係を構築します
  • 階層構造が視覚的にわかりやすくなります

動的 Inventory の構築方法

動的 Inventory は、外部システムから自動的にホスト情報を取得する仕組みです。ここでは AWS を例に、動的 Inventory の構築方法を解説します。

AWS 動的 Inventory の設定

Ansible は AWS EC2 インスタンスの情報を自動的に取得できる aws_ec2 プラグインを提供しています。

まず、必要な Python パッケージをインストールします。

bash# boto3 と botocore のインストール
yarn global add boto3 botocore

ポイント

  • boto3 は AWS SDK for Python です
  • botocore は boto3 の低レベル API ライブラリです

次に、動的 Inventory の設定ファイル(YAML 形式)を作成します。ファイル名は aws_ec2.yml とし、拡張子 .yml が重要です。

yaml# aws_ec2.yml
# プラグインの指定(必須)
plugin: aws_ec2

# AWS リージョンの指定
regions:
  - ap-northeast-1
  - us-east-1

ポイント

  • plugin: aws_ec2 で AWS EC2 動的 Inventory プラグインを指定します
  • regions で取得対象のリージョンを指定します

インスタンスにタグでフィルタをかけて、特定のインスタンスのみを取得することができます。

yaml# フィルタの設定
filters:
  # 実行中のインスタンスのみ取得
  instance-state-name: running
  # 特定のタグを持つインスタンスのみ取得
  'tag:Environment': production

ポイント

  • filters で AWS API のフィルタ条件を指定します
  • タグを活用することで、環境や用途ごとにインスタンスを分類できます

取得したインスタンスを、タグに基づいて自動的にグループ化できます。

yaml# グループ化の設定
keyed_groups:
  # Environment タグでグループ化
  - key: tags.Environment
    prefix: env
  # Name タグでグループ化
  - key: tags.Name
    prefix: name
  # インスタンスタイプでグループ化
  - key: instance_type
    prefix: type

ポイント

  • keyed_groups で EC2 タグやインスタンス属性に基づいてグループを自動生成します
  • prefix でグループ名のプレフィックスを指定できます
  • 例: Environment=production タグを持つインスタンスは env_production グループに所属します

ホスト名として使用する値を設定できます。

yaml# ホスト名の設定
hostnames:
  # プライベート DNS 名を使用
  - private-dns-name
  # タグの Name 値を使用(存在する場合)
  - tag:Name

ポイント

  • hostnames でホスト名として使用する属性を優先順位付きで指定します
  • 最初に見つかった値がホスト名として採用されます

AWS 認証情報の設定は、環境変数または AWS CLI の設定ファイルを使用します。

bash# 環境変数で設定する場合
export AWS_ACCESS_KEY_ID="your-access-key-id"
export AWS_SECRET_ACCESS_KEY="your-secret-access-key"
export AWS_DEFAULT_REGION="ap-northeast-1"

ポイント

  • AWS の認証情報は環境変数で設定するのが一般的です
  • セキュリティ上、認証情報をコードに直接記載してはいけません

動的 Inventory が正しく設定されているか確認するには、以下のコマンドを使用します。

bash# 動的 Inventory の内容を確認
ansible-inventory -i aws_ec2.yml --list

ポイント

  • --list オプションで取得されたすべてのホストと変数を JSON 形式で出力します
  • グループ化が正しく行われているか確認できます

特定のホストの詳細情報を確認することもできます。

bash# 特定ホストの情報を確認
ansible-inventory -i aws_ec2.yml --host <ホスト名>

ポイント

  • 個別ホストに割り当てられた変数を確認できます
  • トラブルシューティングに有効です

以下の図は、AWS 動的 Inventory の動作フローを示しています。

mermaidflowchart TD
  start["ansible-playbook 実行"] -->|読み込み| config["aws_ec2.yml<br/>設定ファイル"]
  config -->|API 呼び出し| aws["AWS EC2 API"]
  aws -->|インスタンス情報| plugin["aws_ec2<br/>プラグイン"]
  plugin -->|フィルタ適用| filter["条件に合う<br/>インスタンス抽出"]
  filter -->|グループ化| group["タグベースの<br/>グループ生成"]
  group -->|Inventory 生成| inv["動的 Inventory"]
  inv -->|ホスト情報| ansible["Ansible<br/>Playbook 実行"]

図で理解できる要点

  • 実行時に AWS API からリアルタイムでインスタンス情報を取得します
  • タグやフィルタに基づいて自動的にグループ化されます
  • 常に最新のインフラ構成が反映されます

その他のクラウドプロバイダー

Ansible は AWS 以外にも、Azure、GCP、VMware など、さまざまなプラットフォーム向けの動的 Inventory プラグインを提供しています。

#プロバイダープラグイン名必要なパッケージ
1AWS EC2aws_ec2boto3, botocore
2Azureazure_rmazure-cli-core, azure-mgmt-compute
3Google Cloudgcp_computerequests, google-auth
4VMwarevmware_vm_inventorypyvmomi
5OpenStackopenstackopenstacksdk

Azure の動的 Inventory の基本設定例です。

yaml# azure_rm.yml
# Azure 動的 Inventory プラグインの指定
plugin: azure_rm

# 認証情報(環境変数または Azure CLI から取得)
auth_source: auto

# サブスクリプション ID の指定
include_vm_resource_groups:
  - production-rg
  - staging-rg

ポイント

  • plugin: azure_rm で Azure 動的 Inventory を有効にします
  • auth_source: auto で Azure CLI の認証情報を自動的に使用します

GCP の動的 Inventory の基本設定例です。

yaml# gcp_compute.yml
# GCP 動的 Inventory プラグインの指定
plugin: gcp_compute

# プロジェクト ID の指定
projects:
  - my-gcp-project-id

# サービスアカウントキーのパス
service_account_file: /path/to/service-account-key.json

ポイント

  • plugin: gcp_compute で GCP Compute Engine の動的 Inventory を有効にします
  • サービスアカウントキーで認証を行います

ベストプラクティス

ディレクトリ構造の整理

Inventory ファイルを適切に整理することで、運用性が大幅に向上します。推奨されるディレクトリ構造は以下の通りです。

plaintext# プロジェクトのディレクトリ構造
inventory/
├── production/
│   ├── hosts.yml          # 本番環境の静的 Inventory
│   ├── group_vars/        # グループ変数
│   │   ├── all.yml        # 全ホスト共通の変数
│   │   ├── webservers.yml # Web サーバーグループの変数
│   │   └── dbservers.yml  # DB サーバーグループの変数
│   └── host_vars/         # ホスト固有の変数
│       ├── web1.yml
│       └── db1.yml
├── staging/
│   ├── hosts.yml          # ステージング環境の静的 Inventory
│   └── group_vars/
│       └── all.yml
└── aws/
    └── aws_ec2.yml        # AWS 動的 Inventory 設定

ポイント

  • 環境ごと(production、staging など)にディレクトリを分けます
  • group_vars でグループ変数、host_vars でホスト変数を管理します
  • ファイル名はグループ名またはホスト名と一致させます

group_vars​/​all.yml には、すべてのホストに共通する変数を定義します。

yaml# inventory/production/group_vars/all.yml
---
# 共通の SSH 設定
ansible_user: deploy
ansible_port: 22
ansible_ssh_private_key_file: ~/.ssh/id_rsa

# 共通の環境変数
environment_name: production
log_level: info

ポイント

  • all グループはすべてのホストが所属する特別なグループです
  • SSH 接続情報や環境識別子など、全体に共通する設定を記載します

group_vars​/​webservers.yml には、Web サーバーグループ固有の変数を定義します。

yaml# inventory/production/group_vars/webservers.yml
---
# Web サーバー固有の設定
http_port: 80
https_port: 443
document_root: /var/www/html
max_connections: 1000

ポイント

  • グループ固有の設定値を分離することで、可読性が向上します
  • 変数の上書きルールにより、group_varsall.yml より優先されます

host_vars​/​web1.yml には、特定ホスト固有の変数を定義します。

yaml# inventory/production/host_vars/web1.yml
---
# web1 固有の設定
server_id: 1
backup_priority: high
local_ip: 192.168.1.100

ポイント

  • ホスト変数は最も優先度が高く、グループ変数を上書きします
  • サーバー固有の ID や IP アドレスなどを記載します

変数の優先順位の理解

Ansible では、変数は複数の場所で定義でき、優先順位のルールがあります。優先順位を理解することで、意図しない変数の上書きを防げます。

変数の優先順位(低い順から高い順)は以下の通りです。

#定義場所優先度用途
1group_vars/all最低全体のデフォルト値
2group_vars/グループ名グループ固有の設定
3host_vars/ホスト名ホスト固有の設定
4Playbook の varsPlaybook 固有の変数
5タスクの varsタスク固有の変数
6コマンドラインの -e最高実行時の一時的な上書き

変数の上書き例を見てみましょう。

yaml# group_vars/all.yml
http_port: 80

# group_vars/webservers.yml
http_port: 8080

# host_vars/web1.yml
http_port: 9090

結果

  • web1http_port9090 になります(host_vars が最優先)
  • その他の webservers グループのホストは 8080 になります
  • webservers 以外のホストは 80 になります

機密情報の管理

Inventory にはパスワードや API キーなどの機密情報が含まれる場合があります。これらを安全に管理するため、Ansible Vault を使用しましょう。

機密情報を含む変数ファイルを暗号化します。

bash# group_vars ファイルを暗号化
ansible-vault encrypt inventory/production/group_vars/dbservers.yml

ポイント

  • ansible-vault encrypt でファイルを AES256 で暗号化します
  • パスワードプロンプトが表示されるので、強固なパスワードを設定します

暗号化されたファイルを編集する場合は、以下のコマンドを使用します。

bash# 暗号化されたファイルを編集
ansible-vault edit inventory/production/group_vars/dbservers.yml

ポイント

  • パスワードを入力すると、一時的に復号化されたファイルがエディタで開きます
  • 編集後、自動的に再暗号化されます

Playbook 実行時に Vault パスワードを指定します。

bash# Vault パスワードを対話的に入力
ansible-playbook -i inventory/production/hosts.yml site.yml --ask-vault-pass

ポイント

  • --ask-vault-pass で実行時にパスワードを入力します
  • CI/CD 環境では --vault-password-file でパスワードファイルを指定できます

パスワードファイルを使用する場合の例です。

bash# パスワードファイルを使用
echo 'your-vault-password' > .vault_pass
chmod 600 .vault_pass

# パスワードファイルを指定して実行
ansible-playbook -i inventory/production/hosts.yml site.yml --vault-password-file .vault_pass

ポイント

  • パスワードファイルは必ず .gitignore に追加し、バージョン管理から除外します
  • ファイルのパーミッションを 600 に設定し、所有者のみが読み取れるようにします

動的 Inventory のキャッシュ活用

動的 Inventory は実行のたびに外部 API を呼び出すため、パフォーマンスが低下する場合があります。キャッシュを活用することで、この問題を解決できます。

キャッシュを有効にした AWS 動的 Inventory の設定例です。

yaml# aws_ec2.yml にキャッシュ設定を追加
plugin: aws_ec2

# キャッシュの有効化
cache: true
cache_plugin: jsonfile
cache_timeout: 3600
cache_connection: /tmp/ansible_inventory_cache

ポイント

  • cache: true でキャッシュを有効化します
  • cache_timeout: 3600 でキャッシュの有効期限を秒単位で指定します(1 時間)
  • cache_connection でキャッシュファイルの保存先を指定します

キャッシュを使用することで、以下のようなメリットがあります。

  • API 呼び出し回数が減少し、実行速度が向上します
  • API のレート制限に達するリスクが低減します
  • ネットワーク障害時でもキャッシュから情報を取得できます

ただし、キャッシュには以下の注意点もあります。

  • インフラの変更が即座に反映されない可能性があります
  • 定期的にキャッシュをクリアする運用が必要です

キャッシュをクリアする方法です。

bash# キャッシュファイルを削除
rm -rf /tmp/ansible_inventory_cache/*

# または、キャッシュタイムアウトを 0 に設定して実行
ansible-inventory -i aws_ec2.yml --list --cache-timeout 0

ポイント

  • 重要な変更を反映させたい場合は、手動でキャッシュをクリアします
  • --cache-timeout 0 で一時的にキャッシュを無効化できます

静的と動的の併用

実務では、静的 Inventory と動的 Inventory を併用するケースが多くあります。例えば、クラウド環境のホストは動的に取得し、オンプレミスのホストは静的に定義するといった使い分けです。

複数の Inventory ソースを使用する場合、ディレクトリにまとめます。

plaintext# 複数の Inventory を含むディレクトリ
inventory/
├── 01_static_hosts.yml   # 静的 Inventory
├── 02_aws_ec2.yml        # AWS 動的 Inventory
└── 03_azure_rm.yml       # Azure 動的 Inventory

ポイント

  • Inventory ディレクトリ内のすべてのファイルが読み込まれます
  • ファイル名の数字プレフィックスで読み込み順序を制御できます
  • 静的と動的の Inventory が統合されて使用されます

Playbook 実行時は、ディレクトリを指定します。

bash# ディレクトリを指定して実行
ansible-playbook -i inventory/ site.yml

ポイント

  • -i inventory​/​ でディレクトリ内のすべての Inventory ファイルが読み込まれます
  • 静的ホストと動的ホストが統合されたビューで操作できます

統合された Inventory の内容を確認する方法です。

bash# 統合された Inventory の確認
ansible-inventory -i inventory/ --list

ポイント

  • すべてのソースから取得されたホストとグループが表示されます
  • グループの重複がある場合は自動的にマージされます

具体例

実践例 1:小規模 Web アプリケーションの Inventory 構築

3 台の Web サーバーと 1 台の DB サーバーで構成される小規模 Web アプリケーションの Inventory を構築してみます。

まず、INI 形式で基本的な Inventory を作成します。

ini# inventory/production/hosts.ini
# Web サーバーグループ
[webservers]
web1.example.com
web2.example.com
web3.example.com

# DB サーバーグループ
[dbservers]
db1.example.com

# ロードバランサー
[loadbalancers]
lb1.example.com

# 本番環境全体
[production:children]
webservers
dbservers
loadbalancers

ポイント

  • 役割ごとにグループを分けることで、Playbook での指定が簡単になります
  • production という親グループで環境全体を管理します

グループ変数で共通設定を定義します。

yaml# inventory/production/group_vars/all.yml
---
# 全ホスト共通の SSH 設定
ansible_user: ubuntu
ansible_port: 22
ansible_ssh_private_key_file: ~/.ssh/production_key

# 環境識別子
env: production
domain: example.com

ポイント

  • SSH 接続に必要な情報を一元管理します
  • 環境変数は Playbook やテンプレートで参照できます

Web サーバーグループの変数を定義します。

yaml# inventory/production/group_vars/webservers.yml
---
# アプリケーション設定
app_port: 8080
app_workers: 4
app_max_memory: 512M

# Nginx 設定
nginx_port: 80
nginx_worker_processes: auto

ポイント

  • アプリケーションサーバーと Web サーバーの設定を分けて管理します
  • Playbook でこれらの変数を参照してテンプレートを生成します

DB サーバーグループの変数(機密情報含む)を定義します。

yaml# inventory/production/group_vars/dbservers.yml
---
# MySQL 設定
mysql_port: 3306
mysql_max_connections: 200

# データベース認証情報(暗号化推奨)
mysql_root_password: 'SecurePassword123!'
mysql_app_user: webapp
mysql_app_password: 'AppPassword456!'
mysql_database: production_db

ポイント

  • データベースの認証情報は Ansible Vault で暗号化すべきです
  • 実務では ansible-vault encrypt コマンドで暗号化します

このファイルを暗号化します。

bash# 機密情報を含むファイルを暗号化
ansible-vault encrypt inventory/production/group_vars/dbservers.yml

実行結果

sqlNew Vault password:
Confirm New Vault password:
Encryption successful

ホスト固有の変数も定義できます。

yaml# inventory/production/host_vars/web1.yml
---
# サーバー固有の設定
server_id: 1
local_ip: 10.0.1.10
yaml# inventory/production/host_vars/web2.yml
---
server_id: 2
local_ip: 10.0.1.11
yaml# inventory/production/host_vars/web3.yml
---
server_id: 3
local_ip: 10.0.1.12

ポイント

  • 各サーバーに一意の ID や IP アドレスを割り当てます
  • ログファイルやモニタリングでサーバーを識別するのに使用します

Inventory の確認を行います。

bash# すべてのホストを確認
ansible-inventory -i inventory/production --list

# 特定のグループのホストを確認
ansible all -i inventory/production --list-hosts

# 特定のホストの変数を確認
ansible-inventory -i inventory/production --host web1.example.com

ポイント

  • Inventory が正しく構成されているか、Playbook 実行前に確認します
  • 変数の優先順位が意図通りか検証します

以下の図は、この小規模 Web アプリケーションの構成と Inventory の関係を示しています。

mermaidflowchart TB
  subgraph inv["Inventory 構造"]
    all["all (全ホスト)"]
    prod["production<br/>(親グループ)"]
    web["webservers"]
    db["dbservers"]
    lb["loadbalancers"]

    all --> prod
    prod --> web
    prod --> db
    prod --> lb
  end

  subgraph hosts["実際のホスト"]
    web1["web1.example.com<br/>server_id: 1"]
    web2["web2.example.com<br/>server_id: 2"]
    web3["web3.example.com<br/>server_id: 3"]
    db1["db1.example.com<br/>mysql_port: 3306"]
    lb1["lb1.example.com<br/>nginx"]
  end

  web -.->|所属| web1
  web -.->|所属| web2
  web -.->|所属| web3
  db -.->|所属| db1
  lb -.->|所属| lb1

図で理解できる要点

  • グループ階層構造により、変数の継承関係が明確になります
  • 各ホストは複数のグループに所属できます
  • 親グループの変数は子グループやホストに継承されます

実践例 2:AWS 環境での動的 Inventory 活用

AWS のオートスケーリンググループで管理されている Web サーバーに対して、動的 Inventory を活用する例です。

まず、EC2 インスタンスに適切なタグを設定します。

#タグキータグ値用途
1Nameweb-server-01インスタンス識別
2Environmentproduction環境識別
3Rolewebserver役割識別
4Applicationmyappアプリケーション識別
5ManagedByansible管理ツール識別

これらのタグを活用した動的 Inventory の設定ファイルを作成します。

yaml# inventory/aws/aws_ec2.yml
# プラグインの指定
plugin: aws_ec2

# 対象リージョン
regions:
  - ap-northeast-1

ポイント

  • plugin: aws_ec2 で AWS EC2 動的 Inventory プラグインを使用します
  • 複数リージョンをリスト形式で指定できます

フィルタ条件を設定して、特定のインスタンスのみを取得します。

yaml# フィルタ設定
filters:
  # 実行中のインスタンスのみ
  instance-state-name: running
  # Ansible で管理対象のインスタンスのみ
  'tag:ManagedBy': ansible
  # 本番環境のインスタンスのみ
  'tag:Environment': production

ポイント

  • filters で不要なインスタンスを除外します
  • タグベースのフィルタリングで管理範囲を明確化します

タグに基づいてグループを自動生成します。

yaml# グループ化設定
keyed_groups:
  # Environment タグでグループ化 (例: env_production)
  - key: tags.Environment
    prefix: env
    separator: '_'

  # Role タグでグループ化 (例: role_webserver)
  - key: tags.Role
    prefix: role
    separator: '_'

  # Application タグでグループ化 (例: app_myapp)
  - key: tags.Application
    prefix: app
    separator: '_'

  # インスタンスタイプでグループ化 (例: type_t3_medium)
  - key: instance_type
    prefix: type
    separator: '_'

ポイント

  • keyed_groups で EC2 タグやインスタンス属性からグループを自動生成します
  • separator でグループ名の区切り文字を指定します
  • 複数の軸でグループ化することで、柔軟な管理が可能になります

ホスト名の設定を行います。

yaml# ホスト名設定
hostnames:
  # Name タグを優先的に使用
  - tag:Name
  # Name タグがない場合はプライベート DNS 名を使用
  - private-dns-name

ポイント

  • リストの上から順に評価され、最初に見つかった値がホスト名になります
  • 一貫性のあるホスト名規則を維持できます

必要な変数を Inventory に追加します。

yaml# 変数の追加
compose:
  # インスタンス ID を変数として追加
  instance_id: instance_id
  # プライベート IP を変数として追加
  private_ip: private_ip_address
  # パブリック IP を変数として追加(存在する場合)
  public_ip: public_ip_address | default('')
  # Environment タグを変数として追加
  env: tags.Environment

ポイント

  • compose でホスト変数を定義します
  • | default('') で値が存在しない場合のデフォルト値を設定します

キャッシュを設定してパフォーマンスを向上させます。

yaml# キャッシュ設定
cache: true
cache_plugin: jsonfile
cache_timeout: 1800 # 30分
cache_connection: /tmp/ansible_aws_inventory_cache
cache_prefix: aws_ec2

ポイント

  • 頻繁に実行する場合はキャッシュを有効化します
  • cache_timeout を環境の変更頻度に応じて調整します

動的 Inventory が正しく動作しているか確認します。

bash# 動的 Inventory の内容を JSON 形式で確認
ansible-inventory -i inventory/aws/aws_ec2.yml --list

# グラフ形式で確認(見やすい)
ansible-inventory -i inventory/aws/aws_ec2.yml --graph

実行結果例(--graph)

less@all:
  |--@aws_ec2:
  |  |--web-server-01
  |  |--web-server-02
  |  |--web-server-03
  |--@env_production:
  |  |--web-server-01
  |  |--web-server-02
  |  |--web-server-03
  |--@role_webserver:
  |  |--web-server-01
  |  |--web-server-02
  |  |--web-server-03
  |--@app_myapp:
  |  |--web-server-01
  |  |--web-server-02
  |  |--web-server-03

特定のグループのホストのみを確認します。

bash# role_webserver グループのホスト一覧
ansible role_webserver -i inventory/aws/aws_ec2.yml --list-hosts

ポイント

  • グループ名を指定して、特定の役割のホストのみを抽出できます
  • Playbook 実行前にターゲットを確認する習慣をつけましょう

実際に Playbook を実行する例です。

bash# role_webserver グループに対して Playbook を実行
ansible-playbook -i inventory/aws/aws_ec2.yml \
  --limit role_webserver \
  site.yml

ポイント

  • --limit で実行対象を絞り込めます
  • タグベースのグループ化により、動的に増減するインスタンスにも自動対応します

以下の図は、AWS 動的 Inventory の活用フローを示しています。

mermaidsequenceDiagram
  participant user as 運用者
  participant ansible as Ansible
  participant inv as aws_ec2.yml
  participant aws as AWS EC2 API
  participant cache as キャッシュ

  user->>ansible: ansible-playbook 実行
  ansible->>inv: 設定読み込み

  alt キャッシュ有効期限内
    ansible->>cache: キャッシュ確認
    cache-->>ansible: Inventory データ
  else キャッシュ期限切れ
    ansible->>aws: インスタンス情報<br/>API リクエスト
    aws-->>ansible: フィルタ条件に合う<br/>インスタンス一覧
    ansible->>ansible: タグベースで<br/>グループ生成
    ansible->>cache: キャッシュ保存
  end

  ansible->>ansible: Playbook 実行
  ansible-->>user: 実行結果

図で理解できる要点

  • キャッシュがあれば API 呼び出しをスキップし、高速化されます
  • タグに基づいて自動的にグループが生成されます
  • インスタンスの増減に自動対応できます

実践例 3:マルチクラウド環境の Inventory 統合

AWS と Azure の両方を使用している環境で、統合された Inventory を構築する例です。

ディレクトリ構造を設計します。

plaintext# マルチクラウド Inventory のディレクトリ構造
inventory/
├── 00_static/
│   ├── hosts.yml           # オンプレミスホスト
│   └── group_vars/
│       └── all.yml
├── 01_aws/
│   ├── aws_ec2.yml         # AWS 動的 Inventory
│   └── group_vars/
│       └── aws_hosts.yml
├── 02_azure/
│   ├── azure_rm.yml        # Azure 動的 Inventory
│   └── group_vars/
│       └── azure_hosts.yml
└── group_vars/
    ├── all.yml             # 全環境共通変数
    └── production.yml      # 本番環境共通変数

ポイント

  • 番号プレフィックスで読み込み順序を制御します
  • クラウドプロバイダーごとにディレクトリを分けます
  • 共通変数は最上位の group_vars に配置します

オンプレミスホストの静的 Inventory を定義します。

yaml# inventory/00_static/hosts.yml
---
all:
  children:
    onpremise:
      hosts:
        onprem-db1.internal:
          ansible_host: 192.168.10.10
        onprem-db2.internal:
          ansible_host: 192.168.10.11
      vars:
        location: datacenter-tokyo
        provider: onpremise

ポイント

  • オンプレミスホストは静的に定義します
  • provider タグで環境を識別できるようにします

AWS 動的 Inventory を設定します。

yaml# inventory/01_aws/aws_ec2.yml
plugin: aws_ec2

regions:
  - ap-northeast-1
  - us-east-1

filters:
  instance-state-name: running
  'tag:Environment': production

keyed_groups:
  - key: tags.Role
    prefix: role
  - key: tags.Environment
    prefix: env
  - key: placement.region
    prefix: aws_region

# AWS 特有の変数を追加
compose:
  provider: "'aws'"
  cloud_location: placement.region

ポイント

  • composeprovider 変数を追加し、クラウドプロバイダーを識別します
  • リージョン情報を変数として利用できるようにします

Azure 動的 Inventory を設定します。

yaml# inventory/02_azure/azure_rm.yml
plugin: azure_rm

auth_source: auto

include_vm_resource_groups:
  - production-rg

keyed_groups:
  - key: tags.Role
    prefix: role
  - key: tags.Environment
    prefix: env
  - key: location
    prefix: azure_location

# Azure 特有の変数を追加
compose:
  provider: "'azure'"
  cloud_location: location

ポイント

  • AWS と同じキーでグループ化することで、統合が容易になります
  • provider 変数で Azure を識別します

全環境共通の変数を定義します。

yaml# inventory/group_vars/all.yml
---
# SSH 接続設定
ansible_user: admin
ansible_port: 22

# タイムゾーン
timezone: Asia/Tokyo

# ログ設定
log_rotation_days: 30

ポイント

  • すべてのホスト(オンプレミス、AWS、Azure)に共通する設定を定義します
  • クラウド固有の設定はここには含めません

統合された Inventory を確認します。

bash# 全ホストを確認
ansible-inventory -i inventory/ --graph

# プロバイダーごとのホスト数を確認
ansible all -i inventory/ --list-hosts | grep -c "hosts ("

実行結果例

less@all:
  |--@aws_ec2:
  |  |--aws-web-01
  |  |--aws-web-02
  |--@azure_rm:
  |  |--azure-web-01
  |  |--azure-web-02
  |--@onpremise:
  |  |--onprem-db1.internal
  |  |--onprem-db2.internal
  |--@role_webserver:
  |  |--aws-web-01
  |  |--aws-web-02
  |  |--azure-web-01
  |  |--azure-web-02
  |--@env_production:
  |  |--aws-web-01
  |  |--aws-web-02
  |  |--azure-web-01
  |  |--azure-web-02
  |  |--onprem-db1.internal
  |  |--onprem-db2.internal

プロバイダー別に Playbook を実行する例です。

bash# AWS のホストのみに実行
ansible-playbook -i inventory/ --limit aws_ec2 playbook.yml

# Azure のホストのみに実行
ansible-playbook -i inventory/ --limit azure_rm playbook.yml

# オンプレミスのホストのみに実行
ansible-playbook -i inventory/ --limit onpremise playbook.yml

ポイント

  • --limit でプロバイダーごとに実行対象を絞り込めます
  • 統合 Inventory により、マルチクラウド環境を一元管理できます

役割ベースで実行する例です。

bash# すべてのクラウドの Web サーバーに実行
ansible-playbook -i inventory/ --limit role_webserver playbook.yml

ポイント

  • クラウドプロバイダーに関係なく、役割ベースで管理できます
  • インフラの抽象化により、クラウド移行が容易になります

以下の図は、マルチクラウド Inventory の統合構造を示しています。

mermaidflowchart TB
  subgraph inv["統合 Inventory"]
    all_inv["all グループ"]

    subgraph static["静的 Inventory"]
      onprem["onpremise"]
      op_db1["onprem-db1"]
      op_db2["onprem-db2"]
      onprem --> op_db1
      onprem --> op_db2
    end

    subgraph aws_inv["AWS 動的 Inventory"]
      aws_group["aws_ec2"]
      aws_web1["aws-web-01"]
      aws_web2["aws-web-02"]
      aws_group --> aws_web1
      aws_group --> aws_web2
    end

    subgraph azure_inv["Azure 動的 Inventory"]
      azure_group["azure_rm"]
      azure_web1["azure-web-01"]
      azure_web2["azure-web-02"]
      azure_group --> azure_web1
      azure_group --> azure_web2
    end

    all_inv --> static
    all_inv --> aws_inv
    all_inv --> azure_inv
  end

  subgraph logical["論理グループ"]
    role_web["role_webserver"]
    env_prod["env_production"]

    role_web -.->|含む| aws_web1
    role_web -.->|含む| aws_web2
    role_web -.->|含む| azure_web1
    role_web -.->|含む| azure_web2

    env_prod -.->|含む| aws_web1
    env_prod -.->|含む| aws_web2
    env_prod -.->|含む| azure_web1
    env_prod -.->|含む| azure_web2
    env_prod -.->|含む| op_db1
    env_prod -.->|含む| op_db2
  end

図で理解できる要点

  • 複数のクラウドプロバイダーとオンプレミスが統合されます
  • 論理グループにより、プロバイダーを超えた横断的な管理が可能です
  • 役割や環境でグループ化することで、運用が簡素化されます

まとめ

Ansible Inventory は、インフラ自動化の基盤となる重要な要素です。この記事では、静的 Inventory と動的 Inventory の基本から、実務で活用できるベストプラクティスまでを解説しました。

静的 Inventory の特徴

  • INI 形式や YAML 形式でシンプルに定義できます
  • 小規模環境やホスト構成が固定的な環境に適しています
  • 手動メンテナンスが必要なため、大規模環境では運用負荷が高くなります

動的 Inventory の特徴

  • クラウド環境やコンテナ環境など、動的に変化する環境に最適です
  • 外部 API から自動的にホスト情報を取得するため、常に最新の状態を反映できます
  • 初期設定は複雑ですが、長期的には運用負荷を大幅に削減できます

ベストプラクティスのポイント

  • 環境ごとにディレクトリを分け、group_varshost_vars で変数を整理しましょう
  • 機密情報は必ず Ansible Vault で暗号化し、セキュリティを確保しましょう
  • 動的 Inventory ではキャッシュを活用し、パフォーマンスを最適化しましょう
  • マルチクラウド環境では、静的と動的を併用して統合管理を実現しましょう

適切な Inventory 設計は、Ansible を活用したインフラ自動化の成功の鍵となります。環境の特性や規模に応じて、静的と動的を使い分け、効率的な運用を目指しましょう。

関連リンク