togatttiのエンジニアメモ

過度な期待はしないでください.

Ansibleで、クライアントPCのファイルの存在チェック

Ansibleを使うとき、クライアント側の実行結果をトリガーにして何かする場合、 local_actionとregisterモジュールを組み合わせれば良い。

クライアントPC側で、あるファイルの存在を確認するためには、statモジュールを使う。

使用例

一般的なAnsibleのディレクトリ構造が以下のようにあり、commonは、

config.ymlをリモートマシンに送るrolesである。

tree .
.
├── inventory
│   └── hosts
├── roles
│   └── common
│       ├── files
│       │   └── config.yml
│       └── tasks
│           └── main.yml
└── site.yml

roles/common/tasks/main.yml の中身は次のように書いた。

ここでは、config.ymlが存在していれば、ファイルをリモートに転送して、

無ければ、ファイルの転送をスキップするように振り分ける。

# roles/common/tasks/main.yml
- name: check config.yml exists in local
  local_action: stat path="roles/common/files/config.yml"
  register: file
  ignore_errors: True

- name: copy config.yml to remote
  copy: src=config.yml dest=~/config.yml
  when: file.stat.exists

config.ymlがある場合

ansible-playbook -i inventory/hosts site.yml 

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [***.***.***.***]

TASK [common : check config.yml exists in local] *******************************
ok: [***.***.***.***]

TASK [common : copy config.yml to remote] **************************************
changed: [***.***.***.***]

PLAY RECAP *********************************************************************
***.***.***.***            : ok=3    changed=1    unreachable=0    failed=0

config.ymlがない場合

ansible-playbook -i inventory/hosts site.yml 

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [***.***.***.***]

TASK [common : check config.yml exists in local] *******************************
ok: [***.***.***.***]

TASK [common : copy config.yml to remote] **************************************
skipping: [***.***.***.***]

PLAY RECAP *********************************************************************
***.***.***.***            : ok=2    changed=0    unreachable=0    failed=0