Skip to content

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: no

Deb パッケージファイル

- 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: present

Git 関連

- 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 モジュール