Ansible file 모듈을 활용한 파일 및 디렉토리 관리

Ansible의 file 모듈은 원격 호스트에서 파일, 디렉토리, 심볼릭 링크의 생성 및 삭제를 관리하고, 권한이나 소유권과 같은 속성을 설정하는 데 사용되는 핵심 모듈입니다. copy, template, assemble과 같은 다른 모듈에서도 유사한 파일 속성 설정 기능을 제공하지만, 파일 시스템 자체의 구조를 제어할 때는 file 모듈이 주로 사용됩니다.

주요 파라미터 구성

파라미터 설명
path 파일이나 디렉토리의 절대 경로를 지정합니다. (필수)
state 대상 상태를 정의합니다. (touch: 파일 생성, absent: 삭제, directory: 디렉토리 생성, link: 심볼릭 링크, hard: 하드 링크)
owner 파일의 소유자를 설정합니다.
group 파일의 소유 그룹을 설정합니다.
mode 파일의 권한을 설정합니다. (예: 0644, 0755)
src 링크를 생성할 때 원본 파일의 경로를 지정합니다.
recurse state=directory일 때 하위 항목들에 속성을 재귀적으로 적용할지 여부를 결정합니다.

1. 신규 파일 생성

모든 대상 서버의 /tmp 디렉토리에 system_init.log라는 빈 파일을 생성하는 예시입니다.

# 애드혹(Ad-hoc) 명령 실행
ansible web_nodes -m file -a "path=/tmp/system_init.log state=touch"

# 실행 결과 (요약)
192.168.1.10 | CHANGED => {
    "changed": true,
    "dest": "/tmp/system_init.log",
    "mode": "0644",
    "owner": "root",
    "state": "file"
}

2. 특정 파일 삭제

특정 노드에서 더 이상 필요 없는 임시 파일을 제거합니다. state=absent를 사용하면 파일이 존재하지 않을 경우 아무 작업도 수행하지 않으며(Idempotency), 존재하면 삭제합니다.

ansible node_01 -m file -a "path=/tmp/system_init.log state=absent"

3. 파일 권한 및 소유권 변경

파일의 보안 강화를 위해 특정 사용자만 접근할 수 있도록 권한과 소유권을 수정할 수 있습니다.

# 사용자: dev_user, 그룹: developers, 권한: 600(소유자 읽기/쓰기만 가능)
ansible db_servers -m file -a "path=/var/www/config.php owner=dev_user group=developers mode=0600"

4. 심볼릭 링크 및 하드 링크 생성

원본 파일을 가리키는 링크 파일을 생성합니다. src는 원본 경로, path는 생성될 링크 경로를 의미합니다.

# 심볼릭 링크 생성
ansible all -m file -a "src=/etc/nginx/sites-available/default path=/etc/nginx/sites-enabled/default state=link"

# 하드 링크 생성
ansible all -m file -a "src=/data/backup.tar.gz path=/data/backup_hardlink.tar.gz state=hard"

5. 디렉토리 관리 및 재귀적 설정

새로운 디렉토리를 생성하고, 해당 디렉토리와 내부의 모든 파일에 대해 동일한 권한을 한 번에 적용할 수 있습니다.

# 디렉토리 생성 및 권한 재귀 설정
ansible app_servers -m file -a "path=/opt/app_data state=directory owner=webadmin mode=0755 recurse=yes"

6. 디렉토리 전체 삭제

디렉토리를 삭제할 때 state=absent를 지정하면 하위 파일과 폴더를 포함하여 모두 제거됩니다.

ansible all -m file -a "path=/opt/app_data state=absent"

태그: Ansible ansible-module linux-administration automation DevOps

6월 2일 18:42에 게시됨