Skip to main content

lineinfile

lineinfile module

Ensure a particular line is in a file, or replace an existing line using a back-referenced regular expression. This module is useful for making small changes to configuration files.

Examples

- name: Add a line to a file
lineinfile:
path: /etc/hosts
line: "192.168.1.100 myhost.example.com"

- name: Replace a line using regex
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PermitRootLogin'
line: 'PermitRootLogin no'

- name: Remove a line
lineinfile:
path: /etc/hosts
regexp: '^192\.168\.1\.100'
state: absent

- name: Insert line after pattern
lineinfile:
path: /etc/fstab
insertafter: '^/dev/sda1'
line: '/dev/sda2 /home ext4 defaults 0 2'

- name: Create file if it doesn't exist
lineinfile:
path: /etc/myapp.conf
line: 'setting=value'
create: true
mode: '0644'

Note: Use regular expressions carefully to avoid unintended matches. The module will create the file if it doesn't exist and create=true is specified.

Module Capabilities

  • Has Revert: true
  • Provides Variables: None

Inputs

ParameterTypeDescriptionRequiredDefaultChoices
backrefsboolUse backreferences from regexp in the line. Only works with regexp.falsefalsetrue, false
createboolCreate the file if it doesn't exist.falsefalsetrue, false
insertafterstringInsert line after this regex pattern, or 'EOF' for end of file.false
insertbeforestringInsert line before this regex pattern, or 'BOF' for beginning of file.false
linestringThe line to insert or replace. Required when state=present.false
modestringFile permissions to set if creating the file (e.g., '0644').false
pathstringPath to the file to modify. Aliases: dest, destfile, name.false
regexpstringRegular expression to match existing lines for replacement or removal.false
statestringWhether the line should be present or absent.falsepresentpresent, absent

Outputs

FieldTypeDescription
msgstring

Parameter aliases

  • dest → path
  • destfile → path
  • name → path