lineinfile 12.9 KB
Newer Older
1 2 3 4
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
5
# (c) 2014, Ahti Kitsik <ak@ahtik.com>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# 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
import tempfile
25

26
DOCUMENTATION = """
27 28
---
module: lineinfile
29
author: Daniel Hokka Zakrisson, Ahti Kitsik
30 31
short_description: Ensure a particular line is in a file, or replace an
                   existing line using a back-referenced regular expression.
32 33 34 35 36 37
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:
38
  dest:
39
    required: true
40
    aliases: [ name, destfile ]
41
    description:
42
      - The file to modify.
43
  regexp:
44
    required: false
45
    description:
46 47 48
      - The regular expression to look for in every line of the file. For
        C(state=present), the pattern to replace if found; only the last line
        found will be replaced. For C(state=absent), the pattern of the line
49 50
        to remove.  Uses Python regular expressions; see
        U(http://docs.python.org/2/library/re.html).
51 52 53 54 55 56 57 58 59 60
  state:
    required: false
    choices: [ present, absent ]
    default: "present"
    aliases: []
    description:
      - Whether the line should be there or not.
  line:
    required: false
    description:
61
      - Required for C(state=present). The line to insert/replace into the
62 63
        file. If C(backrefs) is set, may contain backreferences that will get
        expanded with the C(regexp) capture groups if the regexp matches. The
64 65 66 67 68
        backreferences should be double escaped (see examples).
  backrefs:
    required: false
    default: "no"
    choices: [ "yes", "no" ]
69
    version_added: "1.1"
70 71
    description:
      - Used with C(state=present). If set, line can contain backreferences
72
        (both positional and named) that will get populated if the C(regexp)
73
        matches. This flag changes the operation of the module slightly;
74
        C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp)
75
        doesn't match anywhere in the file, the file will be left unchanged.
76
        If the C(regexp) does match, the last matching line will be replaced by
77
        the expanded line parameter.
78 79 80 81
  insertafter:
    required: false
    default: EOF
    description:
82
      - Used with C(state=present). If specified, the line will be inserted
83 84
        after the specified regular expression. A special value is
        available; C(EOF) for inserting the line at the end of the file.
85
        May not be used with C(backrefs).
86
    choices: [ 'EOF', '*regex*' ]
87 88
  insertbefore:
    required: false
89
    version_added: "1.1"
90 91 92
    description:
      - Used with C(state=present). If specified, the line will be inserted
        before the specified regular expression. A value is available;
93
        C(BOF) for inserting the line at the beginning of the file.
94
        May not be used with C(backrefs).
95
    choices: [ 'BOF', '*regex*' ]
96 97
  create:
    required: false
98 99
    choices: [ "yes", "no" ]
    default: "no"
100 101 102 103
    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.
104 105
  backup:
     required: false
106 107
     default: "no"
     choices: [ "yes", "no" ]
108 109 110
     description:
       - Create a backup file including the timestamp information so you can
         get the original file back if you somehow clobbered it incorrectly.
111 112 113
  validate:
     required: false
     description:
114
       - validation to run before copying into place. The command is passed
115
         securely so shell features like expansion and pipes won't work.
116 117 118
     required: false
     default: None
     version_added: "1.4"
119 120
  others:
     description:
tin committed
121
       - All arguments accepted by the M(file) module also work here.
122
     required: false
123 124
"""

125
EXAMPLES = r"""
126
- lineinfile: dest=/etc/selinux/config regexp=^SELINUX= line=SELINUX=disabled
127

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

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

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

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

136 137 138
# Add a line to a file if it does not exist, without passing regexp
- lineinfile: dest=/tmp/testfile line="192.168.1.99 foo.lab.net foo"

139 140
# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'"
141

142
- lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.*)$' line='\1Xms${xms}m\3' backrefs=yes
143 144 145

# Validate a the sudoers file before saving
- lineinfile: dest=/etc/sudoers state=present regexp='^%ADMIN ALL\=' line='%ADMIN ALL=(ALL) NOPASSWD:ALL' validate='visudo -cf %s'
146
"""
tin committed
147

148 149 150 151 152 153 154
def write_changes(module,lines,dest):

    tmpfd, tmpfile = tempfile.mkstemp()
    f = os.fdopen(tmpfd,'wb')
    f.writelines(lines)
    f.close()

155 156 157
    validate = module.params.get('validate', None)
    valid = not validate
    if validate:
158 159
        if "%s" not in validate:
            module.fail_json(msg="validate must contain %%s: %s" % (validate))
160 161 162 163 164 165 166
        (rc, out, err) = module.run_command(validate % tmpfile)
        valid = rc == 0
        if rc != 0:
            module.fail_json(msg='failed to validate: '
                                 'rc:%s error:%s' % (rc,err))
    if valid:
        module.atomic_move(tmpfile, dest)
167

Michel Blanc committed
168
def check_file_attrs(module, changed, message):
169 170

    file_args = module.load_file_common_arguments(module.params)
171
    if module.set_fs_attributes_if_different(file_args, False):
Michel Blanc committed
172

173 174 175 176 177
        if changed:
            message += " and "
        changed = True
        message += "ownership, perms or SE linux context changed"

tin committed
178 179
    return message, changed

180

tin committed
181 182
def present(module, dest, regexp, line, insertafter, insertbefore, create,
            backup, backrefs):
183

184
    if not os.path.exists(dest):
185 186 187 188 189 190 191 192 193 194
        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()
195

Michel Blanc committed
196 197
    msg = ""

198 199
    if regexp is not None:
        mre = re.compile(regexp)
tin committed
200 201

    if insertafter not in (None, 'BOF', 'EOF'):
202
        insre = re.compile(insertafter)
tin committed
203
    elif insertbefore not in (None, 'BOF'):
204 205 206
        insre = re.compile(insertbefore)
    else:
        insre = None
207

208 209
    # index[0] is the line num where regexp has been found
    # index[1] is the line num where insertafter/inserbefore has been found
210
    index = [-1, -1]
211
    m = None
tin committed
212
    for lineno, cur_line in enumerate(lines):
213 214 215 216
        if regexp is not None:
            match_found = mre.search(cur_line)
        else:
            match_found = line == cur_line.rstrip('\r\n')
217
        if match_found:
218
            index[0] = lineno
219
            m = match_found
tin committed
220
        elif insre is not None and insre.search(cur_line):
221 222 223 224 225 226
            if insertafter:
                # + 1 for the next line
                index[1] = lineno + 1
            if insertbefore:
                # + 1 for the previous line
                index[1] = lineno
227

tin committed
228 229
    msg = ''
    changed = False
230 231
    # Regexp matched a line in the file
    if index[0] != -1:
tin committed
232 233
        if backrefs:
            new_line = m.expand(line)
234
        else:
tin committed
235 236 237 238 239
            # Don't do backref expansion if not asked.
            new_line = line

        if lines[index[0]] != new_line + os.linesep:
            lines[index[0]] = new_line + os.linesep
240 241
            msg = 'line replaced'
            changed = True
tin committed
242 243 244 245
    elif backrefs:
        # Do absolutely nothing, since it's not safe generating the line
        # without the regexp matching to populate the backrefs.
        pass
246
    # Add it to the beginning of the file
247
    elif insertbefore == 'BOF' or insertafter == 'BOF':
248 249 250
        lines.insert(0, line + os.linesep)
        msg = 'line added'
        changed = True
251 252 253
    # 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)
254
    elif insertafter == 'EOF':
255 256 257 258 259

        # If the file is not empty then ensure there's a newline before the added line
        if len(lines)>0 and not (lines[-1].endswith('\n') or lines[-1].endswith('\r')):
            lines.append(os.linesep)

260 261 262
        lines.append(line + os.linesep)
        msg = 'line added'
        changed = True
tin committed
263
    # Do nothing if insert* didn't match
264
    elif index[1] == -1:
tin committed
265 266
        pass
    # insert* matched, but not the regexp
267 268 269 270 271
    else:
        lines.insert(index[1], line + os.linesep)
        msg = 'line added'
        changed = True

272
    backupdest = ""
273
    if changed and not module.check_mode:
274
        if backup and os.path.exists(dest):
275
            backupdest = module.backup_local(dest)
276
        write_changes(module, lines, dest)
277

tin committed
278
    msg, changed = check_file_attrs(module, changed, msg)
279
    module.exit_json(changed=changed, msg=msg, backup=backupdest)
280

tin committed
281

282
def absent(module, dest, regexp, line, backup):
283

284
    if not os.path.exists(dest):
285 286 287
        module.exit_json(changed=False, msg="file not present")

    msg = ""
Michel Blanc committed
288

289
    f = open(dest, 'rb')
290 291
    lines = f.readlines()
    f.close()
292 293
    if regexp is not None:
        cre = re.compile(regexp)
294
    found = []
Michael DeHaan committed
295

296 297 298
    def matcher(cur_line):
        if regexp is not None:
            match_found = cre.search(cur_line)
299
        else:
300 301 302 303
            match_found = line == cur_line.rstrip('\r\n')
        if match_found:
            found.append(cur_line)
        return not match_found
Michael DeHaan committed
304

305 306
    lines = filter(matcher, lines)
    changed = len(found) > 0
307
    backupdest = ""
308
    if changed and not module.check_mode:
309
        if backup:
310
            backupdest = module.backup_local(dest)
311
        write_changes(module, lines, dest)
312 313 314 315

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

tin committed
316
    msg, changed = check_file_attrs(module, changed, msg)
317
    module.exit_json(changed=changed, found=len(found), msg=msg, backup=backupdest)
318

tin committed
319

320 321
def main():
    module = AnsibleModule(
tin committed
322
        argument_spec=dict(
323
            dest=dict(required=True, aliases=['name', 'destfile']),
324
            state=dict(default='present', choices=['absent', 'present']),
325
            regexp=dict(default=None),
326
            line=dict(aliases=['value']),
327 328
            insertafter=dict(default=None),
            insertbefore=dict(default=None),
tin committed
329
            backrefs=dict(default=False, type='bool'),
330 331
            create=dict(default=False, type='bool'),
            backup=dict(default=False, type='bool'),
332
            validate=dict(default=None, type='str'),
333
        ),
tin committed
334 335 336
        mutually_exclusive=[['insertbefore', 'insertafter']],
        add_file_common_args=True,
        supports_check_mode=True
337 338 339
    )

    params = module.params
340 341
    create = module.params['create']
    backup = module.params['backup']
tin committed
342 343
    backrefs = module.params['backrefs']
    dest = os.path.expanduser(params['dest'])
344

345 346 347 348

    if os.path.isdir(dest):
        module.fail_json(rc=256, msg='Destination %s is a directory !' % dest)

349
    if params['state'] == 'present':
350 351 352
        if backrefs and params['regexp'] is None:
            module.fail_json(msg='regexp= is required with backrefs=true')

353
        if params.get('line', None) is None:
354
            module.fail_json(msg='line= is required with state=present')
tin committed
355 356 357 358 359 360 361

        # Deal with the insertafter default value manually, to avoid errors
        # because of the mutually_exclusive mechanism.
        ins_bef, ins_aft = params['insertbefore'], params['insertafter']
        if ins_bef is None and ins_aft is None:
            ins_aft = 'EOF'

362 363 364
        # Replace the newline character with an actual newline. Don't replace
		# escaped \\n, hence sub and not str.replace.
        line = re.sub(r'\n', os.linesep, params['line'])
365 366

        present(module, dest, params['regexp'], line,
tin committed
367
                ins_aft, ins_bef, create, backup, backrefs)
368
    else:
369 370 371 372
        if params['regexp'] is None and params.get('line', None) is None:
            module.fail_json(msg='one of line= or regexp= is required with state=absent')

        absent(module, dest, params['regexp'], params.get('line', None), backup)
373

374
# import module snippets
375
from ansible.module_utils.basic import *
376 377

main()