Ansible Playbook の基本的な利用方法
環境
Ubuntu 24.04
概要
Playbook は冪等性 (べきとうせい) を確保するための
処理をまとめたもので、YAML 形式で記述します。
使用例1
あるファイルが常に同じ属性で存在するシンプルな Playbook を作成します。
$ vi test.yml
# 対象ホスト名 または グループ名
- hosts: 10.0.10.51
tasks:
# 任意のタスク名
- name: Test Task
# [file] モジュールを利用してファイルの状態を記述
file:
path: /home/ubuntu/ark.conf
state: touch
owner: ubuntu
group: ubuntu
mode: 0600
Playbookを実行する
$ ansible-playbook test.yml
結果確認
$ ansible 10.0.10.51 -m command -a "ls -l /home/ubuntu" 10.0.10.51 | CHANGED | rc=0 >> total 0 -rw------- 1 ubuntu ubuntu 0 Jul 31 00:13 ark.conf
使用例2
Apache2 がインストールされ、起動した状態とする
$ vi test.yml
- hosts: target_servers
# 他のユーザー権限を利用 (デフォルト : root)
become: yes
# 他のユーザー権限を利用する方法
become_method: sudo
tasks:
# タスクの定義
- name: apache2 is installed
apt:
name: apache2
state: present
- name: apache2 is running and enabled
service:
name: apache2
state: started
enabled: yes
実行
$ ansible-playbook test.yml --ask-become-pass
確認
$ ansible target_servers -m shell -a “/bin/systemctl status apache2 | head -3"