Ansible system module: sanity pep8 fixes (#32314)

* Ansible system module: pep8 fixes

* Clean up documentation

* Blank line change not required by PEP8

* Update legacy-files.txt

* Documentation updates

* Update documentation

* Documentation update
pull/32313/head
Yadnyawalkya Tale 7 years ago committed by Dag Wieers
parent 48ab1a1334
commit d21a6aa147

@ -7,18 +7,16 @@
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'], 'status': ['preview'],
'supported_by': 'community'} 'supported_by': 'community'}
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
author: "Joris Weijters (@molekuul)" author:
- Joris Weijters (@molekuul)
module: aix_inittab module: aix_inittab
short_description: Manages the inittab on AIX. short_description: Manages the inittab on AIX
description: description:
- Manages the inittab on AIX. - Manages the inittab on AIX.
version_added: "2.3" version_added: "2.3"
@ -26,47 +24,47 @@ options:
name: name:
description: description:
- Name of the inittab entry. - Name of the inittab entry.
required: True required: yes
aliases: ['service'] aliases: ['service']
runlevel: runlevel:
description: description:
- Runlevel of the entry. - Runlevel of the entry.
required: True required: yes
action: action:
description: description:
- Action what the init has to do with this entry. - Action what the init has to do with this entry.
required: True required: yes
choices: [ choices:
'respawn', - boot
'wait', - bootwait
'once', - hold
'boot', - initdefault
'bootwait', - off
'powerfail', - once
'powerwait', - ondemand
'off', - powerfail
'hold', - powerwait
'ondemand', - respawn
'initdefault', - sysinit
'sysinit' - wait
]
command: command:
description: description:
- What command has to run. - What command has to run.
required: True required: yes
insertafter: insertafter:
description: description:
- After which inittabline should the new entry inserted. - After which inittabline should the new entry inserted.
state: state:
description: description:
- Whether the entry should be present or absent in the inittab file - Whether the entry should be present or absent in the inittab file.
choices: [ "present", "absent" ] choices: [ absent, present ]
default: present default: present
notes: notes:
- The changes are persistent across reboots, you need root rights to read or adjust the inittab with the lsitab, chitab, - The changes are persistent across reboots, you need root rights to read or adjust the inittab with the C(lsitab), chitab,
mkitab or rmitab commands. C(mkitab) or C(rmitab) commands.
- tested on AIX 7.1. - Tested on AIX 7.1.
requirements: [ 'itertools'] requirements:
- itertools
''' '''
EXAMPLES = ''' EXAMPLES = '''
@ -76,7 +74,7 @@ EXAMPLES = '''
name: startmyservice name: startmyservice
runlevel: 4 runlevel: 4
action: once action: once
command: "echo hello" command: echo hello
insertafter: existingservice insertafter: existingservice
state: present state: present
become: yes become: yes
@ -87,17 +85,16 @@ EXAMPLES = '''
name: startmyservice name: startmyservice
runlevel: 2 runlevel: 2
action: wait action: wait
command: "echo hello" command: echo hello
state: present state: present
become: yes become: yes
# Remove inittab entry startmyservice. - name: Remove startmyservice from inittab
- name: remove startmyservice from inittab
aix_inittab: aix_inittab:
name: startmyservice name: startmyservice
runlevel: 2 runlevel: 2
action: wait action: wait
command: "echo hello" command: echo hello
state: absent state: absent
become: yes become: yes
''' '''
@ -148,28 +145,25 @@ def main():
# initialize # initialize
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
name=dict(required=True, type='str', aliases=['service']), name=dict(type='str', required=True, aliases=['service']),
runlevel=dict(required=True, type='str'), runlevel=dict(type='str', required=True),
action=dict(choices=[ action=dict(type='str', choices=[
'respawn',
'wait',
'once',
'boot', 'boot',
'bootwait', 'bootwait',
'powerfail',
'powerwait',
'off',
'hold', 'hold',
'ondemand',
'initdefault', 'initdefault',
'sysinit' 'off',
], type='str'), 'once',
command=dict(required=True, type='str'), 'ondemand',
'powerfail',
'powerwait',
'respawn',
'sysinit',
'wait',
]),
command=dict(type='str', required=True),
insertafter=dict(type='str'), insertafter=dict(type='str'),
state=dict(choices=[ state=dict(type='str', required=True, choices=['absent', 'present']),
'present',
'absent',
], required=True, type='str'),
), ),
supports_check_mode=True, supports_check_mode=True,
) )

@ -1,18 +1,16 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# (c) 2014, Nate Coraor <nate@bx.psu.edu> # Copyright: (c) 2014, Nate Coraor <nate@bx.psu.edu>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'], 'status': ['preview'],
'supported_by': 'community'} 'supported_by': 'community'}
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
module: capabilities module: capabilities
@ -24,18 +22,16 @@ options:
path: path:
description: description:
- Specifies the path to the file to be managed. - Specifies the path to the file to be managed.
required: true required: yes
default: null
capability: capability:
description: description:
- Desired capability to set (with operator and flags, if state is C(present)) or remove (if state is C(absent)) - Desired capability to set (with operator and flags, if state is C(present)) or remove (if state is C(absent))
required: true required: yes
default: null aliases: [ cap ]
aliases: [ 'cap' ]
state: state:
description: description:
- Whether the entry should be present or absent in the file's capabilities. - Whether the entry should be present or absent in the file's capabilities.
choices: [ "present", "absent" ] choices: [ absent, present ]
default: present default: present
notes: notes:
- The capabilities system will automatically transform operators and flags - The capabilities system will automatically transform operators and flags
@ -43,19 +39,19 @@ notes:
cap_foo+ep). This module does not attempt to determine the final operator cap_foo+ep). This module does not attempt to determine the final operator
and flags to compare, so you will want to ensure that your capabilities and flags to compare, so you will want to ensure that your capabilities
argument matches the final capabilities. argument matches the final capabilities.
requirements: [] author:
author: "Nate Coraor (@natefoo)" - Nate Coraor (@natefoo)
''' '''
EXAMPLES = ''' EXAMPLES = '''
# Set cap_sys_chroot+ep on /foo - name: Set cap_sys_chroot+ep on /foo
- capabilities: capabilities:
path: /foo path: /foo
capability: cap_sys_chroot+ep capability: cap_sys_chroot+ep
state: present state: present
# Remove cap_net_bind_service from /bar - name: Remove cap_net_bind_service from /bar
- capabilities: capabilities:
path: /bar path: /bar
capability: cap_net_bind_service capability: cap_net_bind_service
state: absent state: absent
@ -63,30 +59,28 @@ EXAMPLES = '''
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
OPS = ('=', '-', '+')
OPS = ( '=', '-', '+' )
class CapabilitiesModule(object): class CapabilitiesModule(object):
platform = 'Linux' platform = 'Linux'
distribution = None distribution = None
def __init__(self, module): def __init__(self, module):
self.module = module self.module = module
self.path = module.params['path'].strip() self.path = module.params['path'].strip()
self.capability = module.params['capability'].strip().lower() self.capability = module.params['capability'].strip().lower()
self.state = module.params['state'] self.state = module.params['state']
self.getcap_cmd = module.get_bin_path('getcap', required=True) self.getcap_cmd = module.get_bin_path('getcap', required=True)
self.setcap_cmd = module.get_bin_path('setcap', required=True) self.setcap_cmd = module.get_bin_path('setcap', required=True)
self.capability_tup = self._parse_cap(self.capability, op_required=self.state=='present') self.capability_tup = self._parse_cap(self.capability, op_required=self.state == 'present')
self.run() self.run()
def run(self): def run(self):
current = self.getcap(self.path) current = self.getcap(self.path)
caps = [ cap[0] for cap in current ] caps = [cap[0] for cap in current]
if self.state == 'present' and self.capability_tup not in current: if self.state == 'present' and self.capability_tup not in current:
# need to add capability # need to add capability
@ -96,7 +90,7 @@ class CapabilitiesModule(object):
# remove from current cap list if it's already set (but op/flags differ) # remove from current cap list if it's already set (but op/flags differ)
current = list(filter(lambda x: x[0] != self.capability_tup[0], current)) current = list(filter(lambda x: x[0] != self.capability_tup[0], current))
# add new cap with correct op/flags # add new cap with correct op/flags
current.append( self.capability_tup ) current.append(self.capability_tup)
self.module.exit_json(changed=True, state=self.state, msg='capabilities changed', stdout=self.setcap(self.path, current)) self.module.exit_json(changed=True, state=self.state, msg='capabilities changed', stdout=self.setcap(self.path, current))
elif self.state == 'absent' and self.capability_tup[0] in caps: elif self.state == 'absent' and self.capability_tup[0] in caps:
# need to remove capability # need to remove capability
@ -130,13 +124,13 @@ class CapabilitiesModule(object):
cap_group = cap.split(',') cap_group = cap.split(',')
cap_group[-1], op, flags = self._parse_cap(cap_group[-1]) cap_group[-1], op, flags = self._parse_cap(cap_group[-1])
for subcap in cap_group: for subcap in cap_group:
rval.append( ( subcap, op, flags ) ) rval.append((subcap, op, flags))
else: else:
rval.append(self._parse_cap(cap)) rval.append(self._parse_cap(cap))
return rval return rval
def setcap(self, path, caps): def setcap(self, path, caps):
caps = ' '.join([ ''.join(cap) for cap in caps ]) caps = ' '.join([''.join(cap) for cap in caps])
cmd = "%s '%s' %s" % (self.setcap_cmd, caps, path) cmd = "%s '%s' %s" % (self.setcap_cmd, caps, path)
rc, stdout, stderr = self.module.run_command(cmd) rc, stdout, stderr = self.module.run_command(cmd)
if rc != 0: if rc != 0:
@ -160,19 +154,19 @@ class CapabilitiesModule(object):
cap, flags = cap.split(op) cap, flags = cap.split(op)
return (cap, op, flags) return (cap, op, flags)
# ============================================================== # ==============================================================
# main # main
def main(): def main():
# defining module # defining module
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec=dict(
path = dict(aliases=['key'], required=True), path=dict(type='str', required=True, aliases=['key']),
capability = dict(aliases=['cap'], required=True), capability=dict(type='str', required=True, aliases=['cap']),
state = dict(default='present', choices=['present', 'absent']), state=dict(type='str', default='present', choices=['absent', 'present']),
), ),
supports_check_mode=True supports_check_mode=True,
) )
CapabilitiesModule(module) CapabilitiesModule(module)

@ -1,30 +1,25 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#
# This file is part of Ansible # Copyright: (c) 2017, Ansible Project
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# Cronvar Plugin: The goal of this plugin is to provide an idempotent # Cronvar Plugin: The goal of this plugin is to provide an idempotent
# method for set cron variable values. It should play well with the # method for set cron variable values. It should play well with the
# existing cron module as well as allow for manually added variables. # existing cron module as well as allow for manually added variables.
# Each variable entered will be preceded with a comment describing the # Each variable entered will be preceded with a comment describing the
# variable so that it can be found later. This is required to be # variable so that it can be found later. This is required to be
# present in order for this plugin to find/modify the variable # present in order for this plugin to find/modify the variable
#
# This module is based on the crontab module. # This module is based on the crontab module.
#
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'], 'status': ['preview'],
'supported_by': 'community'} 'supported_by': 'community'}
DOCUMENTATION = """ DOCUMENTATION = """
--- ---
module: cronvar module: cronvar
@ -37,69 +32,58 @@ options:
name: name:
description: description:
- Name of the crontab variable. - Name of the crontab variable.
default: null required: yes
required: true
value: value:
description: description:
- The value to set this variable to. Required if state=present. - The value to set this variable to.
required: false - Required if C(state=present).
default: null
insertafter: insertafter:
required: false
default: null
description: description:
- Used with C(state=present). If specified, the variable will be inserted - If specified, the variable will be inserted after the variable specified.
after the variable specified. - Used with C(state=present).
insertbefore: insertbefore:
required: false
default: null
description: description:
- Used with C(state=present). If specified, the variable will be inserted - Used with C(state=present). If specified, the variable will be inserted
just before the variable specified. just before the variable specified.
state: state:
description: description:
- Whether to ensure that the variable is present or absent. - Whether to ensure that the variable is present or absent.
required: false choices: [ absent, present ]
default: present default: present
choices: [ "present", "absent" ]
user: user:
description: description:
- The specific user whose crontab should be modified. - The specific user whose crontab should be modified.
required: false
default: root default: root
cron_file: cron_file:
description: description:
- If specified, uses this file instead of an individual user's crontab. - If specified, uses this file instead of an individual user's crontab.
Without a leading /, this is assumed to be in /etc/cron.d. With a leading Without a leading /, this is assumed to be in /etc/cron.d. With a leading
/, this is taken as absolute. /, this is taken as absolute.
required: false
default: null
backup: backup:
description: description:
- If set, create a backup of the crontab before it is modified. - If set, create a backup of the crontab before it is modified.
The location of the backup is returned in the C(backup) variable by this module. The location of the backup is returned in the C(backup) variable by this module.
required: false type: bool
default: false default: 'no'
requirements: requirements:
- cron - cron
author: "Doug Luce (@dougluce)" author:
- Doug Luce (@dougluce)
""" """
EXAMPLES = ''' EXAMPLES = '''
# Ensure a variable exists. - name: Ensure entry like "EMAIL=doug@ansibmod.con.com" exists
# Creates an entry like "EMAIL=doug@ansibmod.con.com" cronvar:
- cronvar:
name: EMAIL name: EMAIL
value: doug@ansibmod.con.com value: doug@ansibmod.con.com
# Make sure a variable is gone. This will remove any variable named - name: Ensure a variable does not exist. This may remove any variable named "LEGACY"
# "LEGACY" cronvar:
- cronvar:
name: LEGACY name: LEGACY
state: absent state: absent
# Adds a variable to a file under /etc/cron.d - name: Add a variable to a file under /etc/cron.d
- cronvar: cronvar:
name: LOGFILE name: LOGFILE
value: /var/log/yum-autoupdate.log value: /var/log/yum-autoupdate.log
user: root user: root
@ -117,7 +101,6 @@ import tempfile
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
CRONCMD = "/usr/bin/crontab" CRONCMD = "/usr/bin/crontab"
@ -132,11 +115,12 @@ class CronVar(object):
user - the user of the crontab (defaults to root) user - the user of the crontab (defaults to root)
cron_file - a cron file under /etc/cron.d cron_file - a cron file under /etc/cron.d
""" """
def __init__(self, module, user=None, cron_file=None): def __init__(self, module, user=None, cron_file=None):
self.module = module self.module = module
self.user = user self.user = user
self.lines = None self.lines = None
self.wordchars = ''.join(chr(x) for x in range(128) if chr(x) not in ('=', "'", '"', )) self.wordchars = ''.join(chr(x) for x in range(128) if chr(x) not in ('=', "'", '"',))
if cron_file: if cron_file:
self.cron_file = "" self.cron_file = ""
@ -167,15 +151,14 @@ class CronVar(object):
# using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME # using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME
(rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True) (rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True)
if rc != 0 and rc != 1: # 1 can mean that there are no jobs. if rc != 0 and rc != 1: # 1 can mean that there are no jobs.
raise CronVarError("Unable to read crontab") raise CronVarError("Unable to read crontab")
lines = out.splitlines() lines = out.splitlines()
count = 0 count = 0
for l in lines: for l in lines:
if count > 2 or (not re.match( r'# DO NOT EDIT THIS FILE - edit the master and reinstall.', l) and if count > 2 or (not re.match(r'# DO NOT EDIT THIS FILE - edit the master and reinstall.', l
not re.match( r'# \(/tmp/.*installed on.*\)', l) and ) and not re.match(r'# \(/tmp/.*installed on.*\)', l) and not re.match(r'# \(.*version.*\)', l)):
not re.match( r'# \(.*version.*\)', l)):
self.lines.append(l) self.lines.append(l)
count += 1 count += 1
@ -258,7 +241,7 @@ class CronVar(object):
newlines = [] newlines = []
for l in self.lines: for l in self.lines:
try: try:
(varname, _) = self.parse_for_var(l) # Throws if not a var line (varname, _) = self.parse_for_var(l) # Throws if not a var line
if varname == insertbefore: if varname == insertbefore:
newlines.append("%s=%s" % (name, value)) newlines.append("%s=%s" % (name, value))
newlines.append(l) newlines.append(l)
@ -266,7 +249,7 @@ class CronVar(object):
newlines.append(l) newlines.append(l)
newlines.append("%s=%s" % (name, value)) newlines.append("%s=%s" % (name, value))
else: else:
raise CronVarError # Append. raise CronVarError # Append.
except CronVarError: except CronVarError:
newlines.append(l) newlines.append(l)
@ -279,9 +262,9 @@ class CronVar(object):
newlines = [] newlines = []
for l in self.lines: for l in self.lines:
try: try:
(varname, _) = self.parse_for_var(l) # Throws if not a var line (varname, _) = self.parse_for_var(l) # Throws if not a var line
if varname != name: if varname != name:
raise CronVarError # Append. raise CronVarError # Append.
if not remove: if not remove:
newlines.append("%s=%s" % (name, value)) newlines.append("%s=%s" % (name, value))
except CronVarError: except CronVarError:
@ -310,10 +293,10 @@ class CronVar(object):
elif platform.system() == 'AIX': elif platform.system() == 'AIX':
return "%s -l %s" % (pipes.quote(CRONCMD), pipes.quote(self.user)) return "%s -l %s" % (pipes.quote(CRONCMD), pipes.quote(self.user))
elif platform.system() == 'HP-UX': elif platform.system() == 'HP-UX':
return "%s %s %s" % (CRONCMD , '-l', pipes.quote(self.user)) return "%s %s %s" % (CRONCMD, '-l', pipes.quote(self.user))
elif pwd.getpwuid(os.getuid())[0] != self.user: elif pwd.getpwuid(os.getuid())[0] != self.user:
user = '-u %s' % pipes.quote(self.user) user = '-u %s' % pipes.quote(self.user)
return "%s %s %s" % (CRONCMD , user, '-l') return "%s %s %s" % (CRONCMD, user, '-l')
def _write_execute(self, path): def _write_execute(self, path):
""" """
@ -325,9 +308,10 @@ class CronVar(object):
return "chown %s %s ; su '%s' -c '%s %s'" % (pipes.quote(self.user), pipes.quote(path), pipes.quote(self.user), CRONCMD, pipes.quote(path)) return "chown %s %s ; su '%s' -c '%s %s'" % (pipes.quote(self.user), pipes.quote(path), pipes.quote(self.user), CRONCMD, pipes.quote(path))
elif pwd.getpwuid(os.getuid())[0] != self.user: elif pwd.getpwuid(os.getuid())[0] != self.user:
user = '-u %s' % pipes.quote(self.user) user = '-u %s' % pipes.quote(self.user)
return "%s %s %s" % (CRONCMD , user, pipes.quote(path)) return "%s %s %s" % (CRONCMD, user, pipes.quote(path))
#================================================== # ==================================================
def main(): def main():
# The following example playbooks: # The following example playbooks:
@ -346,14 +330,14 @@ def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
name=dict(required=True), name=dict(type='str', required=True),
value=dict(required=False), value=dict(type='str'),
user=dict(required=False), user=dict(type='str'),
cron_file=dict(required=False), cron_file=dict(type='str'),
insertafter=dict(default=None), insertafter=dict(type='str'),
insertbefore=dict(default=None), insertbefore=dict(type='str'),
state=dict(default='present', choices=['present', 'absent']), state=dict(type='str', default='present', choices=['absent', 'present']),
backup=dict(default=False, type='bool'), backup=dict(type='bool', default=False),
), ),
mutually_exclusive=[['insertbefore', 'insertafter']], mutually_exclusive=[['insertbefore', 'insertafter']],
supports_check_mode=False, supports_check_mode=False,
@ -373,7 +357,7 @@ def main():
res_args = dict() res_args = dict()
# Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option. # Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option.
os.umask(int('022',8)) os.umask(int('022', 8))
cronvar = CronVar(module, user, cron_file) cronvar = CronVar(module, user, cron_file)
module.debug('cronvar instantiated - name: "%s"' % name) module.debug('cronvar instantiated - name: "%s"' % name)

@ -1,18 +1,16 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# (c) 2014, Steve <yo@groks.org> # Copyright: (c) 2014, Steve <yo@groks.org>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'], 'status': ['preview'],
'supported_by': 'community'} 'supported_by': 'community'}
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
module: crypttab module: crypttab
@ -26,9 +24,7 @@ options:
- Name of the encrypted block device as it appears in the C(/etc/crypttab) file, or - Name of the encrypted block device as it appears in the C(/etc/crypttab) file, or
optionally prefixed with C(/dev/mapper/), as it appears in the filesystem. I(/dev/mapper/) optionally prefixed with C(/dev/mapper/), as it appears in the filesystem. I(/dev/mapper/)
will be stripped from I(name). will be stripped from I(name).
required: true required: yes
default: null
aliases: []
state: state:
description: description:
- Use I(present) to add a line to C(/etc/crypttab) or update it's definition - Use I(present) to add a line to C(/etc/crypttab) or update it's definition
@ -36,45 +32,35 @@ options:
Use I(opts_present) to add options to those already present; options with Use I(opts_present) to add options to those already present; options with
different values will be updated. Use I(opts_absent) to remove options from different values will be updated. Use I(opts_absent) to remove options from
the existing set. the existing set.
required: true required: yes
choices: [ "present", "absent", "opts_present", "opts_absent"] choices: [ absent, opts_absent, opts_present, present ]
default: null
backing_device: backing_device:
description: description:
- Path to the underlying block device or file, or the UUID of a block-device - Path to the underlying block device or file, or the UUID of a block-device
prefixed with I(UUID=) prefixed with I(UUID=).
required: false
default: null
password: password:
description: description:
- Encryption password, the path to a file containing the password, or - Encryption password, the path to a file containing the password, or
'none' or '-' if the password should be entered at boot. C(none) or C(-) if the password should be entered at boot.
required: false default: 'none'
default: "none"
opts: opts:
description: description:
- A comma-delimited list of options. See C(crypttab(5) ) for details. - A comma-delimited list of options. See C(crypttab(5) ) for details.
required: false
path: path:
description: description:
- Path to file to use instead of C(/etc/crypttab). This might be useful - Path to file to use instead of C(/etc/crypttab). This might be useful
in a chroot environment. in a chroot environment.
required: false
default: /etc/crypttab default: /etc/crypttab
author:
notes: [] - Steve (@groks)
requirements: []
author: "Steve (@groks)"
''' '''
EXAMPLES = ''' EXAMPLES = '''
# Since column is a special character in YAML, if your string contains a column, it's better to use quotes around the string
- name: Set the options explicitly a device which must already exist - name: Set the options explicitly a device which must already exist
crypttab: crypttab:
name: luks-home name: luks-home
state: present state: present
opts: 'discard,cipher=aes-cbc-essiv:sha256' opts: discard,cipher=aes-cbc-essiv:sha256
- name: Add the 'discard' option to any existing options for all devices - name: Add the 'discard' option to any existing options for all devices
crypttab: crypttab:
@ -91,30 +77,29 @@ import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils._text import to_bytes, to_native
def main():
def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec=dict(
name = dict(required=True), name=dict(type='str', required=True),
state = dict(required=True, choices=['present', 'absent', 'opts_present', 'opts_absent']), state=dict(type='str', required=True, choices=['absent', 'opts_absent', 'opts_present', 'present']),
backing_device = dict(default=None), backing_device=dict(type='str'),
password = dict(default=None, type='path'), password=dict(type='path'),
opts = dict(default=None), opts=dict(type='str'),
path = dict(default='/etc/crypttab', type='path') path=dict(type='path', default='/etc/crypttab')
), ),
supports_check_mode = True supports_check_mode=True,
) )
backing_device = module.params['backing_device'] backing_device = module.params['backing_device']
password = module.params['password'] password = module.params['password']
opts = module.params['opts'] opts = module.params['opts']
state = module.params['state'] state = module.params['state']
path = module.params['path'] path = module.params['path']
name = module.params['name'] name = module.params['name']
if name.startswith('/dev/mapper/'): if name.startswith('/dev/mapper/'):
name = name[len('/dev/mapper/'):] name = name[len('/dev/mapper/'):]
if state != 'absent' and backing_device is None and password is None and opts is None: if state != 'absent' and backing_device is None and password is None and opts is None:
module.fail_json(msg="expected one or more of 'backing_device', 'password' or 'opts'", module.fail_json(msg="expected one or more of 'backing_device', 'password' or 'opts'",
**module.params) **module.params)
@ -127,8 +112,7 @@ def main():
('backing_device', backing_device), ('backing_device', backing_device),
('password', password), ('password', password),
('opts', opts)): ('opts', opts)):
if (arg is not None if (arg is not None and (' ' in arg or '\t' in arg or arg == '')):
and (' ' in arg or '\t' in arg or arg == '')):
module.fail_json(msg="invalid '%s': contains white space or is empty" % arg_name, module.fail_json(msg="invalid '%s': contains white space or is empty" % arg_name,
**module.params) **module.params)
@ -165,7 +149,6 @@ def main():
if existing_line is not None: if existing_line is not None:
changed, reason = existing_line.opts.remove(opts) changed, reason = existing_line.opts.remove(opts)
if changed and not module.check_mode: if changed and not module.check_mode:
try: try:
f = open(path, 'wb') f = open(path, 'wb')
@ -177,7 +160,6 @@ def main():
class Crypttab(object): class Crypttab(object):
_lines = [] _lines = []
def __init__(self, path): def __init__(self, path):
@ -185,7 +167,7 @@ class Crypttab(object):
if not os.path.exists(path): if not os.path.exists(path):
if not os.path.exists(os.path.dirname(path)): if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path)) os.makedirs(os.path.dirname(path))
open(path,'a').close() open(path, 'a').close()
try: try:
f = open(path, 'r') f = open(path, 'r')
@ -222,7 +204,6 @@ class Crypttab(object):
class Line(object): class Line(object):
def __init__(self, line=None, name=None, backing_device=None, password=None, opts=None): def __init__(self, line=None, name=None, backing_device=None, password=None, opts=None):
self.line = line self.line = line
self.name = name self.name = name
@ -355,8 +336,7 @@ class Options(dict):
super(Options, self).__delitem__(key) super(Options, self).__delitem__(key)
def __ne__(self, obj): def __ne__(self, obj):
return not (isinstance(obj, Options) return not (isinstance(obj, Options) and sorted(self.items()) == sorted(obj.items()))
and sorted(self.items()) == sorted(obj.items()))
def __str__(self): def __str__(self):
ret = [] ret = []

@ -311,7 +311,3 @@ lib/ansible/modules/storage/netapp/sf_snapshot_schedule_manager.py
lib/ansible/modules/storage/netapp/sf_volume_access_group_manager.py lib/ansible/modules/storage/netapp/sf_volume_access_group_manager.py
lib/ansible/modules/storage/netapp/sf_volume_manager.py lib/ansible/modules/storage/netapp/sf_volume_manager.py
lib/ansible/modules/storage/zfs/zfs.py lib/ansible/modules/storage/zfs/zfs.py
lib/ansible/modules/system/aix_inittab.py
lib/ansible/modules/system/capabilities.py
lib/ansible/modules/system/cronvar.py
lib/ansible/modules/system/crypttab.py

Loading…
Cancel
Save