lvg 8.39 KB
Newer Older
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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2013, Alexander Bulimov <lazywolf0@gmail.com>
# based on lvol module by Jeroen Hoekx <jeroen.hoekx@dsquare.be>
#
# 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/>.

DOCUMENTATION = '''
---
author: Alexander Bulimov
module: lvg
short_description: Configure LVM volume groups
description:
28
  - This module creates, removes or resizes volume groups.
29 30 31 32 33 34
version_added: "1.1"
options:
  vg:
    description:
    - The name of the volume group.
    required: true
35
  pvs:
36
    description:
37 38
    - List of comma-separated devices to use as physical devices in this volume group. Required when creating or resizing volume group.
    required: false
39 40
  pesize:
    description:
41
    - The size of the physical extent in megabytes. Must be a power of 2.
42 43
    default: 4
    required: false
44 45 46 47 48 49 50 51
  state:
    choices: [ "present", "absent" ]
    default: present
    description:
    - Control if the volume group exists.
    required: false
  force:
    choices: [ "yes", "no" ]
52
    default: "no"
53
    description:
54
    - If yes, allows to remove volume group with logical volumes.
55 56
    required: false
notes:
57
  - module does not modify PE size for already present volume group
58 59
'''

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
EXAMPLES = '''
# Create a volume group on top of /dev/sda1 with physical extent size = 32MB.
- lvg:  vg=vg.services pvs=/dev/sda1 pesize=32

# Create or resize a volume group on top of /dev/sdb1 and /dev/sdc5. 
# If, for example, we already have VG vg.services on top of /dev/sdb1,
# this VG will be extended by /dev/sdc5.  Or if vg.services was created on
# top of /dev/sda5, we first extend it with /dev/sdb1 and /dev/sdc5,
# and then reduce by /dev/sda5.
- lvg: vg=vg.services pvs=/dev/sdb1,/dev/sdc5

# Remove a volume group with name vg.services.
- lvg: vg=vg.services state=absent
'''

75 76 77 78 79 80 81 82 83 84 85
def parse_vgs(data):
    vgs = []
    for line in data.splitlines():
        parts = line.strip().split(';')
        vgs.append({
            'name': parts[0],
            'pv_count': int(parts[1]),
            'lv_count': int(parts[2]),
        })
    return vgs

86 87 88 89 90 91 92 93 94 95
def parse_pvs(data):
    pvs = []
    for line in data.splitlines():
        parts = line.strip().split(';')
        pvs.append({
            'name': parts[0],
            'vg_name': parts[1],
        })
    return pvs

96 97 98 99
def main():
    module = AnsibleModule(
        argument_spec = dict(
            vg=dict(required=True),
100 101
            pvs=dict(type='list'),
            pesize=dict(type='int', default=4),
102
            state=dict(choices=["absent", "present"], default='present'),
103
            force=dict(type='bool', default='no'),
104 105 106 107 108
        ),
        supports_check_mode=True,
    )

    vg = module.params['vg']
109 110
    state = module.params['state']
    force = module.boolean(module.params['force'])
111
    pesize = module.params['pesize']
112

113 114 115
    if module.params['pvs']:
        dev_string = ' '.join(module.params['pvs'])
        dev_list = module.params['pvs']
116
    elif state == 'present':
117
        module.fail_json(msg="No physical volumes given.")
118

119 120

    
121
    if state=='present':
122
        ### check given devices
123 124
        for test_dev in dev_list:
            if not os.path.exists(test_dev):
125
                module.fail_json(msg="Device %s not found."%test_dev)
126

127
        ### get pv list
128 129
        pvs_cmd = module.get_bin_path('pvs', True)
        rc,current_pvs,err = module.run_command("%s --noheadings -o pv_name,vg_name --separator ';'" % pvs_cmd)
130 131 132 133 134
        if rc != 0:
            module.fail_json(msg="Failed executing pvs command.",rc=rc, err=err)

        ### check pv for devices
        pvs = parse_pvs(current_pvs)
135
        used_pvs = [ pv for pv in pvs if pv['name'] in dev_list and pv['vg_name'] and pv['vg_name'] != vg ]
136
        if used_pvs:
137
            module.fail_json(msg="Device %s is already in %s volume group."%(used_pvs[0]['name'],used_pvs[0]['vg_name']))
138

139 140
    vgs_cmd = module.get_bin_path('vgs', True)
    rc,current_vgs,err = module.run_command("%s --noheadings -o vg_name,pv_count,lv_count --separator ';'" % vgs_cmd)
141 142

    if rc != 0:
143
        module.fail_json(msg="Failed executing vgs command.",rc=rc, err=err)
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    changed = False

    vgs = parse_vgs(current_vgs)

    for test_vg in vgs:
        if test_vg['name'] == vg:
            this_vg = test_vg
            break
    else:
        this_vg = None

    if this_vg is None:
        if state == 'present':
            ### create VG
            if module.check_mode:
                changed = True
            else:
162
                ### create PV
163
                pvcreate_cmd = module.get_bin_path('pvcreate', True)
164
                for current_dev in dev_list:
165
                    rc,_,err = module.run_command("%s %s"%(pvcreate_cmd,current_dev))
166 167 168 169
                    if rc == 0:
                        changed = True
                    else:
                        module.fail_json(msg="Creating physical volume '%s' failed"%current_dev, rc=rc, err=err)
170 171
                vgcreate_cmd = module.get_bin_path('vgcreate')
                rc,_,err = module.run_command("%s -s %s %s %s"%(vgcreate_cmd, pesize, vg, dev_string))
172 173 174
                if rc == 0:
                    changed = True
                else:
175
                    module.fail_json(msg="Creating volume group '%s' failed"%vg, rc=rc, err=err)
176 177 178 179 180
    else:
        if state == 'absent':
            if module.check_mode:
                module.exit_json(changed=True)
            else:
181
                if this_vg['lv_count'] == 0 or force:
182
                    ### remove VG
183 184
                    vgremove_cmd = module.get_bin_path('vgremove', True)
                    rc,_,err = module.run_command("%s --force %s" % (vgremove_cmd, vg))
185 186 187 188 189 190 191
                    if rc == 0:
                        module.exit_json(changed=True)
                    else:
                        module.fail_json(msg="Failed to remove volume group %s"%(vg),rc=rc, err=err)
                else:
                    module.fail_json(msg="Refuse to remove non-empty volume group %s without force=yes"%(vg))

192
        ### resize VG
193
        current_devs = [ pv['name'] for pv in pvs if pv['vg_name'] == vg ]
194 195
        devs_to_remove = list(set(current_devs) - set(dev_list))
        devs_to_add = list(set(dev_list) - set(current_devs))
196 197

        if devs_to_add or devs_to_remove:
198 199 200
            if module.check_mode:
                changed = True
            else:
201 202
                if devs_to_add:
                    devs_to_add_string = ' '.join(devs_to_add)
203
                    ### create PV
204
                    pvcreate_cmd = module.get_bin_path('pvcreate', True)
205
                    for current_dev in devs_to_add:
206
                        rc,_,err = module.run_command("%s %s" % (pvcreate_cmd, current_dev))
207 208 209 210
                        if rc == 0:
                            changed = True
                        else:
                            module.fail_json(msg="Creating physical volume '%s' failed"%current_dev, rc=rc, err=err)
211
                    ### add PV to our VG
212
                    vgextend_cmd = module.get_bin_path('vgextend', True)
Brian Coca committed
213
                    rc,_,err = module.run_command("%s %s %s"%(vgextend_cmd, vg, devs_to_add_string))
214 215 216 217
                    if rc == 0:
                        changed = True
                    else:
                        module.fail_json(msg="Unable to extend %s by %s."%(vg, devs_to_add_string),rc=rc,err=err)
218

219 220 221
                ### remove some PV from our VG
                if devs_to_remove:
                    devs_to_remove_string = ' '.join(devs_to_remove)
222 223
                    vgreduce_cmd = module.get_bin_path('vgreduce', True)
                    rc,_,err = module.run_command("%s --force %s %s" % (vgreduce_cmd, vg, devs_to_remove_string))
224 225 226 227 228
                    if rc == 0:
                        changed = True
                    else:
                        module.fail_json(msg="Unable to reduce %s by %s."%(vg, devs_to_remove_string),rc=rc,err=err)

229 230
    module.exit_json(changed=changed)

231
# import module snippets
232
from ansible.module_utils.basic import *
233
main()