Ansible lineinfile 모듈을 활용한 파일 라인 관리

Ansible에서 특정 파일의 단일 라인을 추가, 수정 또는 삭제해야 할 때 lineinfile 모듈을 활용할 수 있습니다. 이 모듈은 멱등성(idempotency)을 보장하여 동일한 작업을 여러 번 실행해도 결과가 일관되게 유지됩니다.

모듈 개요

lineinfile은 파일 내 특정 문자열의 존재를 보장하거나 정규식을 이용해 기존 라인을 교체합니다. 여러 라인을 동시에 다룰 경우 blockinfile 모듈을, 템플릿 기반 관리가 필요하면 template 모듈을 고려하세요.

핵심 파라미터

파라미터필수설명
path대상 파일 경로 (Ansible 2.3 이전에는 dest, destfile, name 사용)
line조건부추가/교체할 라인 내용 (state=present 시 필수)
regexp아니오매칭할 정규식 패턴
state아니오present(추가/수정) 또는 absent(삭제)
insertafter아니오지정 패턴 뒤에 삽입 (기본값: EOF)
insertbefore아니오지정 패턴 앞에 삽입 (기본값: BOF)
backrefs아니오정규식 캡처 그룹을 활용한 역참조 활성화
create아니오파일이 없을 때 생성 여부 (기본값: no)
backup아니오변경 전 파일 백업 생성
validate아니오저장 전 구문 검증 명령어

실전 활용 예제

설정값 변경

- name: SSH 포트를 2222로 변경
  lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^#?Port\s+'
    line: 'Port 2222'
  notify: restart sshd

라인 삭제

- name: 불필요한 별칭 설정 제거
  lineinfile:
    path: /etc/bashrc
    state: absent
    regexp: '^alias rm='

조건부 삽입

- name: 환경변수 설정 추가
  lineinfile:
    path: /etc/profile
    regexp: '^export APP_HOME='
    line: 'export APP_HOME=/opt/myapp'
    insertafter: '^export PATH='

파일 최초 생성 시 라인 추가

- name: 커스텀 hosts 항목 보장
  lineinfile:
    path: /etc/hosts.custom
    line: '10.0.0.5  internal-api.local'
    create: true
    mode: '0644'

정규식 역참조 활용

- name: JVM 힙 메모리 설정 동적 수정
  lineinfile:
    path: /opt/tomcat/bin/setenv.sh
    regexp: '^(CATALINA_OPTS=.*)-Xmx\d+m(.*)$'
    line: '\1-Xmx2048m\2'
    backrefs: yes

검증과 함께 안전하게 적용

- name: sudoers 파일 안전하게 수정
  lineinfile:
    path: /etc/sudoers
    regexp: '^%developers\s+'
    line: '%developers ALL=(ALL) NOPASSWD: /usr/bin/systemctl *'
    validate: '/usr/sbin/visudo -cf %s'
    state: present

멱등성 보장 팁

정규식을 설계할 때는 변경 전후 상태 모두 매칭되도록 작성하세요. 예를 들어 ^#?Port\s+는 주석 처리된 상태와 활성화된 상태 모두 포착하여 중복 추가를 방지합니다.

# 비권장: 변경 후 다시 실행하면 중복 추가됨
regexp: '^Port 22$'

# 권장: 주석 여부와 기존 값 관계없이 매칭
regexp: '^#?Port\s+'

주의사항

  • backrefs: yes 설정 시 insertafterinsertbefore는 무시됩니다
  • insertafterinsertbefore는 동시에 사용할 수 없습니다
  • 파일이 없고 create: no일 경우 작업이 실패합니다
  • SELinux 환경에서는 seuser, serole, setype 파라미터를 활용할 수 있습니다

태그: Ansible lineinfile configuration-management infrastructure-as-code YAML

6월 26일 01:34에 게시됨