(ansible)statとwhenを使ってみる

投稿者: | 2016年10月30日

みなさんこんにちは。ヒロウミです。

ansibleのplaybookで「ファイルの存在確認→結果を元に条件分岐」の流れを簡単にやってみたのでメモっておきます。

# cat stat.yml
---
- hosts: target01
  tasks:
  - name: /tmp/stat_test.txtのstatusを取得
    stat: path=/tmp/stat_test.txt
    register: file_stat

  - debug: var=file_stat

  - name: /tmp/stat_test.txtが存在すればファイル名を変更
    command: mv /tmp/stat_test.txt /tmp/stat_test_exists.txt
    when: file_stat.stat.exists

 

実行してみます。

# ansible-playbook stat.yml

PLAY [target01] ****************************************************************

TASK [setup] *******************************************************************
ok: [target01]

TASK [/tmp/stat_test.txtのstatusを取得] ****************************************                                                                                        ****
ok: [target01]

TASK [debug] *******************************************************************
ok: [target01] => {
    "file_stat": {
        "changed": false,
        "stat": {
            "atime": 1477802908.3489275,
            "checksum": "caab9e3b38255f94faa22678f01d937b2473f72b",
            "ctime": 1477802902.4509263,
            "dev": 64768,
            "exists": true,
            "gid": 0,
            "gr_name": "root",
            "inode": 264701,
            "isblk": false,
            "ischr": false,
            "isdir": false,
            "isfifo": false,
            "isgid": false,
            "islnk": false,
            "isreg": true,
            "issock": false,
            "isuid": false,
            "md5": "a1b4051f012505b4919cb12df7a14e55",
            "mode": "0644",
            "mtime": 1477802902.4509263,
            "nlink": 1,
            "path": "/tmp/stat_test.txt",
            "pw_name": "root",
            "rgrp": true,
            "roth": true,
            "rusr": true,
            "size": 20,
            "uid": 0,
            "wgrp": false,
            "woth": false,
            "wusr": true,
            "xgrp": false,
            "xoth": false,
            "xusr": false
        }
    }
}

TASK [/tmp/stat_test.txtが存在すればファイル名を変更] **************************                                                                                        **************
changed: [target01]

PLAY RECAP *********************************************************************
target01                   : ok=4    changed=1    unreachable=0    failed=0