Skip to content

Ansible モジュール チートシート

Ansible は強力な自動化ツールです。この記事では、その一般的なモジュールの使用方法を紹介します。

形式

基本的なファイル構造

---
- hosts: production
  remote_user: root
  tasks:
  - ···

モジュールは tasks の下に配置してください。

タスクの形式

1行形式

- apt: pkg=vim state=present

マッピング形式

- apt:
    pkg: vim
    state: present

折りたたみスカラー形式

- apt: >
    pkg=vim
    state=present

上記のどの形式を使用してもタスクを定義できます。短い宣言には1行形式、長い宣言にはマッピング形式が推奨されます。

モジュール

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: [email protected]

リファレンス: 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     # 自動起動を有効にする

リファレンス: 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 # 種類: directory|file|link|hard|touch|absent

    # オプション パラメータ:
    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 モジュール