lineinfile 8.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

import re
import os

24
DOCUMENTATION = """
25 26
---
module: lineinfile
27
author: Daniel Hokka Zakrisson
28 29 30 31 32 33 34
short_description: Ensure a particular line is in a file
description:
  - This module will search a file for a line, and ensure that it is present or absent.
  - This is primarily useful when you want to change a single line in a
    file only. For other cases, see the M(copy) or M(template) modules.
version_added: "0.7"
options:
35
  dest:
36
    required: true
37
    aliases: [ name, destfile ]
38 39 40 41 42
    description:
      - The file to modify
  regexp:
    required: true
    description:
43 44
      - The regular expression to look for in the file. For C(state=present),
        the pattern to replace. For C(state=absent), the pattern of the line
45 46
        to remove.  Uses Python regular expressions; see
        U(http://docs.python.org/2/library/re.html).
47 48 49 50 51 52 53 54 55 56
  state:
    required: false
    choices: [ present, absent ]
    default: "present"
    aliases: []
    description:
      - Whether the line should be there or not.
  line:
    required: false
    description:
57
      - Required for C(state=present). The line to insert/replace into the
58
        file. May contain backreferences.
59 60 61 62
  insertafter:
    required: false
    default: EOF
    description:
63
      - Used with C(state=present). If specified, the line will be inserted
64 65
        after the specified regular expression. A special value is
        available; C(EOF) for inserting the line at the end of the file.
66
    choices: [ 'EOF', '*regex*' ]
67 68
  insertbefore:
    required: false
69
    version_added: 1.1
70 71 72 73 74
    description:
      - Used with C(state=present). If specified, the line will be inserted
        before the specified regular expression. A value is available;
         C(BOF) for inserting the line at the beginning of the
        file.
75
    choices: [ 'BOF', '*regex*' ]
76 77
  create:
    required: false
78 79
    choices: [ "yes", "no" ]
    default: "no"
80 81 82 83
    description:
      - Used with C(state=present). If specified, the file will be created
        if it does not already exist. By default it will fail if the file
        is missing.
84 85
  backup:
     required: false
86 87
     default: "no"
     choices: [ "yes", "no" ]
88 89 90
     description:
       - Create a backup file including the timestamp information so you can
         get the original file back if you somehow clobbered it incorrectly.
91 92
  others:
     description:
93
       - All arguments accepted by the M(file) module also work here. 
94
     required: false
95 96 97 98 99 100 101 102 103 104 105 106 107 108
"""

EXAMPLES = """
   lineinfile: dest=/etc/selinux/config regexp=^SELINUX= line=SELINUX=disabled

   lineinfile: dest=/etc/sudoers state=absent regexp="^%wheel"

   lineinfile: dest=/etc/host regexp='^127\.0\.0\.1' line='127.0.0.1 localhost' owner=root group=root mode=0644

   lineinfile: dest=/etc/httpd/conf/httpd.conf regexp="^Listen " insertafter="^#Listen " line="Listen 8080"

   lineinfile: dest=/etc/services regexp="^# port for http" insertbefore="^www.*80/tcp" line="# port for http by default"

   lineinfile: \\\"dest=/etc/sudoers state=present regexp='^%wheel' line ='%wheel ALL=(ALL) NOPASSWD: ALL'\\\"
109 110

   lineinfile dest=/tmp/grub.conf state=present regexp='^(splashimage=.*)$' line="#\\1"
111
"""
112
   
113

Michel Blanc committed
114
def check_file_attrs(module, changed, message):
115 116 117

    file_args = module.load_file_common_arguments(module.params)
    if module.set_file_attributes_if_different(file_args, False):
Michel Blanc committed
118

119 120 121 122 123 124 125
        if changed:
            message += " and "
        changed = True
        message += "ownership, perms or SE linux context changed"

    return [ message, changed ]

126
def present(module, dest, regexp, line, insertafter, insertbefore, create, backup):
127 128 129 130 131 132 133 134 135 136 137 138 139 140

    if os.path.isdir(dest):
        module.fail_json(rc=256, msg='Destination %s is a directory !' % dest)
    elif not os.path.exists(dest):
        if not create:
            module.fail_json(rc=257, msg='Destination %s does not exist !' % dest)
        destpath = os.path.dirname(dest)
        if not os.path.exists(destpath):
            os.makedirs(destpath)
        lines = []
    else:
        f = open(dest, 'rb')
        lines = f.readlines()
        f.close()
141

Michel Blanc committed
142 143
    msg = ""

144
    mre = re.compile(regexp)
145
    
146
    if insertafter is not None and insertafter not in ('BOF', 'EOF'):
147
        insre = re.compile(insertafter)
148 149 150 151
    elif insertbefore is not None and insertbefore not in ('BOF'):
        insre = re.compile(insertbefore)
    else:
        insre = None
152

153 154
    # index[0] is the line num where regexp has been found
    # index[1] is the line num where insertafter/inserbefore has been found
155
    index = [-1, -1]
156
    m = None
157
    for lineno in range(0, len(lines)):
158 159
        match_found = mre.search(lines[lineno])
        if match_found:
160
            index[0] = lineno
161
            m = match_found
162 163 164 165 166 167 168
        elif insre is not None and insre.search(lines[lineno]):
            if insertafter:
                # + 1 for the next line
                index[1] = lineno + 1
            if insertbefore:
                # + 1 for the previous line
                index[1] = lineno
169 170 171

    # Regexp matched a line in the file
    if index[0] != -1:
172
        if lines[index[0]] == m.expand(line) + os.linesep:
173 174 175
            msg = ''
            changed = False
        else:
176
            lines[index[0]] = m.expand(line) + os.linesep
177 178 179
            msg = 'line replaced'
            changed = True
    # Add it to the beginning of the file
180
    elif insertbefore == 'BOF' or insertafter == 'BOF':
181 182 183
        lines.insert(0, line + os.linesep)
        msg = 'line added'
        changed = True
184 185 186
    # Add it to the end of the file if requested or
    # if insertafter=/insertbefore didn't match anything
    # (so default behaviour is to add at the end)
187 188 189 190
    elif insertafter == 'EOF' or index[1] == -1:
        lines.append(line + os.linesep)
        msg = 'line added'
        changed = True
191
    # insertafter/insertbefore= matched
192 193 194 195 196
    else:
        lines.insert(index[1], line + os.linesep)
        msg = 'line added'
        changed = True

197
    if changed and not module.check_mode:
198
        if backup and os.path.exists(dest):
199 200
            module.backup_local(dest)
        f = open(dest, 'wb')
201 202 203
        f.writelines(lines)
        f.close()

Michel Blanc committed
204
    [ msg, changed ] = check_file_attrs(module, changed, msg)
205 206
    module.exit_json(changed=changed, msg=msg)

207
def absent(module, dest, regexp, backup):
208 209 210 211 212 213 214

    if os.path.isdir(dest):
        module.fail_json(rc=256, msg='Destination %s is a directory !' % dest)
    elif not os.path.exists(dest):
        module.exit_json(changed=False, msg="file not present")

    msg = ""
Michel Blanc committed
215

216
    f = open(dest, 'rb')
217 218 219 220
    lines = f.readlines()
    f.close()
    cre = re.compile(regexp)
    found = []
Michael DeHaan committed
221

222
    def matcher(line):
223
        if cre.search(line):
224 225 226 227
            found.append(line)
            return False
        else:
            return True
Michael DeHaan committed
228

229 230
    lines = filter(matcher, lines)
    changed = len(found) > 0
231
    if changed and not module.check_mode:
232
        if backup:
233 234
            module.backup_local(dest)
        f = open(dest, 'wb')
235 236
        f.writelines(lines)
        f.close()
237 238 239 240

    if changed:
        msg = "%s line(s) removed" % len(found)

Michel Blanc committed
241
    [ msg, changed ] = check_file_attrs(module, changed, msg)
242
    module.exit_json(changed=changed, found=len(found), msg=msg)
243 244 245 246

def main():
    module = AnsibleModule(
        argument_spec = dict(
247
            dest=dict(required=True, aliases=['name', 'destfile']),
248 249 250
            state=dict(default='present', choices=['absent', 'present']),
            regexp=dict(required=True),
            line=dict(aliases=['value']),
251 252
            insertafter=dict(default=None),
            insertbefore=dict(default=None),
253 254
            create=dict(default=False, type='bool'),
            backup=dict(default=False, type='bool'),
255
        ),
256
        mutually_exclusive = [['insertbefore', 'insertafter']],
257
        add_file_common_args = True,
258
        supports_check_mode = True
259 260 261
    )

    params = module.params
262 263
    create = module.params['create']
    backup = module.params['backup']
264
    dest   = os.path.expanduser(params['dest'])
265 266 267 268

    if params['state'] == 'present':
        if 'line' not in params:
            module.fail_json(msg='line= is required with state=present')
269
        present(module, dest, params['regexp'], params['line'],
270
                params['insertafter'], params['insertbefore'], create, backup)
271
    else:
272
        absent(module, dest, params['regexp'], backup)
273 274 275 276 277 278

# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>

main()