[file] Ansible로 빈 파일을 만드는 방법은 무엇입니까?

Ansible을 사용하여 빈 파일을 만드는 가장 쉬운 방법은 무엇입니까? 빈 파일을 files디렉토리에 저장 한 다음 원격 호스트에 복사 할 수 있다는 것을 알고 있지만 다소 만족스럽지 않습니다.

또 다른 방법은 원격 호스트의 파일을 터치하는 것입니다.

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555

그러나 파일은 매번 터치되어 로그에 노란색 선으로 표시되며 불만족 스럽습니다.

이 간단한 문제에 대한 더 나은 해결책이 있습니까?



답변

파일 모듈의 문서에 따르면

인 경우 state=file파일이 존재하지 않으면 생성되지 않습니다. 해당 동작을 원하면 복사 또는 템플릿 모듈을 참조하십시오.

따라서 복사 모듈을 사용 force=no하여 파일이 아직 존재하지 않을 때만 새로운 빈 파일을 생성합니다 (파일이 존재하면 내용이 보존 됨).

- name: ensure file exists
  copy:
    content: ""
    dest: /etc/nologin
    force: no
    group: sys
    owner: root
    mode: 0555

이것은 선언적이고 우아한 솔루션입니다.


답변

다음과 같이 작동합니다 ( stat먼저 모듈을 사용하여 데이터를 수집 한 다음 조건부로 필터링).

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
  when: p.stat.exists is defined and not p.stat.exists

또는 changed_when기능 을 활용할 수도 있습니다.


답변

명령 모듈을 사용하는 또 다른 옵션 :

- name: Create file
  command: touch /path/to/file
  args:
    creates: /path/to/file

‘creates’인수는 파일이 존재하는 경우이 작업이 수행되지 않도록합니다.


답변

수락 된 답변을 기반으로 실행될 때마다 파일의 권한을 확인하고 파일이 존재하는 경우 이에 따라 변경되거나 파일이없는 경우 파일을 생성하려면 다음을 사용할 수 있습니다.

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin
        owner=root
        group=sys
        mode=0555
        state={{ "file" if  p.stat.exists else "touch"}}


답변

file: path=/etc/nologin state=touch

터치와 완전히 동일 (1.4+에서 새로 추가됨)-파일 타임 스탬프를 변경하지 않으려면 stat를 사용하십시오.


답변

파일 모듈은 시간을 수정하지 않고 파일을 터치하는 방법을 제공합니다.

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: u+rw,g-wx,o-rwx
    modification_time: preserve
    access_time: preserve

참조 :
https://docs.ansible.com/ansible/latest/modules/file_module.html


답변

나는 이것을 주석으로 넣기에 충분한 평판을 가지고 있지 않다는 것이 밝혀졌습니다.

레. AllBlackt의 답변, Ansible의 여러 줄 형식을 선호하는 경우 인용문을 조정해야합니다 state(이 작업에 몇 분이 걸렸 으므로 다른 사람의 속도를 높일 수 있기를 바랍니다).

- stat:
    path: "/etc/nologin"
  register: p

- name: create fake 'nologin' shell
  file:
    path: "/etc/nologin"
    owner: root
    group: sys
    mode: 0555
    state: '{{ "file" if  p.stat.exists else "touch" }}'