LoginSignup
14
30

More than 1 year has passed since last update.

Ansible — ansible playbook の基本

Last updated at Posted at 2017-09-28

概念

インベントリ

Ansibleの大前提として、
インベントリでは、動作対象のホストをグループ化出来る

image.png

Playbook

Playbook では「このグループに対して、こういう動作をさせる」という、一連の処理の流れを記述できる。

image.png

インベントリ x Playbook

この組み合わせは自由。

インベントリファイルでホストをグループ化しているので、
Playbookでは対象ホストに関して、煩雑な記述をしなくても済む。

image.png

動作確認

インベントリ

example グループとして、接続先のホストを記述する

inventory.txt
[example]
0.0.0.0
0.0.0.1

プレイブック

この例では

  • example グループに対して
  • shell モジュールを使って
  • ファイルを作成する

という処理をする。

playbook.yml
---
- hosts: example
  tasks:
  - name: touch text file
    shell: touch example.txt

実行

ansible-playbook -i inventory.txt playbook.yml

インベントリで変数を定義する

インベントリ

  • example グループが変数 ( vars ) を持つようにする
inventory.txt
[example]
0.0.0.0
0.0.0.1

[example:vars]
file_name=example

プレイブック

Playbook の中で変数 ( {{file_name}} ) が使えるようになる

playbook.yml
---
- hosts: example
  tasks:
  - name: touch text file
    shell: touch {{file_name}}.txt

プレイブックで変数を定義する

インベントリで定義していた変数を、Playbookの中に移し替えてみる。

インベントリ

ここでは変数を指定しない。

inventory.txt
[example]
0.0.0.0
0.0.0.1

プレイブック

Playbook の中で変数を定義して、さらにそれを使ってみる。

playbook.yml
---
- hosts: example
  vars:
    file_name: example
  tasks:
  - name: touch text file
    shell: touch {{file_name}}.txt

ansible コマンドとの違い

ansible コマンドで同様の操作をおこなう場合は、次のとおり。

ansible -i inventory.txt example -m shell -a 'touch example.txt'

ansible コマンドでもインベントリファイルを使うことに変わりはないが、
動作自体はワンライナーで書く必要があるため、複雑な処理はおこないづらい。

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

14
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
30