summaryrefslogtreecommitdiff
path: root/library/group
blob: fc21c5c1a32aaecbad4cd864ffed7deac3dfe590 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python

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

try:
    import json
except ImportError:
    import simplejson as json
import os
import grp
import shlex
import subprocess
import sys
import syslog

GROUPADD = "/usr/sbin/groupadd"
GROUPDEL = "/usr/sbin/groupdel"
GROUPMOD = "/usr/sbin/groupmod"

def exit_json(rc=0, **kwargs):
    if 'name' in kwargs:
        add_group_info(kwargs)
    print json.dumps(kwargs)
    sys.exit(rc)

def fail_json(**kwargs):
    kwargs['failed'] = True
    exit_json(rc=1, **kwargs)

def add_group_info(kwargs):
    name = kwargs['name']
    if group_exists(name):
        kwargs['state'] = 'present'
        info = group_info(name)
        kwargs['gid'] = info[2]
    else:
        kwargs['state'] = 'absent'
    return kwargs

def group_del(group):
    cmd = [GROUPDEL, group]
    rc = subprocess.call(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if rc == 0:
        return True
    else:
        return False

def group_add(group, **kwargs):
    cmd = [GROUPADD]
    for key in kwargs:
        if key == 'gid' and kwargs[key] is not None:
            cmd.append('-g')
            cmd.append(kwargs[key])
        elif key == 'system' and kwargs[key] == 'yes':
            cmd.append('-r')
    cmd.append(group)
    rc = subprocess.call(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if rc == 0:
        return True
    else:
        return False

def group_mod(group, **kwargs):
    cmd = [GROUPMOD]
    info = group_info(group)
    for key in kwargs:
        if key == 'gid':
            if kwargs[key] is not None and info[2] != int(kwargs[key]):
                cmd.append('-g')
                cmd.append(kwargs[key])
    if len(cmd) == 1:
        return False
    cmd.append(group)
    rc = subprocess.call(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if rc == 0:
        return True
    else:
        return False

def group_exists(group):
    try:
        if grp.getgrnam(group):
            return True
    except KeyError:
        return False

def group_info(group):
    if not group_exists(group):
        return False
    try:
        info = list(grp.getgrnam(group))
    except KeyError:
        return False
    return info
    
# ===========================================

if not os.path.exists(GROUPADD):
    if os.path.exists("/sbin/groupadd"):
        GROUPADD = "/sbin/groupadd"
    else:
        fail_json(msg="Cannot find groupadd")
if not os.path.exists(GROUPDEL):
    if os.path.exists("/sbin/groupdel"):
        GROUPDEL = "/sbin/groupdel"
    else:
        fail_json(msg="Cannot find groupdel")
if not os.path.exists(GROUPMOD):
    if os.path.exists("/sbin/groupmod"):
        GROUPDEL = "/sbin/groupmod"
    else:
        fail_json(msg="Cannot find groupmod")

if len(sys.argv) == 2 and os.path.exists(sys.argv[1]):
    argfile = sys.argv[1]
    args    = open(argfile, 'r').read()
else:
    args = ' '.join(sys.argv[1:])
items   = shlex.split(args)
syslog.openlog('ansible-%s' % os.path.basename(__file__))
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)

if not len(items):
    fail_json(msg='the module requires arguments -a')
    sys.exit(1)

params = {}
for x in items:
    (k, v) = x.split("=")
    params[k] = v

state       = params.get('state','present')
name        = params.get('name', None)
gid         = params.get('gid', None)
system      = params.get('system', 'no')

if state not in [ 'present', 'absent' ]:
    fail_json(msg='invalid state')
if system not in ['yes', 'no']:
    fail_json(msg='invalid system')
if name is None:
    fail_json(msg='name is required')

changed = False
rc = 0
if state == 'absent':
    if group_exists(name):
        changed = group_del(name)
    exit_json(name=name, changed=changed)
elif state == 'present':
    if not group_exists(name):
        changed = group_add(name, gid=gid, system=system)
    else:
        changed = group_mod(name, gid=gid)

    exit_json(name=name, changed=changed)

fail_json(name=name, msg='Unexpected position reached')