Ansible モジュール チートシート
Ansible は強力な運用自動化ツールです。この記事では、その一般的なモジュールの使用方法を紹介します。
フォーマット
基本的なファイル構造
---
- hosts: production
remote_user: root
tasks:
- ···モジュールは tasks の下に配置してください。
タスクのフォーマット
単一行フォーマット
- apt: pkg=vim state=presentマッピングフォーマット
- apt:
pkg: vim
state: present折りたたみスカラーフォーマット (Folded Scalar)
- apt: >
pkg=vim
state=presentタスクの定義には、上記のいずれのフォーマットも使用できます。短い宣言には単一行フォーマット、長い宣言にはマッピングフォーマットが推奨されます。
モジュール
Aptitude
パッケージ管理
- apt:
pkg: nodejs
state: present # absent | latest
update_cache: yes
force: noDeb パッケージファイル
- apt:
deb: "https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb"リポジトリ管理 (ソフトウェアソース)
- apt_repository:
repo: "deb https://··· raring main"
state: presentリポジトリキー
- apt_key:
id: AC40B2F7
url: "http://···"
state: presentGit 関連
- git:
repo: git://github.com/
dest: /srv/checkout
version: master
depth: 10
bare: yes参考: git モジュール
Git 設定
- git_config:
name: user.email
scope: global # local | system
value: hi@example.com参考: git_config モジュール
ユーザー管理
- user:
state: present # 状態: 存在する
name: git # ユーザー名
system: yes # システムユーザー
shell: /bin/sh # ログインシェル
groups: admin # 所属グループ
comment: "Git Version Control" # コメント参考: user モジュール
サービス管理
- service:
name: nginx # サービス名
state: started # 状態: 開始済み
enabled: yes # OS起動時に有効化するかどうか参考: service モジュール
Shell 関連
shell コマンド
- shell: apt-get install nginx -y追加オプション
- shell: echo hello
args:
creates: /path/file # ファイルが存在すればスキップ
removes: /path/file # ファイルが存在しなければスキップ
chdir: /path # 実行前にこのディレクトリへ移動複数行コマンドの例
- shell: |
echo "hello there"
echo "multiple lines"参考: shell モジュール
スクリプト実行
- script: /x/y/script.sh
args:
creates: /path/file # ファイルが存在すればスキップ
removes: /path/file # ファイルが存在しなければスキップ
chdir: /path # 実行前にこのディレクトリへ移動参考: script モジュール
ファイル操作
ファイル管理
- file:
path: /etc/dir
state: directory # タイプ: ディレクトリ|ファイル|リンク|ハードリンク|touch|削除
# オプションパラメータ:
owner: bin # 所有者
group: wheel # 所属グループ
mode: 0644 # 権限
recurse: yes # 再帰的に作成
force: yes # シンボリックリンクの作成を強制参考: file モジュール
ファイルコピー
- copy:
src: /app/config/nginx.conf # コピー元
dest: /etc/nginx/nginx.conf # コピー先
# オプションパラメータ:
owner: user # 所有者
group: user # 所属グループ
mode: 0644 # 权限
backup: yes # バックアップを作成するか参考: copy モジュール
テンプレート
- template:
src: config/redis.j2 # テンプレートのコピー元
dest: /etc/redis.conf # コピー先
# オプションパラメータ:
owner: user # 所有者
group: user # 所属グループ
mode: 0644 # 権限
backup: yes # バックアップを作成するか参考: template モジュール
本地操作
本地実行
- name: 本地で操作を実行
local_action: shell echo helloデバッグ出力
- debug:
msg: "Hello {{ var }}"参考: debug モジュール