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
Parameter | Type | Description | Required | Default | Choices |
---|---|---|---|---|---|
backrefs | bool | Use backreferences from regexp in the line. Only works with regexp. | false | false | true, false |
create | bool | Create the file if it doesn't exist. | false | false | true, false |
insertafter | string | Insert line after this regex pattern, or 'EOF' for end of file. | false | ||
insertbefore | string | Insert line before this regex pattern, or 'BOF' for beginning of file. | false | ||
line | string | The line to insert or replace. Required when state=present. | false | ||
mode | string | File permissions to set if creating the file (e.g., '0644'). | false | ||
path | string | Path to the file to modify. Aliases: dest, destfile, name. | false | ||
regexp | string | Regular expression to match existing lines for replacement or removal. | false | ||
state | string | Whether the line should be present or absent. | false | present | present, absent |
Outputs
Field | Type | Description |
---|---|---|
msg | string |
Parameter aliases
- dest → path
- destfile → path
- name → path