2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ansibleで空ファイルを作成する方法

Last updated at Posted at 2025-04-23

はじめに

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)

image.png

image.png

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.

ファイル作成が上手くいかないと悩んでいる方の参考になれば良いなと思います。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?