はじめに
Ansible-Playbookで空ファイルを作成するタスクを作成する際に、少しつまずいたところがあるのでアウトプットとして記載します。
試したこと
空ファイルを新規作成しようとして以下のタスクを実行しましたが、パスが存在しないというエラーが発生しました。
- name: add new file
ansible.builtin.file:
path: "/test/path/newfile.txt"
state: file
mode: "0644"
FAILED! => {"changed": false, "msg": "file (/test/path/newfile.txt) is absent, cannot continue", "path": "/test/path/newfile.txt", "state": "absent"}
結論
state: file
ではなくstate: touch
を使用します。
- name: add new file
ansible.builtin.file:
path: "/test/path/newfile.txt"
state: touch
mode: "0644"
概要
state: file
はファイルの情報取得やパーミッション・所有者・ユーザーグループの変更などに使うもので、新規作成にはstate: touch
を使用します。
- name: add new file
ansible.builtin.file:
path: "/test/path/newfile.txt"
state: touch
mode: "0644"
- name: change file permission
ansible.builtin.file:
path: "/test/path/newfile.txt"
state: file # デフォルトがstate: fileなので指定しなくても可
mode: "0755"
他にも、ディレクトリの作成にはstate:directory
、ファイル・ディレクトリ削除はstate: absent
を使用します。
最後に
Github Copilotでの回答が、state: file
でファイルが存在しない場合にファイルを新規作成するというものでしたが、調査したところ新規作成はできないようです。(https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html)
If file, even with other options (such as mode), the file will be modified if it exists but will NOT be created if it does not exist.
ファイル作成が上手くいかないと悩んでいる方の参考になれば良いなと思います。