We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
vmware_host_lockdown crashes on failure
##### SUMMARY
Today, I wanted to enable lockdown mode on a host. This failed, although I didn't find out yet why. But that's not important. The bug is that the module includes `vim` from `pyvmomi` instead of `pyVmomi` and doesn't check that this works:

https://github.com/ansible-collections/community.vmware/blob/f418bdaa6a678c09b6fb9115d927d8c44d50060f/plugins/modules/vmware_host_lockdown.py#L123-L126

I think nobody ran into this issue yet because enabling or disabling lockdown seldom fails (in my experience) and `vim` is only used in this case:

https://github.com/ansible-collections/community.vmware/blob/f418bdaa6a678c09b6fb9115d927d8c44d50060f/plugins/modules/vmware_host_lockdown.py#L176-L182

##### ISSUE TYPE
- Bug Report

##### COMPONENT NAME
vmware_host_lockdown

##### ANSIBLE VERSION
```
ansible [core 2.11.6] 
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.9.1 (default, Aug 19 2021, 02:58:42) [GCC 10.2.0]
  jinja version = 3.0.2
  libyaml = True
```

##### COLLECTION VERSION
```
# /usr/lib/python3.9/site-packages/ansible_collections
Collection       Version
---------------- -------
community.vmware 1.15.0
```

##### CONFIGURATION
```

```

##### OS / ENVIRONMENT
VMware Photon OS 4.0 and vSphere 7.0U2, but this is irrelevant.


##### STEPS TO REPRODUCE
Tricky. As I've said, enabling / disabling lockdown usually works.

##### EXPECTED RESULTS
A failure.


##### ACTUAL RESULTS
```
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: name 'vim' is not defined
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `plugins/modules/vmware_host_lockdown.py`
Content:
```
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 
4 # Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9 
10 
11 DOCUMENTATION = r'''
12 ---
13 module: vmware_host_lockdown
14 short_description: Manage administrator permission for the local administrative account for the ESXi host
15 description:
16 - This module can be used to manage administrator permission for the local administrative account for the host when ESXi hostname is given.
17 - All parameters and VMware objects values are case sensitive.
18 - This module is destructive as administrator permission are managed using APIs used, please read options carefully and proceed.
19 - Please specify C(hostname) as vCenter IP or hostname only, as lockdown operations are not possible from standalone ESXi server.
20 author:
21 - Abhijeet Kasurde (@Akasurde)
22 notes:
23 - Tested on vSphere 6.5
24 requirements:
25 - python >= 2.6
26 - PyVmomi
27 options:
28   cluster_name:
29     description:
30     - Name of cluster.
31     - All host systems from given cluster used to manage lockdown.
32     - Required parameter, if C(esxi_hostname) is not set.
33     type: str
34   esxi_hostname:
35     description:
36     - List of ESXi hostname to manage lockdown.
37     - Required parameter, if C(cluster_name) is not set.
38     - See examples for specifications.
39     type: list
40     elements: str
41   state:
42     description:
43     - State of hosts system
44     - If set to C(present), all host systems will be set in lockdown mode.
45     - If host system is already in lockdown mode and set to C(present), no action will be taken.
46     - If set to C(absent), all host systems will be removed from lockdown mode.
47     - If host system is already out of lockdown mode and set to C(absent), no action will be taken.
48     default: present
49     choices: [ present, absent ]
50     type: str
51 extends_documentation_fragment:
52 - community.vmware.vmware.documentation
53 
54 '''
55 
56 EXAMPLES = r'''
57 - name: Enter host system into lockdown mode
58   community.vmware.vmware_host_lockdown:
59     hostname: '{{ vcenter_hostname }}'
60     username: '{{ vcenter_username }}'
61     password: '{{ vcenter_password }}'
62     esxi_hostname: '{{ esxi_hostname }}'
63     state: present
64   delegate_to: localhost
65 
66 - name: Exit host systems from lockdown mode
67   community.vmware.vmware_host_lockdown:
68     hostname: '{{ vcenter_hostname }}'
69     username: '{{ vcenter_username }}'
70     password: '{{ vcenter_password }}'
71     esxi_hostname: '{{ esxi_hostname }}'
72     state: absent
73   delegate_to: localhost
74 
75 - name: Enter host systems into lockdown mode
76   community.vmware.vmware_host_lockdown:
77     hostname: '{{ vcenter_hostname }}'
78     username: '{{ vcenter_username }}'
79     password: '{{ vcenter_password }}'
80     esxi_hostname:
81         - '{{ esxi_hostname_1 }}'
82         - '{{ esxi_hostname_2 }}'
83     state: present
84   delegate_to: localhost
85 
86 - name: Exit host systems from lockdown mode
87   community.vmware.vmware_host_lockdown:
88     hostname: '{{ vcenter_hostname }}'
89     username: '{{ vcenter_username }}'
90     password: '{{ vcenter_password }}'
91     esxi_hostname:
92         - '{{ esxi_hostname_1 }}'
93         - '{{ esxi_hostname_2 }}'
94     state: absent
95   delegate_to: localhost
96 
97 - name: Enter all host system from cluster into lockdown mode
98   community.vmware.vmware_host_lockdown:
99     hostname: '{{ vcenter_hostname }}'
100     username: '{{ vcenter_username }}'
101     password: '{{ vcenter_password }}'
102     cluster_name: '{{ cluster_name }}'
103     state: present
104   delegate_to: localhost
105 '''
106 
107 RETURN = r'''
108 results:
109     description: metadata about state of Host system lock down
110     returned: always
111     type: dict
112     sample: {
113                 "host_lockdown_state": {
114                     "DC0_C0": {
115                         "current_state": "present",
116                         "previous_state": "absent",
117                         "desired_state": "present",
118                     },
119                 }
120             }
121 '''
122 
123 try:
124     from pyvmomi import vim
125 except ImportError:
126     pass
127 
128 from ansible.module_utils.basic import AnsibleModule
129 from ansible_collections.community.vmware.plugins.module_utils.vmware import vmware_argument_spec, PyVmomi
130 from ansible.module_utils._text import to_native
131 
132 
133 class VmwareLockdownManager(PyVmomi):
134     def __init__(self, module):
135         super(VmwareLockdownManager, self).__init__(module)
136         if not self.is_vcenter():
137             self.module.fail_json(msg="Lockdown operations are performed from vCenter only. "
138                                       "hostname %s is an ESXi server. Please specify hostname "
139                                       "as vCenter server." % self.module.params['hostname'])
140         cluster_name = self.params.get('cluster_name', None)
141         esxi_host_name = self.params.get('esxi_hostname', None)
142         self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
143 
144     def ensure(self):
145         """
146         Function to manage internal state management
147         """
148         results = dict(changed=False, host_lockdown_state=dict())
149         change_list = []
150         desired_state = self.params.get('state')
151         for host in self.hosts:
152             results['host_lockdown_state'][host.name] = dict(current_state='',
153                                                              desired_state=desired_state,
154                                                              previous_state=''
155                                                              )
156             changed = False
157             try:
158                 if host.config.adminDisabled:
159                     results['host_lockdown_state'][host.name]['previous_state'] = 'present'
160                     if desired_state == 'absent':
161                         if not self.module.check_mode:
162                             host.ExitLockdownMode()
163                         results['host_lockdown_state'][host.name]['current_state'] = 'absent'
164                         changed = True
165                     else:
166                         results['host_lockdown_state'][host.name]['current_state'] = 'present'
167                 elif not host.config.adminDisabled:
168                     results['host_lockdown_state'][host.name]['previous_state'] = 'absent'
169                     if desired_state == 'present':
170                         if not self.module.check_mode:
171                             host.EnterLockdownMode()
172                         results['host_lockdown_state'][host.name]['current_state'] = 'present'
173                         changed = True
174                     else:
175                         results['host_lockdown_state'][host.name]['current_state'] = 'absent'
176             except vim.fault.HostConfigFault as host_config_fault:
177                 self.module.fail_json(msg="Failed to manage lockdown mode for esxi"
178                                           " hostname %s : %s" % (host.name, to_native(host_config_fault.msg)))
179             except vim.fault.AdminDisabled as admin_disabled:
180                 self.module.fail_json(msg="Failed to manage lockdown mode as administrator "
181                                           "permission has been disabled for "
182                                           "esxi hostname %s : %s" % (host.name, to_native(admin_disabled.msg)))
183             except Exception as generic_exception:
184                 self.module.fail_json(msg="Failed to manage lockdown mode due to generic exception for esxi "
185                                           "hostname %s : %s" % (host.name, to_native(generic_exception)))
186             change_list.append(changed)
187 
188         if any(change_list):
189             results['changed'] = True
190 
191         self.module.exit_json(**results)
192 
193 
194 def main():
195     argument_spec = vmware_argument_spec()
196     argument_spec.update(
197         cluster_name=dict(type='str', required=False),
198         esxi_hostname=dict(type='list', required=False, elements='str'),
199         state=dict(type='str', default='present', choices=['present', 'absent'], required=False),
200     )
201 
202     module = AnsibleModule(
203         argument_spec=argument_spec,
204         supports_check_mode=True,
205         required_one_of=[
206             ['cluster_name', 'esxi_hostname'],
207         ]
208     )
209 
210     vmware_lockdown_mgr = VmwareLockdownManager(module)
211     vmware_lockdown_mgr.ensure()
212 
213 
214 if __name__ == "__main__":
215     main()
216
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/plugins/modules/vmware_host_lockdown.py b/plugins/modules/vmware_host_lockdown.py
--- a/plugins/modules/vmware_host_lockdown.py
+++ b/plugins/modules/vmware_host_lockdown.py
@@ -121,9 +121,10 @@
 '''
 
 try:
-    from pyvmomi import vim
+    from pyVmomi import vim
+    HAS_PYVMOMI = True
 except ImportError:
-    pass
+    HAS_PYVMOMI = False
 
 from ansible.module_utils.basic import AnsibleModule
 from ansible_collections.community.vmware.plugins.module_utils.vmware import vmware_argument_spec, PyVmomi
@@ -207,6 +208,9 @@
         ]
     )
 
+    if not HAS_PYVMOMI:
+        module.fail_json(msg='pyvmomi required for this module')
+
     vmware_lockdown_mgr = VmwareLockdownManager(module)
     vmware_lockdown_mgr.ensure()

{"golden_diff": "diff --git a/plugins/modules/vmware_host_lockdown.py b/plugins/modules/vmware_host_lockdown.py\n--- a/plugins/modules/vmware_host_lockdown.py\n+++ b/plugins/modules/vmware_host_lockdown.py\n@@ -121,9 +121,10 @@\n '''\n \n try:\n-    from pyvmomi import vim\n+    from pyVmomi import vim\n+    HAS_PYVMOMI = True\n except ImportError:\n-    pass\n+    HAS_PYVMOMI = False\n \n from ansible.module_utils.basic import AnsibleModule\n from ansible_collections.community.vmware.plugins.module_utils.vmware import vmware_argument_spec, PyVmomi\n@@ -207,6 +208,9 @@\n         ]\n     )\n \n+    if not HAS_PYVMOMI:\n+        module.fail_json(msg='pyvmomi required for this module')\n+\n     vmware_lockdown_mgr = VmwareLockdownManager(module)\n     vmware_lockdown_mgr.ensure()\n", "issue": "vmware_host_lockdown crashes on failure\n##### SUMMARY\r\nToday, I wanted to enable lockdown mode on a host. This failed, although I didn't find out yet why. But that's not important. The bug is that the module includes `vim` from `pyvmomi` instead of `pyVmomi` and doesn't check that this works:\r\n\r\nhttps://github.com/ansible-collections/community.vmware/blob/f418bdaa6a678c09b6fb9115d927d8c44d50060f/plugins/modules/vmware_host_lockdown.py#L123-L126\r\n\r\nI think nobody ran into this issue yet because enabling or disabling lockdown seldom fails (in my experience) and `vim` is only used in this case:\r\n\r\nhttps://github.com/ansible-collections/community.vmware/blob/f418bdaa6a678c09b6fb9115d927d8c44d50060f/plugins/modules/vmware_host_lockdown.py#L176-L182\r\n\r\n##### ISSUE TYPE\r\n- Bug Report\r\n\r\n##### COMPONENT NAME\r\nvmware_host_lockdown\r\n\r\n##### ANSIBLE VERSION\r\n```\r\nansible [core 2.11.6] \r\n  config file = None\r\n  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']\r\n  ansible python module location = /usr/lib/python3.9/site-packages/ansible\r\n  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections\r\n  executable location = /usr/bin/ansible\r\n  python version = 3.9.1 (default, Aug 19 2021, 02:58:42) [GCC 10.2.0]\r\n  jinja version = 3.0.2\r\n  libyaml = True\r\n```\r\n\r\n##### COLLECTION VERSION\r\n```\r\n# /usr/lib/python3.9/site-packages/ansible_collections\r\nCollection       Version\r\n---------------- -------\r\ncommunity.vmware 1.15.0\r\n```\r\n\r\n##### CONFIGURATION\r\n```\r\n\r\n```\r\n\r\n##### OS / ENVIRONMENT\r\nVMware Photon OS 4.0 and vSphere 7.0U2, but this is irrelevant.\r\n\r\n\r\n##### STEPS TO REPRODUCE\r\nTricky. As I've said, enabling / disabling lockdown usually works.\r\n\r\n##### EXPECTED RESULTS\r\nA failure.\r\n\r\n\r\n##### ACTUAL RESULTS\r\n```\r\nAn exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: name 'vim' is not defined\r\n```\n", "before_files": [{"content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = r'''\n---\nmodule: vmware_host_lockdown\nshort_description: Manage administrator permission for the local administrative account for the ESXi host\ndescription:\n- This module can be used to manage administrator permission for the local administrative account for the host when ESXi hostname is given.\n- All parameters and VMware objects values are case sensitive.\n- This module is destructive as administrator permission are managed using APIs used, please read options carefully and proceed.\n- Please specify C(hostname) as vCenter IP or hostname only, as lockdown operations are not possible from standalone ESXi server.\nauthor:\n- Abhijeet Kasurde (@Akasurde)\nnotes:\n- Tested on vSphere 6.5\nrequirements:\n- python >= 2.6\n- PyVmomi\noptions:\n  cluster_name:\n    description:\n    - Name of cluster.\n    - All host systems from given cluster used to manage lockdown.\n    - Required parameter, if C(esxi_hostname) is not set.\n    type: str\n  esxi_hostname:\n    description:\n    - List of ESXi hostname to manage lockdown.\n    - Required parameter, if C(cluster_name) is not set.\n    - See examples for specifications.\n    type: list\n    elements: str\n  state:\n    description:\n    - State of hosts system\n    - If set to C(present), all host systems will be set in lockdown mode.\n    - If host system is already in lockdown mode and set to C(present), no action will be taken.\n    - If set to C(absent), all host systems will be removed from lockdown mode.\n    - If host system is already out of lockdown mode and set to C(absent), no action will be taken.\n    default: present\n    choices: [ present, absent ]\n    type: str\nextends_documentation_fragment:\n- community.vmware.vmware.documentation\n\n'''\n\nEXAMPLES = r'''\n- name: Enter host system into lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    state: present\n  delegate_to: localhost\n\n- name: Exit host systems from lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    state: absent\n  delegate_to: localhost\n\n- name: Enter host systems into lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname:\n        - '{{ esxi_hostname_1 }}'\n        - '{{ esxi_hostname_2 }}'\n    state: present\n  delegate_to: localhost\n\n- name: Exit host systems from lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname:\n        - '{{ esxi_hostname_1 }}'\n        - '{{ esxi_hostname_2 }}'\n    state: absent\n  delegate_to: localhost\n\n- name: Enter all host system from cluster into lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    cluster_name: '{{ cluster_name }}'\n    state: present\n  delegate_to: localhost\n'''\n\nRETURN = r'''\nresults:\n    description: metadata about state of Host system lock down\n    returned: always\n    type: dict\n    sample: {\n                \"host_lockdown_state\": {\n                    \"DC0_C0\": {\n                        \"current_state\": \"present\",\n                        \"previous_state\": \"absent\",\n                        \"desired_state\": \"present\",\n                    },\n                }\n            }\n'''\n\ntry:\n    from pyvmomi import vim\nexcept ImportError:\n    pass\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_collections.community.vmware.plugins.module_utils.vmware import vmware_argument_spec, PyVmomi\nfrom ansible.module_utils._text import to_native\n\n\nclass VmwareLockdownManager(PyVmomi):\n    def __init__(self, module):\n        super(VmwareLockdownManager, self).__init__(module)\n        if not self.is_vcenter():\n            self.module.fail_json(msg=\"Lockdown operations are performed from vCenter only. \"\n                                      \"hostname %s is an ESXi server. Please specify hostname \"\n                                      \"as vCenter server.\" % self.module.params['hostname'])\n        cluster_name = self.params.get('cluster_name', None)\n        esxi_host_name = self.params.get('esxi_hostname', None)\n        self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)\n\n    def ensure(self):\n        \"\"\"\n        Function to manage internal state management\n        \"\"\"\n        results = dict(changed=False, host_lockdown_state=dict())\n        change_list = []\n        desired_state = self.params.get('state')\n        for host in self.hosts:\n            results['host_lockdown_state'][host.name] = dict(current_state='',\n                                                             desired_state=desired_state,\n                                                             previous_state=''\n                                                             )\n            changed = False\n            try:\n                if host.config.adminDisabled:\n                    results['host_lockdown_state'][host.name]['previous_state'] = 'present'\n                    if desired_state == 'absent':\n                        if not self.module.check_mode:\n                            host.ExitLockdownMode()\n                        results['host_lockdown_state'][host.name]['current_state'] = 'absent'\n                        changed = True\n                    else:\n                        results['host_lockdown_state'][host.name]['current_state'] = 'present'\n                elif not host.config.adminDisabled:\n                    results['host_lockdown_state'][host.name]['previous_state'] = 'absent'\n                    if desired_state == 'present':\n                        if not self.module.check_mode:\n                            host.EnterLockdownMode()\n                        results['host_lockdown_state'][host.name]['current_state'] = 'present'\n                        changed = True\n                    else:\n                        results['host_lockdown_state'][host.name]['current_state'] = 'absent'\n            except vim.fault.HostConfigFault as host_config_fault:\n                self.module.fail_json(msg=\"Failed to manage lockdown mode for esxi\"\n                                          \" hostname %s : %s\" % (host.name, to_native(host_config_fault.msg)))\n            except vim.fault.AdminDisabled as admin_disabled:\n                self.module.fail_json(msg=\"Failed to manage lockdown mode as administrator \"\n                                          \"permission has been disabled for \"\n                                          \"esxi hostname %s : %s\" % (host.name, to_native(admin_disabled.msg)))\n            except Exception as generic_exception:\n                self.module.fail_json(msg=\"Failed to manage lockdown mode due to generic exception for esxi \"\n                                          \"hostname %s : %s\" % (host.name, to_native(generic_exception)))\n            change_list.append(changed)\n\n        if any(change_list):\n            results['changed'] = True\n\n        self.module.exit_json(**results)\n\n\ndef main():\n    argument_spec = vmware_argument_spec()\n    argument_spec.update(\n        cluster_name=dict(type='str', required=False),\n        esxi_hostname=dict(type='list', required=False, elements='str'),\n        state=dict(type='str', default='present', choices=['present', 'absent'], required=False),\n    )\n\n    module = AnsibleModule(\n        argument_spec=argument_spec,\n        supports_check_mode=True,\n        required_one_of=[\n            ['cluster_name', 'esxi_hostname'],\n        ]\n    )\n\n    vmware_lockdown_mgr = VmwareLockdownManager(module)\n    vmware_lockdown_mgr.ensure()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "plugins/modules/vmware_host_lockdown.py"}], "after_files": [{"content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = r'''\n---\nmodule: vmware_host_lockdown\nshort_description: Manage administrator permission for the local administrative account for the ESXi host\ndescription:\n- This module can be used to manage administrator permission for the local administrative account for the host when ESXi hostname is given.\n- All parameters and VMware objects values are case sensitive.\n- This module is destructive as administrator permission are managed using APIs used, please read options carefully and proceed.\n- Please specify C(hostname) as vCenter IP or hostname only, as lockdown operations are not possible from standalone ESXi server.\nauthor:\n- Abhijeet Kasurde (@Akasurde)\nnotes:\n- Tested on vSphere 6.5\nrequirements:\n- python >= 2.6\n- PyVmomi\noptions:\n  cluster_name:\n    description:\n    - Name of cluster.\n    - All host systems from given cluster used to manage lockdown.\n    - Required parameter, if C(esxi_hostname) is not set.\n    type: str\n  esxi_hostname:\n    description:\n    - List of ESXi hostname to manage lockdown.\n    - Required parameter, if C(cluster_name) is not set.\n    - See examples for specifications.\n    type: list\n    elements: str\n  state:\n    description:\n    - State of hosts system\n    - If set to C(present), all host systems will be set in lockdown mode.\n    - If host system is already in lockdown mode and set to C(present), no action will be taken.\n    - If set to C(absent), all host systems will be removed from lockdown mode.\n    - If host system is already out of lockdown mode and set to C(absent), no action will be taken.\n    default: present\n    choices: [ present, absent ]\n    type: str\nextends_documentation_fragment:\n- community.vmware.vmware.documentation\n\n'''\n\nEXAMPLES = r'''\n- name: Enter host system into lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    state: present\n  delegate_to: localhost\n\n- name: Exit host systems from lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    state: absent\n  delegate_to: localhost\n\n- name: Enter host systems into lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname:\n        - '{{ esxi_hostname_1 }}'\n        - '{{ esxi_hostname_2 }}'\n    state: present\n  delegate_to: localhost\n\n- name: Exit host systems from lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname:\n        - '{{ esxi_hostname_1 }}'\n        - '{{ esxi_hostname_2 }}'\n    state: absent\n  delegate_to: localhost\n\n- name: Enter all host system from cluster into lockdown mode\n  community.vmware.vmware_host_lockdown:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    cluster_name: '{{ cluster_name }}'\n    state: present\n  delegate_to: localhost\n'''\n\nRETURN = r'''\nresults:\n    description: metadata about state of Host system lock down\n    returned: always\n    type: dict\n    sample: {\n                \"host_lockdown_state\": {\n                    \"DC0_C0\": {\n                        \"current_state\": \"present\",\n                        \"previous_state\": \"absent\",\n                        \"desired_state\": \"present\",\n                    },\n                }\n            }\n'''\n\ntry:\n    from pyVmomi import vim\n    HAS_PYVMOMI = True\nexcept ImportError:\n    HAS_PYVMOMI = False\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_collections.community.vmware.plugins.module_utils.vmware import vmware_argument_spec, PyVmomi\nfrom ansible.module_utils._text import to_native\n\n\nclass VmwareLockdownManager(PyVmomi):\n    def __init__(self, module):\n        super(VmwareLockdownManager, self).__init__(module)\n        if not self.is_vcenter():\n            self.module.fail_json(msg=\"Lockdown operations are performed from vCenter only. \"\n                                      \"hostname %s is an ESXi server. Please specify hostname \"\n                                      \"as vCenter server.\" % self.module.params['hostname'])\n        cluster_name = self.params.get('cluster_name', None)\n        esxi_host_name = self.params.get('esxi_hostname', None)\n        self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)\n\n    def ensure(self):\n        \"\"\"\n        Function to manage internal state management\n        \"\"\"\n        results = dict(changed=False, host_lockdown_state=dict())\n        change_list = []\n        desired_state = self.params.get('state')\n        for host in self.hosts:\n            results['host_lockdown_state'][host.name] = dict(current_state='',\n                                                             desired_state=desired_state,\n                                                             previous_state=''\n                                                             )\n            changed = False\n            try:\n                if host.config.adminDisabled:\n                    results['host_lockdown_state'][host.name]['previous_state'] = 'present'\n                    if desired_state == 'absent':\n                        if not self.module.check_mode:\n                            host.ExitLockdownMode()\n                        results['host_lockdown_state'][host.name]['current_state'] = 'absent'\n                        changed = True\n                    else:\n                        results['host_lockdown_state'][host.name]['current_state'] = 'present'\n                elif not host.config.adminDisabled:\n                    results['host_lockdown_state'][host.name]['previous_state'] = 'absent'\n                    if desired_state == 'present':\n                        if not self.module.check_mode:\n                            host.EnterLockdownMode()\n                        results['host_lockdown_state'][host.name]['current_state'] = 'present'\n                        changed = True\n                    else:\n                        results['host_lockdown_state'][host.name]['current_state'] = 'absent'\n            except vim.fault.HostConfigFault as host_config_fault:\n                self.module.fail_json(msg=\"Failed to manage lockdown mode for esxi\"\n                                          \" hostname %s : %s\" % (host.name, to_native(host_config_fault.msg)))\n            except vim.fault.AdminDisabled as admin_disabled:\n                self.module.fail_json(msg=\"Failed to manage lockdown mode as administrator \"\n                                          \"permission has been disabled for \"\n                                          \"esxi hostname %s : %s\" % (host.name, to_native(admin_disabled.msg)))\n            except Exception as generic_exception:\n                self.module.fail_json(msg=\"Failed to manage lockdown mode due to generic exception for esxi \"\n                                          \"hostname %s : %s\" % (host.name, to_native(generic_exception)))\n            change_list.append(changed)\n\n        if any(change_list):\n            results['changed'] = True\n\n        self.module.exit_json(**results)\n\n\ndef main():\n    argument_spec = vmware_argument_spec()\n    argument_spec.update(\n        cluster_name=dict(type='str', required=False),\n        esxi_hostname=dict(type='list', required=False, elements='str'),\n        state=dict(type='str', default='present', choices=['present', 'absent'], required=False),\n    )\n\n    module = AnsibleModule(\n        argument_spec=argument_spec,\n        supports_check_mode=True,\n        required_one_of=[\n            ['cluster_name', 'esxi_hostname'],\n        ]\n    )\n\n    if not HAS_PYVMOMI:\n        module.fail_json(msg='pyvmomi required for this module')\n\n    vmware_lockdown_mgr = VmwareLockdownManager(module)\n    vmware_lockdown_mgr.ensure()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "plugins/modules/vmware_host_lockdown.py"}]}