2
# -*- coding: utf-8 -*-
4
# (c) 2012, Red Hat, Inc
5
# Written by Seth Vidal <skvidal at fedoraproject.org>
7
# This file is part of Ansible
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.
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.
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/>.
31
short_description: Manages packages with the I(yum) package manager
33
- Will install, upgrade, remove, and list packages with the I(yum) package manager.
37
- package name, or package specifier with version, like C(name-1.0).
43
- various non-idempotent commands for usage with C(/usr/bin/ansible) and I(not) playbooks. See examples.
48
- whether to install (C(present), C(latest)), or remove (C(absent)) a package.
50
choices: [ "present", "latest", "absent" ]
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 ','
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 ','
73
- code: yum name=httpd state=latest
74
- code: yum name=httpd state=removed
75
- code: yum name=httpd enablerepo=testing state=installed
77
# informational: requirements for nodes
78
requirements: [ yum, rpm ]
82
def_qf = "%{name}-%{version}-%{release}.%{arch}"
84
repoquery='/usr/bin/repoquery'
85
if not os.path.exists(repoquery):
90
def yum_base(conf_file=None, cachedir=False):
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'):
101
cachedir = yum.misc.getCacheDir()
102
my.repos.setCacheDir(cachedir)
109
if hasattr(po, 'ui_nevra'):
112
return '%s-%s-%s.%s' % (po.name, po.version, po.release, po.arch)
114
def is_installed(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
120
my = yum_base(conf_file)
122
my.repos.enableRepo(rid)
123
for rid in dis_repos:
124
my.repos.disableRepo(rid)
126
e,m,u = my.rpmdb.matchPackageNames([pkgspec])
129
pkgs.extend(my.returnInstalledPackagesByDep(pkgspec))
131
module.fail_json(msg="Failure talking to yum: %s" % e)
133
return [ po_to_nevra(p) for p in pkgs ]
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:
143
return [ p for p in out.split('\n') if p.strip() ]
145
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
149
def is_available(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
155
my = yum_base(conf_file)
157
my.repos.enableRepo(rid)
158
for rid in dis_repos:
159
my.repos.disableRepo(rid)
161
e,m,u = my.pkgSack.matchPackageNames([pkgspec])
164
pkgs.extend(my.returnPackagesByDep(pkgspec))
166
module.fail_json(msg="Failure talking to yum: %s" % e)
168
return [ po_to_nevra(p) for p in pkgs ]
171
myrepoq = list(repoq)
173
for repoid in en_repos:
174
r_cmd = ['--enablerepo', repoid]
175
myrepoq.extend(r_cmd)
177
for repoid in dis_repos:
178
r_cmd = ['--disablerepo', repoid]
179
myrepoq.extend(r_cmd)
181
cmd = myrepoq + ["--qf", qf, pkgspec]
182
rc,out,err = module.run_command(cmd)
184
return [ p for p in out.split('\n') if p.strip() ]
186
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
191
def is_update(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
200
my = yum_base(conf_file)
202
my.repos.enableRepo(rid)
203
for rid in dis_repos:
204
my.repos.disableRepo(rid)
206
pkgs = my.returnPackagesByDep(pkgspec) + my.returnInstalledPackagesByDep(pkgspec)
208
e,m,u = my.pkgSack.matchPackageNames([pkgspec])
210
updates = my.doPackageLists(pkgnarrow='updates').updates
212
module.fail_json(msg="Failure talking to yum: %s" % e)
218
return set([ po_to_nevra(p) for p in retpkgs ])
221
myrepoq = list(repoq)
222
for repoid in en_repos:
223
r_cmd = ['--enablerepo', repoid]
224
myrepoq.extend(r_cmd)
226
for repoid in dis_repos:
227
r_cmd = ['--disablerepo', repoid]
228
myrepoq.extend(r_cmd)
231
cmd = myrepoq + ["--pkgnarrow=updates", "--qf", qf, pkgspec]
232
rc,out,err = module.run_command(cmd)
235
return set([ p for p in out.split('\n') if p.strip() ])
237
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
241
def what_provides(module, repoq, req_spec, conf_file, qf=def_qf, en_repos=[], dis_repos=[]):
247
my = yum_base(conf_file)
249
my.repos.enableRepo(rid)
250
for rid in dis_repos:
251
my.repos.disableRepo(rid)
253
pkgs = my.returnPackagesByDep(req_spec) + my.returnInstalledPackagesByDep(req_spec)
255
e,m,u = my.pkgSack.matchPackageNames([req_spec])
258
e,m,u = my.rpmdb.matchPackageNames([req_spec])
262
module.fail_json(msg="Failure talking to yum: %s" % e)
264
return set([ po_to_nevra(p) for p in pkgs ])
267
myrepoq = list(repoq)
268
for repoid in en_repos:
269
r_cmd = ['--enablerepo', repoid]
270
myrepoq.extend(r_cmd)
272
for repoid in dis_repos:
273
r_cmd = ['--disablerepo', repoid]
274
myrepoq.extend(r_cmd)
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:
282
pkgs = set([ p for p in out.split('\n') if p.strip() ])
284
pkgs = is_installed(module, repoq, req_spec, conf_file, qf=qf)
287
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
291
def local_nvra(module, path):
292
"""return nvra of a local rpm passed in"""
294
cmd = ['/bin/rpm', '-qp' ,'--qf',
295
'%{name}-%{version}-%{release}.%{arch}\n', path ]
296
rc, out, err = module.run_command(cmd)
299
nvra = out.split('\n')[0]
302
def pkg_to_dict(pkgstr):
305
n,e,v,r,a,repo = pkgstr.split('|')
307
return {'error_parsing': pkgstr}
316
'nevra': '%s:%s-%s-%s.%s' % (e,n,v,r,a)
319
if repo == 'installed':
320
d['yumstate'] = 'installed'
322
d['yumstate'] = 'available'
326
def repolist(module, repoq, qf="%{repoid}"):
328
cmd = repoq + ["--qf", qf, "-a"]
329
rc,out,err = module.run_command(cmd)
332
ret = set([ p for p in out.split('\n') if p.strip() ])
335
def list_stuff(module, conf_file, stuff):
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]
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() ]
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() ]
353
def install(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
359
res['changed'] = False
364
# check if pkgspec is installed (if possible for idempotence)
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)
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
379
elif spec.startswith('@'):
380
# complete wild ass guess b/c it's a group
383
# range requires or file-requires or pkgname :(
385
# look up what pkgs provide this
386
pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
388
res['msg'] += "No Package matching '%s' found available, installed or updated" % spec
389
module.fail_json(**res)
391
# if any of them are installed
396
if is_installed(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos):
398
res['results'].append('%s providing %s is already installed' % (this, spec))
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.
407
if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
409
res['results'].append('package providing %s is already installed' % (spec))
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
418
cmd = yum_basecmd + ['install', pkg]
420
if module.check_mode:
421
module.exit_json(changed=True)
423
rc, out, err = module.run_command(cmd)
426
res['results'].append(out)
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
433
res['changed'] = True
435
module.exit_json(**res)
438
def remove(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
443
res['changed'] = False
448
# group remove - this is doom on a stick
449
if pkg.startswith('@'):
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)
456
# run an actual yum transaction
457
cmd = yum_basecmd + ["remove", pkg]
459
if module.check_mode:
460
module.exit_json(changed=True)
462
rc, out, err = module.run_command(cmd)
465
res['results'].append(out)
468
# compile the results into one batch. If anything is changed
470
# at the end - if we've end up failed then fail out of the rest
473
# at this point we should check to see if the pkg is no longer present
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
480
module.fail_json(**res)
483
module.fail_json(**res)
485
module.exit_json(**res)
487
def latest(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
492
res['changed'] = False
500
if spec.startswith('@'):
502
# dep/pkgname - find it
504
if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
509
pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
511
res['msg'] += "No Package matching '%s' found available, installed or updated" % spec
512
module.fail_json(**res)
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
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
525
res['results'].append("All packages providing %s are up to date" % spec)
530
cmd = yum_basecmd + [basecmd, pkg]
532
if module.check_mode:
533
return module.exit_json(changed=True)
535
rc, out, err = module.run_command(cmd)
538
res['results'].append(out)
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
547
res['changed'] = True
549
module.exit_json(**res)
551
def ensure(module, state, pkgspec, conf_file, enablerepo, disablerepo):
553
# take multiple args comma separated
554
items = pkgspec.split(',')
556
yum_basecmd = [yumbin, '-d', '1', '-y']
562
repoq = [repoquery, '--show-duplicates', '--plugins', '--quiet', '-q']
564
if conf_file and os.path.exists(conf_file):
565
yum_basecmd += ['-c', conf_file]
567
repoq += ['-c', conf_file]
572
dis_repos = disablerepo.split(',')
574
en_repos = enablerepo.split(',')
576
for repoid in en_repos:
577
r_cmd = ['--enablerepo', repoid]
578
yum_basecmd.extend(r_cmd)
580
for repoid in dis_repos:
581
r_cmd = ['--disablerepo', repoid]
582
yum_basecmd.extend(r_cmd)
584
if state in ['installed', 'present', 'latest']:
585
my = yum_base(conf_file)
588
my.repos.disableRepo(r)
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)
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)
607
# should be caught by AnsibleModule argument_spec
608
return dict(changed=False, failed=True, results='', errors='unexpected state')
612
# state=installed name=pkgspec
613
# state=removed name=pkgspec
614
# state=latest name=pkgspec
616
# informational commands:
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']),
631
conf_file=dict(default=None),
633
required_one_of = [['name','list']],
634
mutually_exclusive = [['name','list']],
635
supports_check_mode = True
638
params = module.params
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)
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)
654
# this is magic, see lib/ansible/module_common.py
655
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>