Ansibleのインストールからインベントリ構築、初めてのYAML Playbook作成、サーバー構築自動化オーケストレーションまでの実践入門ガイド。
🔗 Related: Ansible 基本チートシート · Ansible Roles チートシート · Ansible Playbook 実践例集
インストール
# macOS (Homebrew)
brew install ansible
# Ubuntu / Debian
sudo apt update && sudo apt install -y ansible
# Python Pip (Universal)
pip install ansible
参照:Ansible 公式インストール手順書: Ansible Installation Docs
プロジェクト初期設定
mkdir -p ~/ansible-setup
cd ~/ansible-setup
インベントリ、Playbook、変数を整理するための専用作業ディレクトリを作成します。
設定ファイル
インベントリファイル (Inventory)
hosts
[webservers]
192.168.0.10
192.168.0.11
[databases]
192.168.0.20
[local]
localhost ansible_connection=local
インベントリでは対象ホストを論理グループとして定義します。ansible_connection=local を指定すれば、SSHなしでローカル環境でのテスト自動化が可能です。
参照:Ansible インベントリ構築ガイド: Ansible How to build your inventory
Playbook 定義
playbook.yml
---
- name: Basic Server Provisioning
hosts: webservers
become: true
tasks:
- name: Update apt package cache
apt:
update_cache: yes
cache_valid_time: 3600
- name: Ensure Nginx is installed
apt:
name: nginx
state: present
- name: Start Nginx and enable on boot
service:
name: nginx
state: started
enabled: yes
- name: Create hello world banner
shell: echo "Managed by Ansible" > /tmp/motd.txt
実行手順
疎通確認と Playbook 実行
アドホックな ping コマンドで全対象ホストへの疎通を確認:
ansible -i hosts all -m ping
インベントリを指定して Playbook を一括実行:
ansible-playbook -i hosts playbook.yml
ドライラン(チェックモード)
対象サーバーに変更を加えずに事前差分をシミュレーション確認:
ansible-playbook -i hosts playbook.yml --check --diff