Ansible Playbookの書き方のサンプル

環境
Ansible
RHEL8.6

概要
ベストプラクティスでは、Playbookの再利用性を高めるために、ロールによる分割を行っています。
以下は、ベストプラクティスを参考にしたディレクトリ構造例です。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
production # 商用環境用のインベントリファイル
staging # 開発環境用のインベントリファイル
group_vars/ # グループに対する変数
all.yml
group1.yml
group2.yml
host_vars/ # ホストに対する変数
hostname1
hostname2
site.yml # webservers.ymlとdbservers.ymlをインクルード
webservers.yml # 必要なRoleを指定して実行
dbservers.yml # 必要なRoleを指定して実行
ansible.cfg # 設定ファイル
roles/
common/ #
tasks/ # タスク用
main.yml #
handlers/ # ハンドラ用
main.yml #
templates/ # テンプレートファイル
ntp.conf.j2 #
files/ # 転送するファイル
bar.txt #
foo.sh #
defaults/ # デフォルト変数(最も優先度が低い)
main.yml #
nginx/
mysql/
production # 商用環境用のインベントリファイル staging # 開発環境用のインベントリファイル group_vars/ # グループに対する変数 all.yml group1.yml group2.yml host_vars/ # ホストに対する変数 hostname1 hostname2 site.yml # webservers.ymlとdbservers.ymlをインクルード webservers.yml # 必要なRoleを指定して実行 dbservers.yml # 必要なRoleを指定して実行 ansible.cfg # 設定ファイル roles/ common/ # tasks/ # タスク用 main.yml # handlers/ # ハンドラ用 main.yml # templates/ # テンプレートファイル ntp.conf.j2 # files/ # 転送するファイル bar.txt # foo.sh # defaults/ # デフォルト変数(最も優先度が低い) main.yml # nginx/ mysql/
production                # 商用環境用のインベントリファイル
staging                   # 開発環境用のインベントリファイル
 
group_vars/               # グループに対する変数
   all.yml
   group1.yml             
   group2.yml             
host_vars/                # ホストに対する変数
   hostname1              
   hostname2              
 
site.yml                  # webservers.ymlとdbservers.ymlをインクルード
webservers.yml            # 必要なRoleを指定して実行
dbservers.yml             # 必要なRoleを指定して実行
 
ansible.cfg               # 設定ファイル
 
roles/
    common/               #
        tasks/            # タスク用
            main.yml      #
        handlers/         # ハンドラ用
            main.yml      #
        templates/        # テンプレートファイル
            ntp.conf.j2   #
        files/            # 転送するファイル
            bar.txt       #
            foo.sh        #
        defaults/         # デフォルト変数(最も優先度が低い)
            main.yml      #
 
    nginx/                
    mysql/

操作例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
---
- hosts: all
become: true
tasks:
- name: ローカルのファイルをリモートにコピーする
copy:
src={{ playbook_dir }}/tmp/data.txt
dest=/tmp
owner=root
group=root
mode=0700
tags: upload
- name: Apacheをインストール
yum: name=httpd state=latest
--- - hosts: all become: true tasks: - name: ローカルのファイルをリモートにコピーする copy: src={{ playbook_dir }}/tmp/data.txt dest=/tmp owner=root group=root mode=0700 tags: upload - name: Apacheをインストール yum: name=httpd state=latest
---
- hosts: all
  become: true
  tasks:
    - name: ローカルのファイルをリモートにコピーする
      copy: 
        src={{ playbook_dir }}/tmp/data.txt
        dest=/tmp
        owner=root
        group=root
        mode=0700
      tags: upload
 
    - name: Apacheをインストール
      yum: name=httpd state=latest

 

Ansible

Posted by arkgame