summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/vmware/vmware_portgroup.py
blob: 532a007483079fa2975e650d02bbff717479bdf1 (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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2015, Joseph Callen <jcallen () csc.com>
# Copyright: (c) 2017-18, Ansible Project
# Copyright: (c) 2017-18, Abhijeet Kasurde <akasurde@redhat.com>
# 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
__metaclass__ = type

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: vmware_portgroup
short_description: Create a VMware portgroup
description:
    - Create a VMware portgroup on given host/s or hosts of given cluster
version_added: 2.0
author:
- Joseph Callen (@jcpowermac)
- Russell Teague (@mtnbikenc)
- Abhijeet Kasurde (@akasurde) <akasurde@redhat.com>
notes:
    - Tested on vSphere 5.5, 6.5
requirements:
    - "python >= 2.6"
    - PyVmomi
options:
    switch_name:
        description:
            - vSwitch to modify.
        required: True
    portgroup_name:
        description:
            - Portgroup name to add.
        required: True
    vlan_id:
        description:
            - VLAN ID to assign to portgroup.
        required: True
    network_policy:
        description:
            - Network policy specifies layer 2 security settings for a
              portgroup such as promiscuous mode, where guest adapter listens
              to all the packets, MAC address changes and forged transmits.
            - Dict which configures the different security values for portgroup.
            - 'Valid attributes are:'
            - '- C(promiscuous_mode) (bool): indicates whether promiscuous mode is allowed. (default: false)'
            - '- C(forged_transmits) (bool): indicates whether forged transmits are allowed. (default: false)'
            - '- C(mac_changes) (bool): indicates whether mac changes are allowed. (default: false)'
        required: False
        version_added: "2.2"
        default: {
            mac_changes: false,
            promiscuous_mode: false,
            forged_transmits: false,
        }
    cluster_name:
        description:
            - Name of cluster name for host membership.
            - Portgroup will be created on all hosts of the given cluster.
            - This option is required if C(hosts) is not specified.
        version_added: "2.5"
    hosts:
        description:
            - List of name of host or hosts on which portgroup needs to be added.
            - This option is required if C(cluster_name) is not specified.
        aliases: [ esxi_hostname ]
        version_added: "2.5"
    state:
        description:
            - Determines if the portgroup should be present or not.
        choices:
            - 'present'
            - 'absent'
        version_added: '2.5'
        default: present
extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = r'''
- name: Add Management Network VM Portgroup
  vmware_portgroup:
    hostname: esxi_hostname
    username: esxi_username
    password: esxi_password
    switch_name: vswitch_name
    portgroup_name: portgroup_name
    vlan_id: vlan_id

- name: Add Portgroup with Promiscuous Mode Enabled
  vmware_portgroup:
    hostname: esxi_hostname
    username: esxi_username
    password: esxi_password
    switch_name: vswitch_name
    portgroup_name: portgroup_name
    network_policy:
        promiscuous_mode: True

- name: Add Management Network VM Portgroup to specific hosts
  vmware_portgroup:
    hostname: vCenter_hostname
    username: esxi_username
    password: esxi_password
    hosts: [esxi_hostname_one]
    switch_name: vswitch_name
    portgroup_name: portgroup_name
    vlan_id: vlan_id

- name: Add Management Network VM Portgroup to all hosts in a cluster
  vmware_portgroup:
    hostname: vCenter_hostname
    username: esxi_username
    password: esxi_password
    cluster_name: rh_engineering
    switch_name: vswitch_name
    portgroup_name: portgroup_name
    vlan_id: vlan_id

- name: Remove Management Network VM Portgroup to all hosts in a cluster
  vmware_portgroup:
    hostname: vCenter_hostname
    username: esxi_username
    password: esxi_password
    cluster_name: rh_engineering
    switch_name: vswitch_name
    portgroup_name: portgroup_name
    vlan_id: vlan_id
    state: absent
'''

RETURN = r'''
result:
    description: metadata about the portgroup
    returned: always
    type: dict
    sample: {
                "esxi01.example.com": {
                    "portgroup_name": "pg0010",
                    "switch_name": "vswitch_0001",
                    "vlan_id": 1
                }
            }
'''


try:
    from pyVmomi import vim, vmodl
except ImportError:
    pass

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
from ansible.module_utils._text import to_native


class PyVmomiHelper(PyVmomi):
    def __init__(self, module):
        super(PyVmomiHelper, self).__init__(module)

        hosts = self.params['hosts']
        cluster = self.params['cluster_name']
        self.portgroup_name = self.params['portgroup_name']
        self.switch_name = self.params['switch_name']
        self.vlan_id = self.params['vlan_id']
        self.promiscuous_mode = self.params['network_policy'].get('promiscuous_mode')
        self.forged_transmits = self.params['network_policy'].get('forged_transmits')
        self.mac_changes = self.params['network_policy'].get('mac_changes')
        self.network_policy = self.create_network_policy()
        self.state = self.params['state']
        self.host_obj_list = self.get_all_host_objs(cluster_name=cluster, esxi_host_name=hosts)

    def process_state(self):
        """
        Function to manage state
        """
        if self.state == 'present':
            self.add_hosts_port_group()
        elif self.state == 'absent':
            self.remove_hosts_port_group()

    # Get
    def get_port_group_by_name(self, host_system, portgroup_name, vswitch_name):
        """
        Function to get specific port group by given name
        Args:
            host_system: Name of Host System
            portgroup_name: Name of Port Group
            vswitch_name: Name of vSwitch

        Returns: List of port groups by given specifications

        """
        pgs_list = self.get_all_port_groups_by_host(host_system=host_system)
        desired_pgs = []
        for pg in pgs_list:
            if pg.spec.name == portgroup_name and pg.spec.vswitchName == vswitch_name:
                desired_pgs.append(pg)
        return desired_pgs

    @staticmethod
    def check_network_policy_diff(current_policy, desired_policy):
        """
        Function to find difference between existing network policy and user given network policy
        Args:
            current_policy: Current network policy
            desired_policy: User defined network policy

        Returns: True if difference found, False if not.

        """
        ret = False
        if (current_policy.security.allowPromiscuous != desired_policy.security.allowPromiscuous) or \
                (current_policy.security.forgedTransmits != desired_policy.security.forgedTransmits) or \
                (current_policy.security.macChanges != desired_policy.security.macChanges):
            ret = True
        return ret

    # Add
    def add_hosts_port_group(self):
        """
        Function to add port group to given hosts
        """
        results = dict(changed=False, result=dict())
        host_change_list = []
        for host in self.host_obj_list:
            change = False
            results['result'][host.name] = dict(portgroup_name=self.portgroup_name,
                                                vlan_id=self.vlan_id,
                                                switch_name=self.switch_name)
            change = self.create_host_port_group(host, self.portgroup_name, self.vlan_id, self.switch_name, self.network_policy)
            host_change_list.append(change)
        if any(host_change_list):
            results['changed'] = True
        self.module.exit_json(**results)

    def create_host_port_group(self, host_system, portgroup_name, vlan_id, vswitch_name, network_policy):
        """
        Function to create/update portgroup on given host using portgroup specifications
        Args:
            host_system: Name of Host System
            portgroup_name: Name of Portgroup
            vlan_id: The VLAN ID for ports using this port group.
            vswitch_name: Name of vSwitch Name
            network_policy: Network policy object
        """
        desired_pgs = self.get_port_group_by_name(host_system=host_system,
                                                  portgroup_name=portgroup_name,
                                                  vswitch_name=vswitch_name)

        port_group = vim.host.PortGroup.Config()
        port_group.spec = vim.host.PortGroup.Specification()

        if not desired_pgs:
            # Add new portgroup
            port_group.spec.name = portgroup_name
            port_group.spec.vlanId = vlan_id
            port_group.spec.vswitchName = vswitch_name
            port_group.spec.policy = network_policy

            try:
                host_system.configManager.networkSystem.AddPortGroup(portgrp=port_group.spec)
                self.changed = True
            except vim.fault.AlreadyExists as e:
                # To match with other vmware_* modules if portgroup
                # exists, we proceed, as user may want idempotency
                self.changed = False
            except vim.fault.NotFound as not_found:
                self.module.fail_json(msg="Failed to add Portgroup as vSwitch"
                                          " was not found: %s" % to_native(not_found.msg))
            except vim.fault.HostConfigFault as host_config_fault:
                self.module.fail_json(msg="Failed to add Portgroup due to host system"
                                          " configuration failure : %s" % to_native(host_config_fault.msg))
            except vmodl.fault.InvalidArgument as invalid_argument:
                self.module.fail_json(msg="Failed to add Portgroup as VLAN id was not"
                                          " correct as per specifications: %s" % to_native(invalid_argument.msg))
            except Exception as generic_exception:
                self.module.fail_json(msg="Failed to add Portgroup due to generic"
                                          " exception : %s" % to_native(generic_exception))
        else:
            self.changed = False
            # Change portgroup
            if desired_pgs[0].spec.vlanId != vlan_id:
                port_group.spec.vlanId = vlan_id
                self.changed = True
            if self.check_network_policy_diff(desired_pgs[0].spec.policy, network_policy):
                port_group.spec.policy = network_policy
                self.changed = True

            if self.changed:
                try:
                    host_system.configManager.networkSystem.UpdatePortGroup(pgName=self.portgroup_name,
                                                                            portgrp=port_group.spec)
                    self.changed = True
                except vim.fault.AlreadyExists as e:
                    # To match with other vmware_* modules if portgroup
                    # exists, we proceed, as user may want idempotency
                    self.changed = False
                except vim.fault.NotFound as not_found:
                    self.module.fail_json(msg="Failed to update Portgroup as"
                                              " vSwitch was not found: %s" % to_native(not_found.msg))
                except vim.fault.HostConfigFault as host_config_fault:
                    self.module.fail_json(msg="Failed to update Portgroup due to host"
                                              " system configuration failure : %s" % to_native(host_config_fault.msg))
                except vmodl.fault.InvalidArgument as invalid_argument:
                    self.module.fail_json(msg="Failed to update Portgroup as VLAN id was not"
                                              " correct as per specifications: %s" % to_native(invalid_argument.msg))
                except Exception as generic_exception:
                    self.module.fail_json(msg="Failed to update Portgroup due to generic"
                                              " exception : %s" % to_native(generic_exception))
        return self.changed

    def create_network_policy(self):
        """
        Function to create Network policy
        Returns: Network policy object
        """
        security_policy = vim.host.NetworkPolicy.SecurityPolicy()
        if self.promiscuous_mode:
            security_policy.allowPromiscuous = self.promiscuous_mode
        if self.forged_transmits:
            security_policy.forgedTransmits = self.forged_transmits
        if self.mac_changes:
            security_policy.macChanges = self.mac_changes
        network_policy = vim.host.NetworkPolicy(security=security_policy)
        return network_policy

    def remove_hosts_port_group(self):
        """
        Function to remove port group from given host
        """
        results = dict(changed=False, result=dict())
        host_change_list = []
        for host in self.host_obj_list:
            change = False
            results['result'][host.name] = dict(portgroup_name=self.portgroup_name,
                                                vlan_id=self.vlan_id,
                                                switch_name=self.switch_name)
            change = self.remove_host_port_group(host_system=host,
                                                 portgroup_name=self.portgroup_name,
                                                 vswitch_name=self.switch_name)
            host_change_list.append(change)
        if any(host_change_list):
            results['changed'] = True
        self.module.exit_json(**results)

    def remove_host_port_group(self, host_system, portgroup_name, vswitch_name):
        """
        Function to remove port group depending upon host system, port group name and vswitch name
        Args:
            host_system: Name of Host System
            portgroup_name: Name of Portgroup
            vswitch_name: Name of vSwitch

        """
        changed = False
        desired_pgs = self.get_port_group_by_name(host_system=host_system,
                                                  portgroup_name=portgroup_name,
                                                  vswitch_name=vswitch_name)
        if desired_pgs:
            try:
                host_system.configManager.networkSystem.RemovePortGroup(pgName=self.portgroup_name)
                changed = True
            except vim.fault.NotFound as not_found:
                self.module.fail_json(msg="Failed to remove Portgroup as it was"
                                          " not found: %s" % to_native(not_found.msg))
            except vim.fault.ResourceInUse as resource_in_use:
                self.module.fail_json(msg="Failed to remove Portgroup as it is"
                                          " in use: %s" % to_native(resource_in_use.msg))
            except vim.fault.HostConfigFault as host_config_fault:
                self.module.fail_json(msg="Failed to remove Portgroup due to configuration"
                                          " failures: %s" % to_native(host_config_fault.msg))
            except Exception as generic_exception:
                self.module.fail_json(msg="Failed to remove Portgroup due to generic"
                                          " exception : %s" % to_native(generic_exception))
        return changed


def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(dict(
        portgroup_name=dict(required=True, type='str'),
        switch_name=dict(required=True, type='str'),
        vlan_id=dict(required=True, type='int'),
        hosts=dict(type='list', aliases=['esxi_hostname']),
        cluster_name=dict(type='str'),
        state=dict(type='str', choices=['present', 'absent'], default='present'),
        network_policy=dict(type='dict',
                            options=dict(
                                promiscuous_mode=dict(type='bool'),
                                forged_transmits=dict(type='bool'),
                                mac_changes=dict(type='bool'),
                            ),
                            default=dict(
                                promiscuous_mode=False,
                                forged_transmits=False,
                                mac_changes=False,
                            )
                            ),
    )
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False,
                           required_one_of=[
                               ['cluster_name', 'hosts'],
                           ]
                           )

    try:
        pyv = PyVmomiHelper(module)
        pyv.process_state()
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=to_native(runtime_fault.msg))
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=to_native(method_fault.msg))
    except Exception as e:
        module.fail_json(msg=to_native(e))


if __name__ == '__main__':
    main()