summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/vmware/plugins/modules/vmware_custom_attribute.py
blob: 2d33ba254e9d0ce173d13cbcc91f1f5b692251f3 (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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = r'''
---
module: vmware_custom_attribute
version_added: '3.2.0'
short_description: Manage custom attributes definitions
description:
  - This module can be used to add and remove custom attributes definitions for various vSphere objects.
author:
  - Mario Lenz (@mariolenz)
options:
  custom_attribute:
    description:
      - Name of the custom attribute.
    required: true
    type: str
  object_type:
    description:
      - Type of the object the custom attribute is associated with.
    type: str
    choices:
      - Cluster
      - Datacenter
      - Datastore
      - DistributedVirtualPortgroup
      - DistributedVirtualSwitch
      - Folder
      - Global
      - HostSystem
      - ResourcePool
      - VirtualMachine
    required: true
  state:
    description:
      - Manage definition of custom attributes.
      - If set to V(present) and definition not present, then custom attribute definition is created.
      - If set to V(present) and definition is present, then no action taken.
      - If set to V(absent) and definition is present, then custom attribute definition is removed.
      - If set to V(absent) and definition is absent, then no action taken.
    default: 'present'
    choices: ['present', 'absent']
    type: str
extends_documentation_fragment:
- community.vmware.vmware.documentation

'''

EXAMPLES = r'''
- name: Add VM Custom Attribute Definition
  community.vmware.vmware_custom_attribute:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    state: present
    object_type: VirtualMachine
    custom_attribute: custom_attr_def_1
  delegate_to: localhost
  register: defs

- name: Remove VM Custom Attribute Definition
  community.vmware.vmware_custom_attribute:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    state: absent
    object_type: VirtualMachine
    custom_attribute: custom_attr_def_1
  delegate_to: localhost
  register: defs
'''

RETURN = r'''
'''

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, vmware_argument_spec

try:
    from pyVmomi import vim
except ImportError:
    pass


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

        if not self.is_vcenter():
            self.module.fail_json(msg="You have to connect to a vCenter server!")

        object_types_map = {
            'Cluster': vim.ClusterComputeResource,
            'Datacenter': vim.Datacenter,
            'Datastore': vim.Datastore,
            'DistributedVirtualPortgroup': vim.DistributedVirtualPortgroup,
            'DistributedVirtualSwitch': vim.DistributedVirtualSwitch,
            'Folder': vim.Folder,
            'Global': None,
            'HostSystem': vim.HostSystem,
            'ResourcePool': vim.ResourcePool,
            'VirtualMachine': vim.VirtualMachine
        }

        self.object_type = object_types_map[self.params['object_type']]

    def remove_custom_def(self, field):
        changed = False
        for x in self.custom_field_mgr:
            if x.name == field and x.managedObjectType == self.object_type:
                changed = True
                if not self.module.check_mode:
                    self.content.customFieldsManager.RemoveCustomFieldDef(key=x.key)
                break
        return {'changed': changed, 'failed': False}

    def add_custom_def(self, field):
        changed = False
        found = False
        for x in self.custom_field_mgr:
            if x.name == field and x.managedObjectType == self.object_type:
                found = True
                break

        if not found:
            changed = True
            if not self.module.check_mode:
                self.content.customFieldsManager.AddFieldDefinition(name=field, moType=self.object_type)
        return {'changed': changed, 'failed': False}


def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        custom_attribute=dict(type='str', no_log=False, required=True),
        object_type=dict(type='str', required=True, choices=[
            'Cluster',
            'Datacenter',
            'Datastore',
            'DistributedVirtualPortgroup',
            'DistributedVirtualSwitch',
            'Folder',
            'Global',
            'HostSystem',
            'ResourcePool',
            'VirtualMachine'
        ]),
        state=dict(type='str', default='present', choices=['absent', 'present']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    pyv = CustomAttribute(module)
    results = dict(changed=False, custom_attribute_defs=list())
    if module.params['state'] == "present":
        results = pyv.add_custom_def(module.params['custom_attribute'])
    elif module.params['state'] == "absent":
        results = pyv.remove_custom_def(module.params['custom_attribute'])

    module.exit_json(**results)


if __name__ == '__main__':
    main()