Consistent path attribute for file-related modules

Not all file-related modules consistently use "path" as the attribute to specify a single filename, some use "dest", others use "name". Most do have aliases for either "name" or "destfile".

This change makes "path" the default attribute for (single) file-related modules, but also adds "dest" and "name" as aliases, so that people can use a consistent way of attributing paths, but also to ensure backward compatibility with existing playbooks.

NOTE: The reason for changing this, is that it makes Ansible needlessly harder to use if you have to remember that e.g. the xattr module requires the name attribute, the lineinfile module requires a dest attribute, and the stat module requires a path attribute.
This commit is contained in:
Dag Wieers 2017-01-03 13:47:00 +01:00 committed by Brian Coca
parent 1c8b85a6f1
commit 1ad55ec9de
9 changed files with 215 additions and 200 deletions

View file

@ -27,12 +27,12 @@ short_description: Sets and retrieves file ACL information.
description: description:
- Sets and retrieves file ACL information. - Sets and retrieves file ACL information.
options: options:
name: path:
required: true required: true
default: null default: null
description: description:
- The full path of the file or object. - The full path of the file or object.
aliases: ['path'] aliases: ['name']
state: state:
required: false required: false
@ -54,7 +54,7 @@ options:
default: no default: no
choices: [ 'yes', 'no' ] choices: [ 'yes', 'no' ]
description: description:
- if the target is a directory, setting this to yes will make it the default acl for entities created inside the directory. It causes an error if name is a file. - if the target is a directory, setting this to yes will make it the default acl for entities created inside the directory. It causes an error if path is a file.
entity: entity:
version_added: "1.5" version_added: "1.5"
@ -70,7 +70,6 @@ options:
description: description:
- the entity type of the ACL to apply, see setfacl documentation for more info. - the entity type of the ACL to apply, see setfacl documentation for more info.
permissions: permissions:
version_added: "1.5" version_added: "1.5"
required: false required: false
@ -97,12 +96,13 @@ author:
notes: notes:
- The "acl" module requires that acls are enabled on the target filesystem and that the setfacl and getfacl binaries are installed. - The "acl" module requires that acls are enabled on the target filesystem and that the setfacl and getfacl binaries are installed.
- As of Ansible 2.0, this module only supports Linux distributions. - As of Ansible 2.0, this module only supports Linux distributions.
- As of Ansible 2.3, the I(name) option has been changed to I(path) as default, but I(name) still works as well.
''' '''
EXAMPLES = ''' EXAMPLES = '''
# Grant user Joe read access to a file # Grant user Joe read access to a file
- acl: - acl:
name: /etc/foo.conf path: /etc/foo.conf
entity: joe entity: joe
etype: user etype: user
permissions: r permissions: r
@ -110,14 +110,14 @@ EXAMPLES = '''
# Removes the acl for Joe on a specific file # Removes the acl for Joe on a specific file
- acl: - acl:
name: /etc/foo.conf path: /etc/foo.conf
entity: joe entity: joe
etype: user etype: user
state: absent state: absent
# Sets default acl for joe on foo.d # Sets default acl for joe on foo.d
- acl: - acl:
name: /etc/foo.d path: /etc/foo.d
entity: joe entity: joe
etype: user etype: user
permissions: rw permissions: rw
@ -126,13 +126,13 @@ EXAMPLES = '''
# Same as previous but using entry shorthand # Same as previous but using entry shorthand
- acl: - acl:
name: /etc/foo.d path: /etc/foo.d
entry: "default:user:joe:rw-" entry: "default:user:joe:rw-"
state: present state: present
# Obtain the acl for a specific file # Obtain the acl for a specific file
- acl: - acl:
name: /etc/foo.conf path: /etc/foo.conf
register: acl_info register: acl_info
''' '''
@ -144,6 +144,10 @@ acl:
sample: [ "user::rwx", "group::rwx", "other::rwx" ] sample: [ "user::rwx", "group::rwx", "other::rwx" ]
''' '''
import os
# import module snippets
from ansible.module_utils.basic import AnsibleModule, get_platform
def split_entry(entry): def split_entry(entry):
''' splits entry and ensures normalized return''' ''' splits entry and ensures normalized return'''
@ -258,7 +262,7 @@ def run_acl(module, cmd, check_rc=True):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
name=dict(required=True, aliases=['path'], type='path'), path=dict(required=True, aliases=['name'], type='path'),
entry=dict(required=False, type='str'), entry=dict(required=False, type='str'),
entity=dict(required=False, type='str', default=''), entity=dict(required=False, type='str', default=''),
etype=dict( etype=dict(
@ -284,7 +288,7 @@ def main():
if get_platform().lower() not in ['linux', 'freebsd']: if get_platform().lower() not in ['linux', 'freebsd']:
module.fail_json(msg="The acl module is not available on this system.") module.fail_json(msg="The acl module is not available on this system.")
path = module.params.get('name') path = module.params.get('path')
entry = module.params.get('entry') entry = module.params.get('entry')
entity = module.params.get('entity') entity = module.params.get('entity')
etype = module.params.get('etype') etype = module.params.get('etype')
@ -369,8 +373,5 @@ def main():
module.exit_json(changed=changed, msg=msg, acl=acl) module.exit_json(changed=changed, msg=msg, acl=acl)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -36,15 +36,13 @@ version_added: '2.0'
description: description:
- This module will insert/update/remove a block of multi-line text - This module will insert/update/remove a block of multi-line text
surrounded by customizable marker lines. surrounded by customizable marker lines.
notes:
- This module supports check mode.
- When using 'with_*' loops be aware that if you do not set a unique mark the block will be overwritten on each iteration.
options: options:
dest: path:
aliases: [ name, destfile ] aliases: [ dest, destfile, name ]
required: true required: true
description: description:
- The file to modify. - The file to modify.
- Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).
state: state:
required: false required: false
choices: [ present, absent ] choices: [ present, absent ]
@ -104,12 +102,17 @@ options:
description: description:
- 'This flag indicates that filesystem links, if they exist, should be followed.' - 'This flag indicates that filesystem links, if they exist, should be followed.'
version_added: "2.1" version_added: "2.1"
notes:
- This module supports check mode.
- When using 'with_*' loops be aware that if you do not set a unique mark the block will be overwritten on each iteration.
- As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well.
""" """
EXAMPLES = r""" EXAMPLES = r"""
# Before 2.3, option 'dest' or 'name' was used instead of 'path'
- name: insert/update "Match User" configuration block in /etc/ssh/sshd_config - name: insert/update "Match User" configuration block in /etc/ssh/sshd_config
blockinfile: blockinfile:
dest: /etc/ssh/sshd_config path: /etc/ssh/sshd_config
block: | block: |
Match User ansible-agent Match User ansible-agent
PasswordAuthentication no PasswordAuthentication no
@ -117,7 +120,7 @@ EXAMPLES = r"""
- name: insert/update eth0 configuration stanza in /etc/network/interfaces - name: insert/update eth0 configuration stanza in /etc/network/interfaces
(it might be better to copy files into /etc/network/interfaces.d/) (it might be better to copy files into /etc/network/interfaces.d/)
blockinfile: blockinfile:
dest: /etc/network/interfaces path: /etc/network/interfaces
block: | block: |
iface eth0 inet static iface eth0 inet static
address 192.0.2.23 address 192.0.2.23
@ -125,7 +128,7 @@ EXAMPLES = r"""
- name: insert/update HTML surrounded by custom markers after <body> line - name: insert/update HTML surrounded by custom markers after <body> line
blockinfile: blockinfile:
dest: /var/www/html/index.html path: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->" marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
insertafter: "<body>" insertafter: "<body>"
content: | content: |
@ -134,13 +137,13 @@ EXAMPLES = r"""
- name: remove HTML as well as surrounding markers - name: remove HTML as well as surrounding markers
blockinfile: blockinfile:
dest: /var/www/html/index.html path: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->" marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
content: "" content: ""
- name: Add mappings to /etc/hosts - name: Add mappings to /etc/hosts
blockinfile: blockinfile:
dest: /etc/hosts path: /etc/hosts
block: | block: |
{{ item.ip }} {{ item.name }} {{ item.ip }} {{ item.name }}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}" marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
@ -157,7 +160,7 @@ from ansible.module_utils.six import b
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes
def write_changes(module, contents, dest): def write_changes(module, contents, path):
tmpfd, tmpfile = tempfile.mkstemp() tmpfd, tmpfile = tempfile.mkstemp()
f = os.fdopen(tmpfd, 'wb') f = os.fdopen(tmpfd, 'wb')
@ -175,7 +178,7 @@ def write_changes(module, contents, dest):
module.fail_json(msg='failed to validate: ' module.fail_json(msg='failed to validate: '
'rc:%s error:%s' % (rc, err)) 'rc:%s error:%s' % (rc, err))
if valid: if valid:
module.atomic_move(tmpfile, dest, unsafe_writes=module.params['unsafe_writes']) module.atomic_move(tmpfile, path, unsafe_writes=module.params['unsafe_writes'])
def check_file_attrs(module, changed, message): def check_file_attrs(module, changed, message):
@ -194,7 +197,7 @@ def check_file_attrs(module, changed, message):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
dest=dict(required=True, aliases=['name', 'destfile'], type='path'), path=dict(required=True, aliases=['dest', 'destfile', 'name'], type='path'),
state=dict(default='present', choices=['absent', 'present']), state=dict(default='present', choices=['absent', 'present']),
marker=dict(default='# {mark} ANSIBLE MANAGED BLOCK', type='str'), marker=dict(default='# {mark} ANSIBLE MANAGED BLOCK', type='str'),
block=dict(default='', type='str', aliases=['content']), block=dict(default='', type='str', aliases=['content']),
@ -210,23 +213,23 @@ def main():
) )
params = module.params params = module.params
dest = params['dest'] path = params['path']
if module.boolean(params.get('follow', None)): if module.boolean(params.get('follow', None)):
dest = os.path.realpath(dest) path = os.path.realpath(path)
if os.path.isdir(dest): if os.path.isdir(path):
module.fail_json(rc=256, module.fail_json(rc=256,
msg='Destination %s is a directory !' % dest) msg='Path %s is a directory !' % path)
path_exists = os.path.exists(dest) path_exists = os.path.exists(path)
if not path_exists: if not path_exists:
if not module.boolean(params['create']): if not module.boolean(params['create']):
module.fail_json(rc=257, module.fail_json(rc=257,
msg='Destination %s does not exist !' % dest) msg='Path %s does not exist !' % path)
original = None original = None
lines = [] lines = []
else: else:
f = open(dest, 'rb') f = open(path, 'rb')
original = f.read() original = f.read()
f.close() f.close()
lines = original.splitlines() lines = original.splitlines()
@ -238,7 +241,7 @@ def main():
present = params['state'] == 'present' present = params['state'] == 'present'
if not present and not path_exists: if not present and not path_exists:
module.exit_json(changed=False, msg="File not present") module.exit_json(changed=False, msg="File %s not present" % path)
if insertbefore is None and insertafter is None: if insertbefore is None and insertafter is None:
insertafter = 'EOF' insertafter = 'EOF'
@ -310,8 +313,8 @@ def main():
if changed and not module.check_mode: if changed and not module.check_mode:
if module.boolean(params['backup']) and path_exists: if module.boolean(params['backup']) and path_exists:
module.backup_local(dest) module.backup_local(path)
write_changes(module, result, dest) write_changes(module, result, path)
if module.check_mode and not path_exists: if module.check_mode and not path_exists:
module.exit_json(changed=changed, msg=msg) module.exit_json(changed=changed, msg=msg)

View file

@ -36,11 +36,13 @@ description:
- Before version 2.0, comments are discarded when the source file is read, and therefore will not show up in the destination file. - Before version 2.0, comments are discarded when the source file is read, and therefore will not show up in the destination file.
version_added: "0.9" version_added: "0.9"
options: options:
dest: path:
description: description:
- Path to the INI-style file; this file is created if required - Path to the INI-style file; this file is created if required.
- Before 2.3 this option was only usable as I(dest).
required: true required: true
default: null default: null
aliases: ['dest']
section: section:
description: description:
- Section name in INI file. This is added if C(state=present) automatically when - Section name in INI file. This is added if C(state=present) automatically when
@ -94,15 +96,18 @@ options:
notes: notes:
- While it is possible to add an I(option) without specifying a I(value), this makes - While it is possible to add an I(option) without specifying a I(value), this makes
no sense. no sense.
- As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but
I(dest) still works as well.
author: author:
- "Jan-Piet Mens (@jpmens)" - "Jan-Piet Mens (@jpmens)"
- "Ales Nosek (@noseka1)" - "Ales Nosek (@noseka1)"
''' '''
EXAMPLES = ''' EXAMPLES = '''
# Ensure "fav=lemonade is in section "[drinks]" in specified file # Before 2.3, option 'dest' was used instead of 'path'
- ini_file: - name: Ensure "fav=lemonade is in section "[drinks]" in specified file
dest: /etc/conf ini_file:
path: /etc/conf
section: drinks section: drinks
option: fav option: fav
value: lemonade value: lemonade
@ -110,7 +115,7 @@ EXAMPLES = '''
backup: yes backup: yes
- ini_file: - ini_file:
dest: /etc/anotherconf path: /etc/anotherconf
section: drinks section: drinks
option: temperature option: temperature
value: cold value: cold
@ -120,6 +125,9 @@ EXAMPLES = '''
import os import os
import re import re
# import module snippets
from ansible.module_utils.basic import AnsibleModule
# ============================================================== # ==============================================================
# match_opt # match_opt
@ -258,7 +266,7 @@ def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec = dict(
dest = dict(required=True), path = dict(required=True, aliases=['dest'], type='path'),
section = dict(required=True), section = dict(required=True),
option = dict(required=False), option = dict(required=False),
value = dict(required=False), value = dict(required=False),
@ -271,7 +279,7 @@ def main():
supports_check_mode = True supports_check_mode = True
) )
dest = os.path.expanduser(module.params['dest']) path = os.path.expanduser(module.params['path'])
section = module.params['section'] section = module.params['section']
option = module.params['option'] option = module.params['option']
value = module.params['value'] value = module.params['value']
@ -280,20 +288,18 @@ def main():
no_extra_spaces = module.params['no_extra_spaces'] no_extra_spaces = module.params['no_extra_spaces']
create = module.params['create'] create = module.params['create']
(changed,backup_file,diff,msg) = do_ini(module, dest, section, option, value, state, backup, no_extra_spaces, create) (changed,backup_file,diff,msg) = do_ini(module, path, section, option, value, state, backup, no_extra_spaces, create)
if not module.check_mode and os.path.exists(dest): if not module.check_mode and os.path.exists(path):
file_args = module.load_file_common_arguments(module.params) file_args = module.load_file_common_arguments(module.params)
changed = module.set_fs_attributes_if_different(file_args, changed) changed = module.set_fs_attributes_if_different(file_args, changed)
results = { 'changed': changed, 'msg': msg, 'dest': dest, 'diff': diff } results = { 'changed': changed, 'msg': msg, 'path': path, 'diff': diff }
if backup_file is not None: if backup_file is not None:
results['backup_file'] = backup_file results['backup_file'] = backup_file
# Mission complete # Mission complete
module.exit_json(**results) module.exit_json(**results)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -42,11 +42,12 @@ description:
For other cases, see the M(copy) or M(template) modules. For other cases, see the M(copy) or M(template) modules.
version_added: "0.7" version_added: "0.7"
options: options:
dest: path:
required: true required: true
aliases: [ name, destfile ] aliases: [ 'dest', 'destfile', 'name' ]
description: description:
- The file to modify. - The file to modify.
- Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).
regexp: regexp:
required: false required: false
version_added: 1.7 version_added: 1.7
@ -121,21 +122,24 @@ options:
description: description:
- All arguments accepted by the M(file) module also work here. - All arguments accepted by the M(file) module also work here.
required: false required: false
notes:
- As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well.
""" """
EXAMPLES = r""" EXAMPLES = r"""
# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- lineinfile: - lineinfile:
dest: /etc/selinux/config path: /etc/selinux/config
regexp: '^SELINUX=' regexp: '^SELINUX='
line: 'SELINUX=enforcing' line: 'SELINUX=enforcing'
- lineinfile: - lineinfile:
dest: /etc/sudoers path: /etc/sudoers
state: absent state: absent
regexp: '^%wheel' regexp: '^%wheel'
- lineinfile: - lineinfile:
dest: /etc/hosts path: /etc/hosts
regexp: '^127\.0\.0\.1' regexp: '^127\.0\.0\.1'
line: '127.0.0.1 localhost' line: '127.0.0.1 localhost'
owner: root owner: root
@ -143,39 +147,39 @@ EXAMPLES = r"""
mode: 0644 mode: 0644
- lineinfile: - lineinfile:
dest: /etc/httpd/conf/httpd.conf path: /etc/httpd/conf/httpd.conf
regexp: '^Listen ' regexp: '^Listen '
insertafter: '^#Listen ' insertafter: '^#Listen '
line: 'Listen 8080' line: 'Listen 8080'
- lineinfile: - lineinfile:
dest: /etc/services path: /etc/services
regexp: '^# port for http' regexp: '^# port for http'
insertbefore: '^www.*80/tcp' insertbefore: '^www.*80/tcp'
line: '# port for http by default' line: '# port for http by default'
# Add a line to a file if it does not exist, without passing regexp # Add a line to a file if it does not exist, without passing regexp
- lineinfile: - lineinfile:
dest: /tmp/testfile path: /tmp/testfile
line: '192.168.1.99 foo.lab.net foo' line: '192.168.1.99 foo.lab.net foo'
# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs. # Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- lineinfile: - lineinfile: "
dest: /etc/sudoers path: /etc/sudoers
state: present state: present
regexp: '^%wheel\s' regexp: '^%wheel\s'
line: '%wheel ALL=(ALL) NOPASSWD: ALL' line: '%wheel ALL=(ALL) NOPASSWD: ALL'
# Yaml requires escaping backslashes in double quotes but not in single quotes # Yaml requires escaping backslashes in double quotes but not in single quotes
- lineinfile: - lineinfile:
dest: /opt/jboss-as/bin/standalone.conf path: /opt/jboss-as/bin/standalone.conf
regexp: "^(.*)Xms(\\d+)m(.*)$" regexp: '^(.*)Xms(\\d+)m(.*)$'
line: '\1Xms${xms}m\3' line: '\1Xms${xms}m\3'
backrefs: yes backrefs: yes
# Validate the sudoers file before saving # Validate the sudoers file before saving
- lineinfile: - lineinfile:
dest: /etc/sudoers path: /etc/sudoers
state: present state: present
regexp: '^%ADMIN ALL=' regexp: '^%ADMIN ALL='
line: '%ADMIN ALL=(ALL) NOPASSWD: ALL' line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
@ -412,7 +416,7 @@ def absent(module, dest, regexp, line, backup):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
dest=dict(required=True, aliases=['name', 'destfile'], type='path'), path=dict(required=True, aliases=['dest', 'destfile', 'name'], type='path'),
state=dict(default='present', choices=['absent', 'present']), state=dict(default='present', choices=['absent', 'present']),
regexp=dict(default=None), regexp=dict(default=None),
line=dict(aliases=['value']), line=dict(aliases=['value']),
@ -432,11 +436,11 @@ def main():
create = params['create'] create = params['create']
backup = params['backup'] backup = params['backup']
backrefs = params['backrefs'] backrefs = params['backrefs']
dest = params['dest'] path = params['path']
b_dest = to_bytes(dest, errors='surrogate_or_strict') b_path = to_bytes(path, errors='surrogate_or_strict')
if os.path.isdir(b_dest): if os.path.isdir(b_path):
module.fail_json(rc=256, msg='Destination %s is a directory !' % dest) module.fail_json(rc=256, msg='Path %s is a directory !' % path)
if params['state'] == 'present': if params['state'] == 'present':
if backrefs and params['regexp'] is None: if backrefs and params['regexp'] is None:
@ -453,13 +457,13 @@ def main():
line = params['line'] line = params['line']
present(module, dest, params['regexp'], line, present(module, path, params['regexp'], line,
ins_aft, ins_bef, create, backup, backrefs) ins_aft, ins_bef, create, backup, backrefs)
else: else:
if params['regexp'] is None and params.get('line', None) is None: 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') module.fail_json(msg='one of line= or regexp= is required with state=absent')
absent(module, dest, params['regexp'], params.get('line', None), backup) absent(module, path, params['regexp'], params.get('line', None), backup)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -43,11 +43,12 @@ description:
same pattern would never match any replacements made. same pattern would never match any replacements made.
version_added: "1.6" version_added: "1.6"
options: options:
dest: path:
required: true required: true
aliases: [ name, destfile ] aliases: [ dest, destfile, name ]
description: description:
- The file to modify. - The file to modify.
- Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).
regexp: regexp:
required: true required: true
description: description:
@ -80,30 +81,38 @@ options:
version_added: "1.9" version_added: "1.9"
description: description:
- 'This flag indicates that filesystem links, if they exist, should be followed.' - 'This flag indicates that filesystem links, if they exist, should be followed.'
notes:
- As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well.
""" """
EXAMPLES = r""" EXAMPLES = r"""
# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- replace: - replace:
dest: /etc/hosts path: /etc/hosts
regexp: '(\s+)old\.host\.name(\s+.*)?$' regexp: '(\s+)old\.host\.name(\s+.*)?$'
replace: '\1new.host.name\2' replace: '\1new.host.name\2'
backup: yes backup: yes
- replace: - replace:
dest: /home/jdoe/.ssh/known_hosts path: /home/jdoe/.ssh/known_hosts
regexp: '^old\.host\.name[^\n]*\n' regexp: '^old\.host\.name[^\n]*\n'
owner: jdoe owner: jdoe
group: jdoe group: jdoe
mode: 0644 mode: 0644
- replace: - replace:
dest: /etc/apache/ports path: /etc/apache/ports
regexp: '^(NameVirtualHost|Listen)\s+80\s*$' regexp: '^(NameVirtualHost|Listen)\s+80\s*$'
replace: '\1 127.0.0.1:8080' replace: '\1 127.0.0.1:8080'
validate: '/usr/sbin/apache2ctl -f %s -t' validate: '/usr/sbin/apache2ctl -f %s -t'
""" """
def write_changes(module,contents,dest): import os
# import module snippets
from ansible.module_utils.basic import AnsibleModule
def write_changes(module, contents, path):
tmpfd, tmpfile = tempfile.mkstemp() tmpfd, tmpfile = tempfile.mkstemp()
f = os.fdopen(tmpfd,'wb') f = os.fdopen(tmpfd,'wb')
@ -121,7 +130,7 @@ def write_changes(module,contents,dest):
module.fail_json(msg='failed to validate: ' module.fail_json(msg='failed to validate: '
'rc:%s error:%s' % (rc,err)) 'rc:%s error:%s' % (rc,err))
if valid: if valid:
module.atomic_move(tmpfile, dest, unsafe_writes=module.params['unsafe_writes']) module.atomic_move(tmpfile, path, unsafe_writes=module.params['unsafe_writes'])
def check_file_attrs(module, changed, message): def check_file_attrs(module, changed, message):
@ -138,7 +147,7 @@ def check_file_attrs(module, changed, message):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
dest=dict(required=True, aliases=['name', 'destfile']), path=dict(required=True, aliases=['dest', 'destfile', 'name'], type='path'),
regexp=dict(required=True), regexp=dict(required=True),
replace=dict(default='', type='str'), replace=dict(default='', type='str'),
backup=dict(default=False, type='bool'), backup=dict(default=False, type='bool'),
@ -149,16 +158,16 @@ def main():
) )
params = module.params params = module.params
dest = os.path.expanduser(params['dest']) path = os.path.expanduser(params['path'])
res_args = dict() res_args = dict()
if os.path.isdir(dest): if os.path.isdir(path):
module.fail_json(rc=256, msg='Destination %s is a directory !' % dest) module.fail_json(rc=256, msg='Path %s is a directory !' % path)
if not os.path.exists(dest): if not os.path.exists(path):
module.fail_json(rc=257, msg='Destination %s does not exist !' % dest) module.fail_json(rc=257, msg='Path %s does not exist !' % path)
else: else:
f = open(dest, 'rb') f = open(path, 'rb')
contents = to_text(f.read(), errors='surrogate_or_strict') contents = to_text(f.read(), errors='surrogate_or_strict')
f.close() f.close()
@ -170,9 +179,9 @@ def main():
changed = True changed = True
if module._diff: if module._diff:
res_args['diff'] = { res_args['diff'] = {
'before_header': dest, 'before_header': path,
'before': contents, 'before': contents,
'after_header': dest, 'after_header': path,
'after': result[0], 'after': result[0],
} }
else: else:
@ -180,17 +189,14 @@ def main():
changed = False changed = False
if changed and not module.check_mode: if changed and not module.check_mode:
if params['backup'] and os.path.exists(dest): if params['backup'] and os.path.exists(path):
res_args['backup_file'] = module.backup_local(dest) res_args['backup_file'] = module.backup_local(path)
if params['follow'] and os.path.islink(dest): if params['follow'] and os.path.islink(path):
dest = os.path.realpath(dest) path = os.path.realpath(path)
write_changes(module, result[0], dest) write_changes(module, result[0], path)
res_args['msg'], res_args['changed'] = check_file_attrs(module, changed, msg) res_args['msg'], res_args['changed'] = check_file_attrs(module, changed, msg)
module.exit_json(**res_args) module.exit_json(**res_args)
# this is magic, see lib/ansible/module_common.py
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -27,12 +27,13 @@ description:
- Manages filesystem user defined extended attributes, requires that they are enabled - Manages filesystem user defined extended attributes, requires that they are enabled
on the target filesystem and that the setfattr/getfattr utilities are present. on the target filesystem and that the setfattr/getfattr utilities are present.
options: options:
name: path:
required: true required: true
default: None default: None
aliases: ['path'] aliases: ['name']
description: description:
- The full path of the file/object to get the facts of - The full path of the file/object to get the facts of.
- Before 2.3 this option was only usable as I(name).
key: key:
required: false required: false
default: None default: None
@ -61,6 +62,8 @@ options:
description: description:
- if yes, dereferences symlinks and sets/gets attributes on symlink target, - if yes, dereferences symlinks and sets/gets attributes on symlink target,
otherwise acts on symlink itself. otherwise acts on symlink itself.
notes:
- As of Ansible 2.3, the I(name) option has been changed to I(path) as default, but I(name) still works as well.
author: "Brian Coca (@bcoca)" author: "Brian Coca (@bcoca)"
''' '''
@ -68,7 +71,7 @@ author: "Brian Coca (@bcoca)"
EXAMPLES = ''' EXAMPLES = '''
# Obtain the extended attributes of /etc/foo.conf # Obtain the extended attributes of /etc/foo.conf
- xattr: - xattr:
name: /etc/foo.conf path: /etc/foo.conf
# Sets the key 'foo' to value 'bar' # Sets the key 'foo' to value 'bar'
- xattr: - xattr:
@ -78,7 +81,7 @@ EXAMPLES = '''
# Removes the key 'foo' # Removes the key 'foo'
- xattr: - xattr:
name: /etc/foo.conf path: /etc/foo.conf
key: user.foo key: user.foo
state: absent state: absent
''' '''
@ -87,6 +90,10 @@ import operator
import re import re
import os import os
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
def get_xattr_keys(module,path,follow): def get_xattr_keys(module,path,follow):
cmd = [ module.get_bin_path('getfattr', True) ] cmd = [ module.get_bin_path('getfattr', True) ]
# prevents warning and not sure why it's not default # prevents warning and not sure why it's not default
@ -156,7 +163,7 @@ def _run_xattr(module,cmd,check_rc=True):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec = dict(
name = dict(required=True, aliases=['path'], type='path'), path = dict(required=True, aliases=['name'], type='path'),
key = dict(required=False, default=None, type='str'), key = dict(required=False, default=None, type='str'),
value = dict(required=False, default=None, type='str'), value = dict(required=False, default=None, type='str'),
state = dict(required=False, default='read', choices=[ 'read', 'present', 'all', 'keys', 'absent' ], type='str'), state = dict(required=False, default='read', choices=[ 'read', 'present', 'all', 'keys', 'absent' ], type='str'),
@ -164,7 +171,7 @@ def main():
), ),
supports_check_mode=True, supports_check_mode=True,
) )
path = module.params.get('name') path = module.params.get('path')
key = module.params.get('key') key = module.params.get('key')
value = module.params.get('value') value = module.params.get('value')
state = module.params.get('state') state = module.params.get('state')
@ -214,8 +221,5 @@ def main():
module.exit_json(changed=changed, msg=msg, xattr=res) module.exit_json(changed=changed, msg=msg, xattr=res)
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -20,16 +20,6 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import get_platform
from ansible.module_utils.ismount import ismount
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.six import iteritems
import os
ANSIBLE_METADATA = {'status': ['preview'], ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'core', 'supported_by': 'core',
'version': '1.0'} 'version': '1.0'}
@ -45,13 +35,15 @@ author:
- Seth Vidal - Seth Vidal
version_added: "0.6" version_added: "0.6"
options: options:
name: path:
description: description:
- Path to the mount point (e.g. C(/mnt/files)) - Path to the mount point (e.g. C(/mnt/files)).
- Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).
required: true required: true
aliases: [ name ]
src: src:
description: description:
- Device to be mounted on I(name). Required when I(state) set to - Device to be mounted on I(path). Required when I(state) set to
C(present) or C(mounted). C(present) or C(mounted).
required: false required: false
default: null default: null
@ -109,12 +101,15 @@ options:
required: false required: false
default: yes default: yes
choices: ["yes", "no"] choices: ["yes", "no"]
notes:
- As of Ansible 2.3, the I(name) option has been changed to I(path) as default, but I(name) still works as well.
''' '''
EXAMPLES = ''' EXAMPLES = '''
# Before 2.3, option 'name' was used instead of 'path'
- name: Mount DVD read-only - name: Mount DVD read-only
mount: mount:
name: /mnt/dvd path: /mnt/dvd
src: /dev/sr0 src: /dev/sr0
fstype: iso9660 fstype: iso9660
opts: ro opts: ro
@ -122,23 +117,31 @@ EXAMPLES = '''
- name: Mount up device by label - name: Mount up device by label
mount: mount:
name: /srv/disk path: /srv/disk
src: LABEL=SOME_LABEL src: LABEL=SOME_LABEL
fstype: ext4 fstype: ext4
state: present state: present
- name: Mount up device by UUID - name: Mount up device by UUID
mount: mount:
name: /home path: /home
src: UUID=b3e48f45-f933-4c8e-a700-22a159ec9077 src: UUID=b3e48f45-f933-4c8e-a700-22a159ec9077
fstype: xfs fstype: xfs
opts: noatime opts: noatime
state: present state: present
''' '''
import os
def write_fstab(lines, dest): # import module snippets
fs_w = open(dest, 'w') from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule, get_platform
from ansible.module_utils.ismount import ismount
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.six import iteritems
def write_fstab(lines, path):
fs_w = open(path, 'w')
for l in lines: for l in lines:
fs_w.write(l) fs_w.write(l)
@ -352,11 +355,11 @@ def mount(module, args):
return rc, out+err return rc, out+err
def umount(module, dest): def umount(module, path):
"""Unmount a path.""" """Unmount a path."""
umount_bin = module.get_bin_path('umount', required=True) umount_bin = module.get_bin_path('umount', required=True)
cmd = [umount_bin, dest] cmd = [umount_bin, path]
rc, out, err = module.run_command(cmd) rc, out, err = module.run_command(cmd)
@ -584,7 +587,7 @@ def main():
dump=dict(), dump=dict(),
fstab=dict(default=None), fstab=dict(default=None),
fstype=dict(), fstype=dict(),
name=dict(required=True, type='path'), path=dict(required=True, aliases=['name'], type='path'),
opts=dict(), opts=dict(),
passno=dict(type='str'), passno=dict(type='str'),
src=dict(type='path'), src=dict(type='path'),
@ -608,7 +611,7 @@ def main():
# explicitly specified it in mount() and remount() # explicitly specified it in mount() and remount()
if get_platform().lower() == 'sunos': if get_platform().lower() == 'sunos':
args = dict( args = dict(
name=module.params['name'], name=module.params['path'],
opts='-', opts='-',
passno='-', passno='-',
fstab=module.params['fstab'], fstab=module.params['fstab'],
@ -618,7 +621,7 @@ def main():
args['fstab'] = '/etc/vfstab' args['fstab'] = '/etc/vfstab'
else: else:
args = dict( args = dict(
name=module.params['name'], name=module.params['path'],
opts='defaults', opts='defaults',
dump='0', dump='0',
passno='0', passno='0',
@ -667,7 +670,7 @@ def main():
# changed in fstab then remount it. # changed in fstab then remount it.
state = module.params['state'] state = module.params['state']
name = module.params['name'] name = module.params['path']
if state == 'absent': if state == 'absent':
name, changed = unset_mount(module, args) name, changed = unset_mount(module, args)
@ -735,6 +738,5 @@ def main():
module.exit_json(changed=changed, **args) module.exit_json(changed=changed, **args)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -25,7 +25,7 @@ $params = Parse-Args $args;
# Initialize defaults for input parameters. # Initialize defaults for input parameters.
$dest= Get-Attr $params "dest" $FALSE; $path= Get-Attr $params "path" $FALSE;
$regexp = Get-Attr $params "regexp" $FALSE; $regexp = Get-Attr $params "regexp" $FALSE;
$state = Get-Attr $params "state" "present"; $state = Get-Attr $params "state" "present";
$line = Get-Attr $params "line" $FALSE; $line = Get-Attr $params "line" $FALSE;
@ -39,32 +39,34 @@ $encoding = Get-Attr $params "encoding" "auto";
$newline = Get-Attr $params "newline" "windows"; $newline = Get-Attr $params "newline" "windows";
# Parse dest / name /destfile param aliases for compatibility with lineinfile # Parse path / dest / destfile / name param aliases for compatibility with lineinfile
# and fail if at least one spelling of the parameter is not provided. # and fail if at least one spelling of the parameter is not provided.
$dest = Get-Attr $params "dest" $FALSE; If ($path -eq $FALSE) {
If ($dest -eq $FALSE) { $path = Get-Attr $params "dest" $FALSE;
$dest = Get-Attr $params "name" $FALSE; If ($path -eq $FALSE) {
If ($dest -eq $FALSE) { $path = Get-Attr $params "destfile" $FALSE;
$dest = Get-Attr $params "destfile" $FALSE; If ($path -eq $FALSE) {
If ($dest -eq $FALSE) { $path = Get-Attr $params "name" $FALSE;
Fail-Json (New-Object psobject) "missing required argument: dest"; If ($path -eq $FALSE) {
Fail-Json (New-Object psobject) "missing required argument: path";
}
} }
} }
} }
# Fail if the destination is not a file # Fail if the path is not a file
If (Test-Path $dest -pathType container) { If (Test-Path $path -pathType container) {
Fail-Json (New-Object psobject) "destination is a directory"; Fail-Json (New-Object psobject) "Path $path is a directory";
} }
# Write lines to a file using the specified line separator and encoding, # Write lines to a file using the specified line separator and encoding,
# performing validation if a validation command was specified. # performing validation if a validation command was specified.
function WriteLines($outlines, $dest, $linesep, $encodingobj, $validate) { function WriteLines($outlines, $path, $linesep, $encodingobj, $validate) {
$temppath = [System.IO.Path]::GetTempFileName(); $temppath = [System.IO.Path]::GetTempFileName();
$joined = $outlines -join $linesep; $joined = $outlines -join $linesep;
[System.IO.File]::WriteAllText($temppath, $joined, $encodingobj); [System.IO.File]::WriteAllText($temppath, $joined, $encodingobj);
@ -94,9 +96,9 @@ function WriteLines($outlines, $dest, $linesep, $encodingobj, $validate) {
} }
# Commit changes to the destination file # Commit changes to the path
$cleandest = $dest.Replace("/", "\"); $cleanpath = $path.Replace("/", "\");
Copy-Item $temppath $cleandest -force; Copy-Item $temppath $cleanpath -force;
Remove-Item $temppath -force; Remove-Item $temppath -force;
} }
@ -113,24 +115,24 @@ function BackupFile($path) {
# Implement the functionality for state == 'present' # Implement the functionality for state == 'present'
function Present($dest, $regexp, $line, $insertafter, $insertbefore, $create, $backup, $backrefs, $validate, $encodingobj, $linesep) { function Present($path, $regexp, $line, $insertafter, $insertbefore, $create, $backup, $backrefs, $validate, $encodingobj, $linesep) {
# Note that we have to clean up the dest path because ansible wants to treat / and \ as # Note that we have to clean up the path because ansible wants to treat / and \ as
# interchangeable in windows pathnames, but .NET framework internals do not support that. # interchangeable in windows pathnames, but .NET framework internals do not support that.
$cleandest = $dest.Replace("/", "\"); $cleanpath = $path.Replace("/", "\");
# Check if destination exists. If it does not exist, either create it if create == "yes" # Check if path exists. If it does not exist, either create it if create == "yes"
# was specified or fail with a reasonable error message. # was specified or fail with a reasonable error message.
If (!(Test-Path $dest)) { If (!(Test-Path $path)) {
If ($create -eq "no") { If ($create -eq "no") {
Fail-Json (New-Object psobject) "Destination $dest does not exist !"; Fail-Json (New-Object psobject) "Path $path does not exist !";
} }
# Create new empty file, using the specified encoding to write correct BOM # Create new empty file, using the specified encoding to write correct BOM
[System.IO.File]::WriteAllLines($cleandest, "", $encodingobj); [System.IO.File]::WriteAllLines($cleanpath, "", $encodingobj);
} }
# Read the dest file lines using the indicated encoding into a mutable ArrayList. # Read the dest file lines using the indicated encoding into a mutable ArrayList.
$content = [System.IO.File]::ReadAllLines($cleandest, $encodingobj); $content = [System.IO.File]::ReadAllLines($cleanpath, $encodingobj);
If ($content -eq $null) { If ($content -eq $null) {
$lines = New-Object System.Collections.ArrayList; $lines = New-Object System.Collections.ArrayList;
} }
@ -225,15 +227,15 @@ function Present($dest, $regexp, $line, $insertafter, $insertbefore, $create, $b
} }
# Write backup file if backup == "yes" # Write backup file if backup == "yes"
$backupdest = ""; $backuppath = "";
If ($changed -eq $TRUE -and $backup -eq "yes") { If ($changed -eq $TRUE -and $backup -eq "yes") {
$backupdest = BackupFile $dest; $backuppath = BackupFile $path;
} }
# Write changes to the destination file if changes were made # Write changes to the path if changes were made
If ($changed) { If ($changed) {
WriteLines $lines $dest $linesep $encodingobj $validate; WriteLines $lines $path $linesep $encodingobj $validate;
} }
$encodingstr = $encodingobj.WebName; $encodingstr = $encodingobj.WebName;
@ -242,7 +244,7 @@ function Present($dest, $regexp, $line, $insertafter, $insertbefore, $create, $b
$result = New-Object psobject @{ $result = New-Object psobject @{
changed = $changed changed = $changed
msg = $msg msg = $msg
backup = $backupdest backup = $backuppath
encoding = $encodingstr encoding = $encodingstr
} }
@ -252,19 +254,19 @@ function Present($dest, $regexp, $line, $insertafter, $insertbefore, $create, $b
# Implement the functionality for state == 'absent' # Implement the functionality for state == 'absent'
function Absent($dest, $regexp, $line, $backup, $validate, $encodingobj, $linesep) { function Absent($path, $regexp, $line, $backup, $validate, $encodingobj, $linesep) {
# Check if destination exists. If it does not exist, fail with a reasonable error message. # Check if path exists. If it does not exist, fail with a reasonable error message.
If (!(Test-Path $dest)) { If (!(Test-Path $path)) {
Fail-Json (New-Object psobject) "Destination $dest does not exist !"; Fail-Json (New-Object psobject) "Path $path does not exist !";
} }
# Read the dest file lines using the indicated encoding into a mutable ArrayList. Note # Read the dest file lines using the indicated encoding into a mutable ArrayList. Note
# that we have to clean up the dest path because ansible wants to treat / and \ as # that we have to clean up the path because ansible wants to treat / and \ as
# interchangeable in windows pathnames, but .NET framework internals do not support that. # interchangeable in windows pathnames, but .NET framework internals do not support that.
$cleandest = $dest.Replace("/", "\"); $cleanpath = $path.Replace("/", "\");
$content = [System.IO.File]::ReadAllLines($cleandest, $encodingobj); $content = [System.IO.File]::ReadAllLines($cleanpath, $encodingobj);
If ($content -eq $null) { If ($content -eq $null) {
$lines = New-Object System.Collections.ArrayList; $lines = New-Object System.Collections.ArrayList;
} }
@ -303,15 +305,15 @@ function Absent($dest, $regexp, $line, $backup, $validate, $encodingobj, $linese
} }
# Write backup file if backup == "yes" # Write backup file if backup == "yes"
$backupdest = ""; $backuppath = "";
If ($changed -eq $TRUE -and $backup -eq "yes") { If ($changed -eq $TRUE -and $backup -eq "yes") {
$backupdest = BackupFile $dest; $backuppath = BackupFile $path;
} }
# Write changes to the destination file if changes were made # Write changes to the path if changes were made
If ($changed) { If ($changed) {
WriteLines $left $dest $linesep $encodingobj $validate; WriteLines $left $path $linesep $encodingobj $validate;
} }
# Return result information # Return result information
@ -322,7 +324,7 @@ function Absent($dest, $regexp, $line, $backup, $validate, $encodingobj, $linese
$result = New-Object psobject @{ $result = New-Object psobject @{
changed = $changed changed = $changed
msg = $msg msg = $msg
backup = $backupdest backup = $backuppath
found = $fcount found = $fcount
encoding = $encodingstr encoding = $encodingstr
} }
@ -362,7 +364,7 @@ If ($encoding -ne "auto") {
# Otherwise see if we can determine the current encoding of the target file. # Otherwise see if we can determine the current encoding of the target file.
# If the file doesn't exist yet (create == 'yes') we use the default or # If the file doesn't exist yet (create == 'yes') we use the default or
# explicitly specified encoding set above. # explicitly specified encoding set above.
Elseif (Test-Path $dest) { Elseif (Test-Path $path) {
# Get a sorted list of encodings with preambles, longest first # Get a sorted list of encodings with preambles, longest first
@ -381,7 +383,7 @@ Elseif (Test-Path $dest) {
# Get the first N bytes from the file, where N is the max preamble length we saw # Get the first N bytes from the file, where N is the max preamble length we saw
[Byte[]]$bom = Get-Content -Encoding Byte -ReadCount $max_preamble_len -TotalCount $max_preamble_len -Path $dest; [Byte[]]$bom = Get-Content -Encoding Byte -ReadCount $max_preamble_len -TotalCount $max_preamble_len -Path $path;
# Iterate through the sorted encodings, looking for a full match. # Iterate through the sorted encodings, looking for a full match.
@ -426,7 +428,7 @@ If ($state -eq "present") {
$insertafter = "EOF"; $insertafter = "EOF";
} }
Present $dest $regexp $line $insertafter $insertbefore $create $backup $backrefs $validate $encodingobj $linesep; Present $path $regexp $line $insertafter $insertbefore $create $backup $backrefs $validate $encodingobj $linesep;
} }
Else { Else {
@ -435,22 +437,5 @@ Else {
Fail-Json (New-Object psobject) "one of line= or regexp= is required with state=absent"; Fail-Json (New-Object psobject) "one of line= or regexp= is required with state=absent";
} }
Absent $dest $regexp $line $backup $validate $encodingobj $linesep; Absent $path $regexp $line $backup $validate $encodingobj $linesep;
} }

View file

@ -30,12 +30,13 @@ description:
- This is primarily useful when you want to change a single line in a file only. - This is primarily useful when you want to change a single line in a file only.
version_added: "2.0" version_added: "2.0"
options: options:
dest: path:
required: true required: true
aliases: [ name, destfile ] aliases: [ dest, destfile, name ]
description: description:
- The path of the file to modify. - The path of the file to modify.
- Note that the Windows path delimiter C(\) must be escaped as C(\\) when the line is double quoted. - Note that the Windows path delimiter C(\) must be escaped as C(\\) when the line is double quoted.
- Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).
regexp: regexp:
required: false required: false
description: description:
@ -101,46 +102,49 @@ options:
- "Specifies the line separator style to use for the modified file. This defaults to the windows line separator (C(\r\n)). Note that the indicated line separator will be used for file output regardless of the original line separator that appears in the input file." - "Specifies the line separator style to use for the modified file. This defaults to the windows line separator (C(\r\n)). Note that the indicated line separator will be used for file output regardless of the original line separator that appears in the input file."
choices: [ "windows", "unix" ] choices: [ "windows", "unix" ]
default: "windows" default: "windows"
notes:
- As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well.
""" """
EXAMPLES = r""" EXAMPLES = r"""
# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- win_lineinfile: - win_lineinfile:
dest: C:\temp\example.conf path: C:\temp\example.conf
regexp: '^name=' regexp: '^name='
line: 'name=JohnDoe' line: 'name=JohnDoe'
- win_lineinfile: - win_lineinfile:
dest: C:\temp\example.conf path: C:\temp\example.conf
regexp: '^name=' regexp: '^name='
state: absent state: absent
- win_lineinfile: - win_lineinfile:
dest: C:\temp\example.conf path: C:\temp\example.conf
regexp: '^127\.0\.0\.1' regexp: '^127\.0\.0\.1'
line: '127.0.0.1 localhost' line: '127.0.0.1 localhost'
- win_lineinfile: - win_lineinfile:
dest: C:\temp\httpd.conf path: C:\temp\httpd.conf
regexp: '^Listen ' regexp: '^Listen '
insertafter: '^#Listen ' insertafter: '^#Listen '
line: Listen 8080 line: Listen 8080
- win_lineinfile: - win_lineinfile:
dest: C:\temp\services path: C:\temp\services
regexp: '^# port for http' regexp: '^# port for http'
insertbefore: '^www.*80/tcp' insertbefore: '^www.*80/tcp'
line: '# port for http by default' line: '# port for http by default'
# Create file if it doesn't exist with a specific encoding # Create file if it doesn't exist with a specific encoding
- win_lineinfile: - win_lineinfile:
dest: C:\temp\utf16.txt path: C:\temp\utf16.txt
create: yes create: yes
encoding: utf-16 encoding: utf-16
line: This is a utf-16 encoded file line: This is a utf-16 encoded file
# Add a line to a file and ensure the resulting file uses unix line separators # Add a line to a file and ensure the resulting file uses unix line separators
- win_lineinfile: - win_lineinfile:
dest: C:\temp\testfile.txt path: C:\temp\testfile.txt
line: Line added to file line: Line added to file
newline: unix newline: unix
""" """