~canonical-ci-engineering/ubuntu-ci-services-itself/ansible

« back to all changes in this revision

Viewing changes to library/yum

  • Committer: Package Import Robot
  • Author(s): Michael Vogt, Harlan Lieberman-Berg, Michael Vogt
  • Date: 2013-11-01 09:40:59 UTC
  • mfrom: (1.1.2)
  • Revision ID: package-import@ubuntu.com-20131101094059-6w580ocxzqyqzuu3
Tags: 1.3.4+dfsg-1
[ Harlan Lieberman-Berg ]
* New upstream release (Closes: #717777).
  Fixes CVE-2013-2233 (Closes: #714822).
  Fixes CVE-2013-4259 (Closes: #721766).
* Drop fix-ansible-cfg patch.
* Change docsite generation to not expect docs as part of a wordpress install.
* Add trivial patch to fix lintian error with rpm-key script.
* Add patch header information to fix-html-makefile.

[ Michael Vogt ]
* add myself to uploader
* build/ship the module manpages for ansible in the ansible package

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python -tt
2
 
# -*- coding: utf-8 -*-
3
 
 
4
 
# (c) 2012, Red Hat, Inc
5
 
# Written by Seth Vidal <skvidal at fedoraproject.org>
6
 
#
7
 
# This file is part of Ansible
8
 
#
9
 
# Ansible is free software: you can redistribute it and/or modify
10
 
# it under the terms of the GNU General Public License as published by
11
 
# the Free Software Foundation, either version 3 of the License, or
12
 
# (at your option) any later version.
13
 
#
14
 
# Ansible is distributed in the hope that it will be useful,
15
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 
# GNU General Public License for more details.
18
 
#
19
 
# You should have received a copy of the GNU General Public License
20
 
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
21
 
#
22
 
 
23
 
 
24
 
import traceback
25
 
import os
26
 
import yum
27
 
 
28
 
DOCUMENTATION = '''
29
 
---
30
 
module: yum
31
 
short_description: Manages packages with the I(yum) package manager
32
 
description:
33
 
     - Will install, upgrade, remove, and list packages with the I(yum) package manager.
34
 
options:
35
 
  name:
36
 
    description:
37
 
      - package name, or package specifier with version, like C(name-1.0).
38
 
    required: true
39
 
    default: null
40
 
    aliases: []
41
 
  list:
42
 
    description:
43
 
      - various non-idempotent commands for usage with C(/usr/bin/ansible) and I(not) playbooks. See examples.
44
 
    required: false
45
 
    default: null
46
 
  state:
47
 
    description:
48
 
      - whether to install (C(present), C(latest)), or remove (C(absent)) a package.
49
 
    required: false
50
 
    choices: [ "present", "latest", "absent" ]
51
 
    default: "present"
52
 
  enablerepo:
53
 
    description:
54
 
      - Repoid of repositories to enable for the install/update operation.
55
 
        These repos will not persist beyond the transaction
56
 
        multiple repos separated with a ','
57
 
    required: false
58
 
    version_added: "0.9"
59
 
    default: null
60
 
    aliases: []
61
 
    
62
 
  disablerepo:
63
 
    description:
64
 
      - I(repoid) of repositories to disable for the install/update operation
65
 
        These repos will not persist beyond the transaction
66
 
        Multiple repos separated with a ','
67
 
    required: false
68
 
    version_added: "0.9"
69
 
    default: null
70
 
    aliases: []
71
 
    
72
 
examples:
73
 
   - code: yum name=httpd state=latest
74
 
   - code: yum name=httpd state=removed
75
 
   - code: yum name=httpd enablerepo=testing state=installed
76
 
notes: []
77
 
# informational: requirements for nodes
78
 
requirements: [ yum, rpm ]
79
 
author: Seth Vidal
80
 
'''
81
 
 
82
 
def_qf = "%{name}-%{version}-%{release}.%{arch}"
83
 
 
84
 
repoquery='/usr/bin/repoquery'
85
 
if not os.path.exists(repoquery):
86
 
    repoquery = None
87
 
 
88
 
yumbin='/usr/bin/yum'
89
 
 
90
 
def yum_base(conf_file=None, cachedir=False):
91
 
 
92
 
    my = yum.YumBase()
93
 
    my.preconf.debuglevel=0
94
 
    my.preconf.errorlevel=0
95
 
    if conf_file and os.path.exists(conf_file):
96
 
        my.preconf.fn = conf_file
97
 
    if cachedir or os.geteuid() != 0:
98
 
        if hasattr(my, 'setCacheDir'):
99
 
            my.setCacheDir()
100
 
        else:
101
 
            cachedir = yum.misc.getCacheDir()
102
 
            my.repos.setCacheDir(cachedir)
103
 
            my.conf.cache = 0 
104
 
 
105
 
    return my
106
 
 
107
 
def po_to_nevra(po):
108
 
 
109
 
    if hasattr(po, 'ui_nevra'):
110
 
        return po.ui_nevra
111
 
    else:
112
 
        return '%s-%s-%s.%s' % (po.name, po.version, po.release, po.arch)
113
 
 
114
 
def is_installed(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
115
 
 
116
 
    if not repoq:
117
 
 
118
 
        pkgs = []
119
 
        try:
120
 
            my = yum_base(conf_file)
121
 
            for rid in en_repos:
122
 
                my.repos.enableRepo(rid)
123
 
            for rid in dis_repos:
124
 
                my.repos.disableRepo(rid)
125
 
                
126
 
            e,m,u = my.rpmdb.matchPackageNames([pkgspec])
127
 
            pkgs = e + m
128
 
            if not pkgs:
129
 
                pkgs.extend(my.returnInstalledPackagesByDep(pkgspec))
130
 
        except Exception, e:
131
 
            module.fail_json(msg="Failure talking to yum: %s" % e)
132
 
 
133
 
        return [ po_to_nevra(p) for p in pkgs ]
134
 
 
135
 
    else:
136
 
 
137
 
        cmd = repoq + ["--disablerepo=*", "--pkgnarrow=installed", "--qf", qf, pkgspec]
138
 
        rc,out,err = module.run_command(cmd)
139
 
        cmd = repoq + ["--disablerepo=*", "--pkgnarrow=installed", "--qf", qf, "--whatprovides", pkgspec]
140
 
        rc2,out2,err2 = module.run_command(cmd)
141
 
        if rc == 0 and rc2 == 0:
142
 
            out += out2
143
 
            return [ p for p in out.split('\n') if p.strip() ]
144
 
        else:
145
 
            module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
146
 
            
147
 
    return []
148
 
 
149
 
def is_available(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
150
 
 
151
 
    if not repoq:
152
 
 
153
 
        pkgs = []
154
 
        try:
155
 
            my = yum_base(conf_file)
156
 
            for rid in en_repos:
157
 
                my.repos.enableRepo(rid)
158
 
            for rid in dis_repos:
159
 
                my.repos.disableRepo(rid)
160
 
 
161
 
            e,m,u = my.pkgSack.matchPackageNames([pkgspec])
162
 
            pkgs = e + m
163
 
            if not pkgs:
164
 
                pkgs.extend(my.returnPackagesByDep(pkgspec))
165
 
        except Exception, e:
166
 
            module.fail_json(msg="Failure talking to yum: %s" % e)
167
 
            
168
 
        return [ po_to_nevra(p) for p in pkgs ]
169
 
 
170
 
    else:
171
 
        myrepoq = list(repoq)
172
 
 
173
 
        for repoid in en_repos:
174
 
            r_cmd = ['--enablerepo', repoid]
175
 
            myrepoq.extend(r_cmd)
176
 
    
177
 
        for repoid in dis_repos:
178
 
            r_cmd = ['--disablerepo', repoid]
179
 
            myrepoq.extend(r_cmd)
180
 
 
181
 
        cmd = myrepoq + ["--qf", qf, pkgspec]
182
 
        rc,out,err = module.run_command(cmd)
183
 
        if rc == 0:
184
 
            return [ p for p in out.split('\n') if p.strip() ]
185
 
        else:
186
 
            module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
187
 
 
188
 
            
189
 
    return []
190
 
 
191
 
def is_update(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
192
 
 
193
 
    if not repoq:
194
 
 
195
 
        retpkgs = []
196
 
        pkgs = []
197
 
        updates = []
198
 
 
199
 
        try:
200
 
            my = yum_base(conf_file)
201
 
            for rid in en_repos:
202
 
                my.repos.enableRepo(rid)
203
 
            for rid in dis_repos:
204
 
                my.repos.disableRepo(rid)
205
 
 
206
 
            pkgs = my.returnPackagesByDep(pkgspec) + my.returnInstalledPackagesByDep(pkgspec)
207
 
            if not pkgs:
208
 
                e,m,u = my.pkgSack.matchPackageNames([pkgspec])
209
 
                pkgs = e + m
210
 
            updates = my.doPackageLists(pkgnarrow='updates').updates 
211
 
        except Exception, e:
212
 
            module.fail_json(msg="Failure talking to yum: %s" % e)
213
 
 
214
 
        for pkg in pkgs:
215
 
            if pkg in updates:
216
 
                retpkgs.append(pkg)
217
 
            
218
 
        return set([ po_to_nevra(p) for p in retpkgs ])
219
 
 
220
 
    else:
221
 
        myrepoq = list(repoq)
222
 
        for repoid in en_repos:
223
 
            r_cmd = ['--enablerepo', repoid]
224
 
            myrepoq.extend(r_cmd)
225
 
    
226
 
        for repoid in dis_repos:
227
 
            r_cmd = ['--disablerepo', repoid]
228
 
            myrepoq.extend(r_cmd)
229
 
 
230
 
 
231
 
        cmd = myrepoq + ["--pkgnarrow=updates", "--qf", qf, pkgspec]
232
 
        rc,out,err = module.run_command(cmd)
233
 
        
234
 
        if rc == 0:
235
 
            return set([ p for p in out.split('\n') if p.strip() ])
236
 
        else:
237
 
            module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
238
 
            
239
 
    return []
240
 
 
241
 
def what_provides(module, repoq, req_spec, conf_file,  qf=def_qf, en_repos=[], dis_repos=[]):
242
 
 
243
 
    if not repoq:
244
 
 
245
 
        pkgs = []
246
 
        try:
247
 
            my = yum_base(conf_file)
248
 
            for rid in en_repos:
249
 
                my.repos.enableRepo(rid)
250
 
            for rid in dis_repos:
251
 
                my.repos.disableRepo(rid)
252
 
 
253
 
            pkgs = my.returnPackagesByDep(req_spec) + my.returnInstalledPackagesByDep(req_spec)
254
 
            if not pkgs:
255
 
                e,m,u = my.pkgSack.matchPackageNames([req_spec])
256
 
                pkgs.extend(e)
257
 
                pkgs.extend(m)
258
 
                e,m,u = my.rpmdb.matchPackageNames([req_spec])
259
 
                pkgs.extend(e)
260
 
                pkgs.extend(m)
261
 
        except Exception, e:
262
 
            module.fail_json(msg="Failure talking to yum: %s" % e)
263
 
 
264
 
        return set([ po_to_nevra(p) for p in pkgs ])
265
 
 
266
 
    else:
267
 
        myrepoq = list(repoq)
268
 
        for repoid in en_repos:
269
 
            r_cmd = ['--enablerepo', repoid]
270
 
            myrepoq.extend(r_cmd)
271
 
    
272
 
        for repoid in dis_repos:
273
 
            r_cmd = ['--disablerepo', repoid]
274
 
            myrepoq.extend(r_cmd)
275
 
 
276
 
        cmd = myrepoq + ["--qf", qf, "--whatprovides", req_spec]
277
 
        rc,out,err = module.run_command(cmd)
278
 
        cmd = myrepoq + ["--qf", qf, req_spec]
279
 
        rc2,out2,err2 = module.run_command(cmd)
280
 
        if rc == 0 and rc2 == 0:
281
 
            out += out2
282
 
            pkgs = set([ p for p in out.split('\n') if p.strip() ])
283
 
            if not pkgs:
284
 
                pkgs = is_installed(module, repoq, req_spec, conf_file, qf=qf)
285
 
            return pkgs
286
 
        else:
287
 
            module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
288
 
 
289
 
    return []
290
 
 
291
 
def local_nvra(module, path):
292
 
    """return nvra of a local rpm passed in"""
293
 
    
294
 
    cmd = ['/bin/rpm', '-qp' ,'--qf', 
295
 
            '%{name}-%{version}-%{release}.%{arch}\n', path ]
296
 
    rc, out, err = module.run_command(cmd)
297
 
    if rc != 0:
298
 
        return None
299
 
    nvra = out.split('\n')[0]
300
 
    return nvra
301
 
    
302
 
def pkg_to_dict(pkgstr):
303
 
 
304
 
    if pkgstr.strip():
305
 
        n,e,v,r,a,repo = pkgstr.split('|')
306
 
    else:
307
 
        return {'error_parsing': pkgstr}
308
 
 
309
 
    d = {
310
 
        'name':n,
311
 
        'arch':a,
312
 
        'epoch':e,
313
 
        'release':r,
314
 
        'version':v,
315
 
        'repo':repo,
316
 
        'nevra': '%s:%s-%s-%s.%s' % (e,n,v,r,a)
317
 
    }
318
 
 
319
 
    if repo == 'installed':
320
 
        d['yumstate'] = 'installed'
321
 
    else:
322
 
        d['yumstate'] = 'available'
323
 
 
324
 
    return d
325
 
 
326
 
def repolist(module, repoq, qf="%{repoid}"):
327
 
 
328
 
    cmd = repoq + ["--qf", qf, "-a"]
329
 
    rc,out,err = module.run_command(cmd)
330
 
    ret = []
331
 
    if rc == 0:
332
 
        ret = set([ p for p in out.split('\n') if p.strip() ])
333
 
    return ret
334
 
 
335
 
def list_stuff(module, conf_file, stuff):
336
 
 
337
 
    qf = "%{name}|%{epoch}|%{version}|%{release}|%{arch}|%{repoid}"
338
 
    repoq = [repoquery, '--show-duplicates', '--plugins', '--quiet', '-q']
339
 
    if conf_file and os.path.exists(conf_file):
340
 
        repoq += ['-c', conf_file]
341
 
 
342
 
    if stuff == 'installed':
343
 
        return [ pkg_to_dict(p) for p in is_installed(module, repoq, '-a', conf_file, qf=qf) if p.strip() ]
344
 
    elif stuff == 'updates':
345
 
        return [ pkg_to_dict(p) for p in is_update(module, repoq, '-a', conf_file, qf=qf) if p.strip() ]
346
 
    elif stuff == 'available':
347
 
        return [ pkg_to_dict(p) for p in is_available(module, repoq, '-a', conf_file, qf=qf) if p.strip() ]
348
 
    elif stuff == 'repos':
349
 
        return [ dict(repoid=name, state='enabled') for name in repolist(module, repoq) if name.strip() ]
350
 
    else:
351
 
        return [ pkg_to_dict(p) for p in is_installed(module, repoq, stuff, conf_file, qf=qf) + is_available(module, repoq, stuff, conf_file, qf=qf) if p.strip() ]
352
 
 
353
 
def install(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
354
 
 
355
 
    res = {}
356
 
    res['results'] = []
357
 
    res['msg'] = ''
358
 
    res['rc'] = 0
359
 
    res['changed'] = False
360
 
 
361
 
    for spec in items:
362
 
        pkg = None
363
 
 
364
 
        # check if pkgspec is installed (if possible for idempotence)
365
 
        # localpkg
366
 
        if spec.endswith('.rpm'):
367
 
            # get the pkg name-v-r.arch
368
 
            if not os.path.exists(spec):
369
 
                res['msg'] += "No Package file matching '%s' found on system" % spec
370
 
                module.fail_json(**res)
371
 
 
372
 
            nvra = local_nvra(module, spec)
373
 
            # look for them in the rpmdb
374
 
            if is_installed(module, repoq, nvra, conf_file, en_repos=en_repos, dis_repos=dis_repos):
375
 
                # if they are there, skip it
376
 
                continue
377
 
            pkg = spec
378
 
        #groups :(
379
 
        elif  spec.startswith('@'):
380
 
            # complete wild ass guess b/c it's a group
381
 
            pkg = spec
382
 
 
383
 
        # range requires or file-requires or pkgname :(
384
 
        else:
385
 
            # look up what pkgs provide this
386
 
            pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
387
 
            if not pkglist:
388
 
                res['msg'] += "No Package matching '%s' found available, installed or updated" % spec
389
 
                module.fail_json(**res)
390
 
 
391
 
            # if any of them are installed
392
 
            # then nothing to do
393
 
 
394
 
            found = False
395
 
            for this in pkglist:
396
 
                if is_installed(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos):
397
 
                    found = True
398
 
                    res['results'].append('%s providing %s is already installed' % (this, spec))
399
 
                    break
400
 
 
401
 
            # if the version of the pkg you have installed is not in ANY repo, but there are
402
 
            # other versions in the repos (both higher and lower) then the previous checks won't work.
403
 
            # so we check one more time. This really only works for pkgname - not for file provides or virt provides
404
 
            # but virt provides should be all caught in what_provides on its own.
405
 
            # highly irritating
406
 
            if not found:
407
 
                if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
408
 
                    found = True
409
 
                    res['results'].append('package providing %s is already installed' % (spec))
410
 
                    
411
 
            if found:
412
 
                continue
413
 
            # if not - then pass in the spec as what to install
414
 
            # we could get here if nothing provides it but that's not
415
 
            # the error we're catching here
416
 
            pkg = spec
417
 
 
418
 
        cmd = yum_basecmd + ['install', pkg]
419
 
 
420
 
        if module.check_mode:
421
 
            module.exit_json(changed=True)
422
 
 
423
 
        rc, out, err = module.run_command(cmd)
424
 
 
425
 
        res['rc'] += rc
426
 
        res['results'].append(out)
427
 
        res['msg'] += err
428
 
 
429
 
        # FIXME - if we did an install - go and check the rpmdb to see if it actually installed
430
 
        # look for the pkg in rpmdb
431
 
        # look for the pkg via obsoletes
432
 
        if not rc:
433
 
            res['changed'] = True
434
 
 
435
 
    module.exit_json(**res)
436
 
 
437
 
 
438
 
def remove(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
439
 
 
440
 
    res = {}
441
 
    res['results'] = []
442
 
    res['msg'] = ''
443
 
    res['changed'] = False
444
 
    res['rc'] = 0
445
 
 
446
 
    for pkg in items:
447
 
        is_group = False
448
 
        # group remove - this is doom on a stick
449
 
        if pkg.startswith('@'):
450
 
            is_group = True
451
 
        else:
452
 
            if not is_installed(module, repoq, pkg, conf_file, en_repos=en_repos, dis_repos=dis_repos):
453
 
                res['results'].append('%s is not installed' % pkg)
454
 
                continue
455
 
 
456
 
        # run an actual yum transaction
457
 
        cmd = yum_basecmd + ["remove", pkg]
458
 
 
459
 
        if module.check_mode:
460
 
            module.exit_json(changed=True)
461
 
 
462
 
        rc, out, err = module.run_command(cmd)
463
 
 
464
 
        res['rc'] += rc
465
 
        res['results'].append(out)
466
 
        res['msg'] += err
467
 
 
468
 
        # compile the results into one batch. If anything is changed 
469
 
        # then mark changed
470
 
        # at the end - if we've end up failed then fail out of the rest
471
 
        # of the process
472
 
 
473
 
        # at this point we should check to see if the pkg is no longer present
474
 
        
475
 
        if not is_group: # we can't sensibly check for a group being uninstalled reliably
476
 
            # look to see if the pkg shows up from is_installed. If it doesn't
477
 
            if not is_installed(module, repoq, pkg, conf_file, en_repos=en_repos, dis_repos=dis_repos):
478
 
                res['changed'] = True
479
 
            else:
480
 
                module.fail_json(**res)
481
 
 
482
 
        if rc != 0:
483
 
            module.fail_json(**res)
484
 
            
485
 
    module.exit_json(**res)
486
 
 
487
 
def latest(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
488
 
 
489
 
    res = {}
490
 
    res['results'] = []
491
 
    res['msg'] = ''
492
 
    res['changed'] = False
493
 
    res['rc'] = 0
494
 
 
495
 
    for spec in items:
496
 
 
497
 
        pkg = None
498
 
        basecmd = 'update'
499
 
        # groups, again
500
 
        if spec.startswith('@'):
501
 
            pkg = spec
502
 
        # dep/pkgname  - find it
503
 
        else:
504
 
            if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
505
 
                basecmd = 'update'
506
 
            else:
507
 
                basecmd = 'install'
508
 
 
509
 
            pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
510
 
            if not pkglist:
511
 
                res['msg'] += "No Package matching '%s' found available, installed or updated" % spec
512
 
                module.fail_json(**res)
513
 
            
514
 
            nothing_to_do = True
515
 
            for this in pkglist:
516
 
                if basecmd == 'install' and is_available(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos):
517
 
                    nothing_to_do = False
518
 
                    break
519
 
                    
520
 
                if basecmd == 'update' and is_update(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=en_repos):
521
 
                    nothing_to_do = False
522
 
                    break
523
 
                    
524
 
            if nothing_to_do:
525
 
                res['results'].append("All packages providing %s are up to date" % spec)
526
 
                continue
527
 
 
528
 
            pkg = spec
529
 
 
530
 
        cmd = yum_basecmd + [basecmd, pkg]
531
 
 
532
 
        if module.check_mode:
533
 
            return module.exit_json(changed=True)
534
 
 
535
 
        rc, out, err = module.run_command(cmd)
536
 
 
537
 
        res['rc'] += rc
538
 
        res['results'].append(out)
539
 
        res['msg'] += err
540
 
 
541
 
        # FIXME if it is - update it and check to see if it applied
542
 
        # check to see if there is no longer an update available for the pkgspec
543
 
 
544
 
        if rc:
545
 
            res['failed'] = True
546
 
        else:
547
 
            res['changed'] = True
548
 
 
549
 
    module.exit_json(**res)
550
 
 
551
 
def ensure(module, state, pkgspec, conf_file, enablerepo, disablerepo):
552
 
 
553
 
    # take multiple args comma separated
554
 
    items = pkgspec.split(',')
555
 
 
556
 
    yum_basecmd = [yumbin, '-d', '1', '-y']
557
 
 
558
 
        
559
 
    if not repoquery:
560
 
        repoq = None
561
 
    else:
562
 
        repoq = [repoquery, '--show-duplicates', '--plugins', '--quiet', '-q']
563
 
 
564
 
    if conf_file and os.path.exists(conf_file):
565
 
        yum_basecmd += ['-c', conf_file]
566
 
        if repoq:
567
 
            repoq += ['-c', conf_file]
568
 
 
569
 
    dis_repos =[]
570
 
    en_repos = []
571
 
    if disablerepo:
572
 
        dis_repos = disablerepo.split(',')
573
 
    if enablerepo:
574
 
        en_repos = enablerepo.split(',')
575
 
 
576
 
    for repoid in en_repos:
577
 
        r_cmd = ['--enablerepo', repoid]
578
 
        yum_basecmd.extend(r_cmd)
579
 
        
580
 
    for repoid in dis_repos:
581
 
        r_cmd = ['--disablerepo', repoid]
582
 
        yum_basecmd.extend(r_cmd)
583
 
 
584
 
    if state in ['installed', 'present', 'latest']:
585
 
        my = yum_base(conf_file)
586
 
        try:
587
 
            for r in dis_repos:
588
 
                my.repos.disableRepo(r)
589
 
 
590
 
            for r in en_repos:
591
 
                try:
592
 
                    my.repos.enableRepo(r)
593
 
                    rid = my.repos.getRepo(r)
594
 
                    a = rid.repoXML.repoid
595
 
                except yum.Errors.YumBaseError, e:
596
 
                    module.fail_json(msg="Error setting/accessing repo %s: %s" % (r, e))
597
 
        except yum.Errors.YumBaseError, e:
598
 
            module.fail_json(msg="Error accessing repos: %s" % e)
599
 
 
600
 
    if state in ['installed', 'present']:
601
 
        install(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
602
 
    elif state in ['removed', 'absent']:
603
 
        remove(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
604
 
    elif state == 'latest':
605
 
        latest(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
606
 
 
607
 
    # should be caught by AnsibleModule argument_spec
608
 
    return dict(changed=False, failed=True, results='', errors='unexpected state')
609
 
 
610
 
def main():
611
 
 
612
 
    # state=installed name=pkgspec
613
 
    # state=removed name=pkgspec
614
 
    # state=latest name=pkgspec
615
 
    #
616
 
    # informational commands:
617
 
    #   list=installed
618
 
    #   list=updates
619
 
    #   list=available
620
 
    #   list=repos
621
 
    #   list=pkgspec
622
 
 
623
 
    module = AnsibleModule(
624
 
        argument_spec = dict(
625
 
            name=dict(aliases=['pkg']),
626
 
            # removed==absent, installed==present, these are accepted as aliases
627
 
            state=dict(default='installed', choices=['absent','present','installed','removed','latest']),
628
 
            enablerepo=dict(),
629
 
            disablerepo=dict(),
630
 
            list=dict(),
631
 
            conf_file=dict(default=None),
632
 
        ),
633
 
        required_one_of = [['name','list']],
634
 
        mutually_exclusive = [['name','list']],
635
 
        supports_check_mode = True
636
 
    )
637
 
 
638
 
    params = module.params
639
 
 
640
 
    if params['list']:
641
 
        if not repoquery:
642
 
            module.fail_json(msg="repoquery is required to use list= with this module. Please install the yum-utils package.")
643
 
        results = dict(results=list_stuff(module, params['conf_file'], params['list']))
644
 
        module.exit_json(**results)
645
 
 
646
 
    else:
647
 
        pkg = params['name']
648
 
        state = params['state']
649
 
        enablerepo = params.get('enablerepo', '')
650
 
        disablerepo = params.get('disablerepo', '')
651
 
        res = ensure(module, state, pkg, params['conf_file'], enablerepo, disablerepo)
652
 
        module.fail_json(msg="we should never get here unless this all failed", **res)
653
 
 
654
 
# this is magic, see lib/ansible/module_common.py
655
 
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
656
 
main()
657