Ansible Playbook の基本的な利用方法

環境
Ubuntu 24.04

概要
Playbook は冪等性 (べきとうせい) を確保するための
処理をまとめたもので、YAML 形式で記述します。

使用例1
あるファイルが常に同じ属性で存在するシンプルな Playbook を作成します。
$ vi test.yml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 対象ホスト名 または グループ名
- hosts: 10.0.10.51
tasks:
# 任意のタスク名
- name: Test Task
# [file] モジュールを利用してファイルの状態を記述
file:
path: /home/ubuntu/ark.conf
state: touch
owner: ubuntu
group: ubuntu
mode: 0600
# 対象ホスト名 または グループ名 - hosts: 10.0.10.51 tasks: # 任意のタスク名 - name: Test Task # [file] モジュールを利用してファイルの状態を記述 file: path: /home/ubuntu/ark.conf state: touch owner: ubuntu group: ubuntu mode: 0600
# 対象ホスト名 または グループ名
- 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

結果確認

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ 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
$ 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
$ 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 がインストールされ、起動した状態とする

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ 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
$ 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
$ 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

実行

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ ansible-playbook test.yml --ask-become-pass
$ ansible-playbook test.yml --ask-become-pass
$ ansible-playbook test.yml --ask-become-pass

確認
$ ansible target_servers -m shell -a “/bin/systemctl status apache2 | head -3"

IT

Posted by arkgame