We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Change service startup policy with vmware_host_service_manager without defining service state
<!--- Verify first that your feature was not already discussed on GitHub -->
<!--- Complete *all* sections as described, this form is processed automatically -->

##### SUMMARY
<!--- Describe the new feature/improvement briefly below -->
When setting up the service in vSphere Client, the actions to set startup policy or service state are independent. However, when setting the service startup policy using the `vmware_host_service_manager` module, you have to specify the service state if you don't want to start the service, which is the default behavior.

##### ISSUE TYPE
- Feature Idea

##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
`vmware_host_service_manager` in community.vmware v1.11.0

##### ADDITIONAL INFORMATION
<!--- Describe how the feature would be used, why it is needed and what it would solve -->
Using the Ansible module should probably match the vSphere Client management behavior. It is not necessary to know the service state before changing the startup policy. The workaround is to use `vmware_host_service_info` module to first gather the state and then use it (which is kinda complicated way as the output values of the variable `running` from the `vmware_host_service_info` don't match the input values of the variable `state` in `vmware_host_service_manager`).

The `state` value of `unchanged` could be added (and set as default?). The current default is `start`.

Example playbook with the changes implemented:
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- hosts: localhost
  gather_facts: false
  tasks:
    - name: Disabling SSH service
      community.vmware.vmware_host_service_manager:
        esxi_hostname: <esxi_hostname>
        service_name: 'TSM-SSH'
        service_policy: 'off'
        state: 'unchanged'
```

<!--- HINT: You can also paste gist.github.com links for larger files -->


--- 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_service_manager.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_service_manager
14 short_description: Manage services on a given ESXi host
15 description:
16 - This module can be used to manage (start, stop, restart) services on a given ESXi host.
17 - If cluster_name is provided, specified service will be managed on all ESXi host belonging to that cluster.
18 - If specific esxi_hostname is provided, then specified service will be managed on given ESXi host only.
19 author:
20 - Abhijeet Kasurde (@Akasurde)
21 notes:
22 - Tested on vSphere 6.5
23 requirements:
24 - python >= 2.6
25 - PyVmomi
26 options:
27   cluster_name:
28     description:
29     - Name of the cluster.
30     - Service settings are applied to every ESXi host system/s in given cluster.
31     - If C(esxi_hostname) is not given, this parameter is required.
32     type: str
33   esxi_hostname:
34     description:
35     - ESXi hostname.
36     - Service settings are applied to this ESXi host system.
37     - If C(cluster_name) is not given, this parameter is required.
38     type: str
39   state:
40     description:
41     - Desired state of service.
42     - "State value 'start' and 'present' has same effect."
43     - "State value 'stop' and 'absent' has same effect."
44     choices: [ absent, present, restart, start, stop ]
45     type: str
46     default: 'start'
47   service_policy:
48     description:
49     - Set of valid service policy strings.
50     - If set C(on), then service should be started when the host starts up.
51     - If set C(automatic), then service should run if and only if it has open firewall ports.
52     - If set C(off), then Service should not be started when the host starts up.
53     choices: [ 'automatic', 'off', 'on' ]
54     type: str
55   service_name:
56     description:
57     - Name of Service to be managed. This is a brief identifier for the service, for example, ntpd, vxsyslogd etc.
58     - This value should be a valid ESXi service name.
59     required: True
60     type: str
61 extends_documentation_fragment:
62 - community.vmware.vmware.documentation
63 
64 '''
65 
66 EXAMPLES = r'''
67 - name: Start ntpd service setting for all ESXi Host in given Cluster
68   community.vmware.vmware_host_service_manager:
69     hostname: '{{ vcenter_hostname }}'
70     username: '{{ vcenter_username }}'
71     password: '{{ vcenter_password }}'
72     cluster_name: '{{ cluster_name }}'
73     service_name: ntpd
74     state: present
75   delegate_to: localhost
76 
77 - name: Start ntpd setting for an ESXi Host
78   community.vmware.vmware_host_service_manager:
79     hostname: '{{ vcenter_hostname }}'
80     username: '{{ vcenter_username }}'
81     password: '{{ vcenter_password }}'
82     esxi_hostname: '{{ esxi_hostname }}'
83     service_name: ntpd
84     state: present
85   delegate_to: localhost
86 
87 - name: Start ntpd setting for an ESXi Host with Service policy
88   community.vmware.vmware_host_service_manager:
89     hostname: '{{ vcenter_hostname }}'
90     username: '{{ vcenter_username }}'
91     password: '{{ vcenter_password }}'
92     esxi_hostname: '{{ esxi_hostname }}'
93     service_name: ntpd
94     service_policy: on
95     state: present
96   delegate_to: localhost
97 
98 - name: Stop ntpd setting for an ESXi Host
99   community.vmware.vmware_host_service_manager:
100     hostname: '{{ vcenter_hostname }}'
101     username: '{{ vcenter_username }}'
102     password: '{{ vcenter_password }}'
103     esxi_hostname: '{{ esxi_hostname }}'
104     service_name: ntpd
105     state: absent
106   delegate_to: localhost
107 '''
108 
109 RETURN = r'''#
110 '''
111 
112 try:
113     from pyVmomi import vim, vmodl
114 except ImportError:
115     pass
116 
117 from ansible.module_utils.basic import AnsibleModule
118 from ansible_collections.community.vmware.plugins.module_utils.vmware import vmware_argument_spec, PyVmomi
119 from ansible.module_utils._text import to_native
120 
121 
122 class VmwareServiceManager(PyVmomi):
123     def __init__(self, module):
124         super(VmwareServiceManager, self).__init__(module)
125         cluster_name = self.params.get('cluster_name', None)
126         esxi_host_name = self.params.get('esxi_hostname', None)
127         self.options = self.params.get('options', dict())
128         self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
129         self.desired_state = self.params.get('state')
130         self.desired_policy = self.params.get('service_policy', None)
131         self.service_name = self.params.get('service_name')
132         self.results = {}
133 
134     def service_ctrl(self):
135         changed = False
136         host_service_state = []
137         for host in self.hosts:
138             actual_service_state, actual_service_policy = self.check_service_state(host=host, service_name=self.service_name)
139             host_service_system = host.configManager.serviceSystem
140             if host_service_system:
141                 changed_state = False
142                 self.results[host.name] = dict(service_name=self.service_name,
143                                                actual_service_state='running' if actual_service_state else 'stopped',
144                                                actual_service_policy=actual_service_policy,
145                                                desired_service_policy=self.desired_policy,
146                                                desired_service_state=self.desired_state,
147                                                error='',
148                                                )
149                 try:
150                     if self.desired_state in ['start', 'present']:
151                         if not actual_service_state:
152                             if not self.module.check_mode:
153                                 host_service_system.StartService(id=self.service_name)
154                             changed_state = True
155                     elif self.desired_state in ['stop', 'absent']:
156                         if actual_service_state:
157                             if not self.module.check_mode:
158                                 host_service_system.StopService(id=self.service_name)
159                             changed_state = True
160                     elif self.desired_state == 'restart':
161                         if not self.module.check_mode:
162                             host_service_system.RestartService(id=self.service_name)
163                         changed_state = True
164 
165                     if self.desired_policy:
166                         if actual_service_policy != self.desired_policy:
167                             if not self.module.check_mode:
168                                 host_service_system.UpdateServicePolicy(id=self.service_name,
169                                                                         policy=self.desired_policy)
170                             changed_state = True
171 
172                     host_service_state.append(changed_state)
173                     self.results[host.name].update(changed=changed_state)
174                 except (vim.fault.InvalidState, vim.fault.NotFound,
175                         vim.fault.HostConfigFault, vmodl.fault.InvalidArgument) as e:
176                     self.results[host.name].update(changed=False,
177                                                    error=to_native(e.msg))
178 
179         if any(host_service_state):
180             changed = True
181         self.module.exit_json(changed=changed, host_service_status=self.results)
182 
183     def check_service_state(self, host, service_name):
184         host_service_system = host.configManager.serviceSystem
185         if host_service_system:
186             services = host_service_system.serviceInfo.service
187             for service in services:
188                 if service.key == service_name:
189                     return service.running, service.policy
190 
191         msg = "Failed to find '%s' service on host system '%s'" % (service_name, host.name)
192         cluster_name = self.params.get('cluster_name', None)
193         if cluster_name:
194             msg += " located on cluster '%s'" % cluster_name
195         msg += ", please check if you have specified a valid ESXi service name."
196         self.module.fail_json(msg=msg)
197 
198 
199 def main():
200     argument_spec = vmware_argument_spec()
201     argument_spec.update(
202         cluster_name=dict(type='str', required=False),
203         esxi_hostname=dict(type='str', required=False),
204         state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop']),
205         service_name=dict(type='str', required=True),
206         service_policy=dict(type='str', choices=['automatic', 'off', 'on']),
207     )
208 
209     module = AnsibleModule(
210         argument_spec=argument_spec,
211         required_one_of=[
212             ['cluster_name', 'esxi_hostname'],
213         ],
214         supports_check_mode=True
215     )
216 
217     vmware_host_service = VmwareServiceManager(module)
218     vmware_host_service.service_ctrl()
219 
220 
221 if __name__ == "__main__":
222     main()
223
```
--- 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_service_manager.py b/plugins/modules/vmware_host_service_manager.py
--- a/plugins/modules/vmware_host_service_manager.py
+++ b/plugins/modules/vmware_host_service_manager.py
@@ -41,7 +41,8 @@
     - Desired state of service.
     - "State value 'start' and 'present' has same effect."
     - "State value 'stop' and 'absent' has same effect."
-    choices: [ absent, present, restart, start, stop ]
+    - State value C(unchanged) is added in version 1.14.0 to allow defining startup policy without defining or changing service state.
+    choices: [ absent, present, restart, start, stop, unchanged ]
     type: str
     default: 'start'
   service_policy:
@@ -201,7 +202,7 @@
     argument_spec.update(
         cluster_name=dict(type='str', required=False),
         esxi_hostname=dict(type='str', required=False),
-        state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop']),
+        state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop', 'unchanged']),
         service_name=dict(type='str', required=True),
         service_policy=dict(type='str', choices=['automatic', 'off', 'on']),
     )

{"golden_diff": "diff --git a/plugins/modules/vmware_host_service_manager.py b/plugins/modules/vmware_host_service_manager.py\n--- a/plugins/modules/vmware_host_service_manager.py\n+++ b/plugins/modules/vmware_host_service_manager.py\n@@ -41,7 +41,8 @@\n     - Desired state of service.\n     - \"State value 'start' and 'present' has same effect.\"\n     - \"State value 'stop' and 'absent' has same effect.\"\n-    choices: [ absent, present, restart, start, stop ]\n+    - State value C(unchanged) is added in version 1.14.0 to allow defining startup policy without defining or changing service state.\n+    choices: [ absent, present, restart, start, stop, unchanged ]\n     type: str\n     default: 'start'\n   service_policy:\n@@ -201,7 +202,7 @@\n     argument_spec.update(\n         cluster_name=dict(type='str', required=False),\n         esxi_hostname=dict(type='str', required=False),\n-        state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop']),\n+        state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop', 'unchanged']),\n         service_name=dict(type='str', required=True),\n         service_policy=dict(type='str', choices=['automatic', 'off', 'on']),\n     )\n", "issue": "Change service startup policy with vmware_host_service_manager without defining service state\n<!--- Verify first that your feature was not already discussed on GitHub -->\r\n<!--- Complete *all* sections as described, this form is processed automatically -->\r\n\r\n##### SUMMARY\r\n<!--- Describe the new feature/improvement briefly below -->\r\nWhen setting up the service in vSphere Client, the actions to set startup policy or service state are independent. However, when setting the service startup policy using the `vmware_host_service_manager` module, you have to specify the service state if you don't want to start the service, which is the default behavior.\r\n\r\n##### ISSUE TYPE\r\n- Feature Idea\r\n\r\n##### COMPONENT NAME\r\n<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->\r\n`vmware_host_service_manager` in community.vmware v1.11.0\r\n\r\n##### ADDITIONAL INFORMATION\r\n<!--- Describe how the feature would be used, why it is needed and what it would solve -->\r\nUsing the Ansible module should probably match the vSphere Client management behavior. It is not necessary to know the service state before changing the startup policy. The workaround is to use `vmware_host_service_info` module to first gather the state and then use it (which is kinda complicated way as the output values of the variable `running` from the `vmware_host_service_info` don't match the input values of the variable `state` in `vmware_host_service_manager`).\r\n\r\nThe `state` value of `unchanged` could be added (and set as default?). The current default is `start`.\r\n\r\nExample playbook with the changes implemented:\r\n<!--- Paste example playbooks or commands between quotes below -->\r\n```yaml\r\n- hosts: localhost\r\n  gather_facts: false\r\n  tasks:\r\n    - name: Disabling SSH service\r\n      community.vmware.vmware_host_service_manager:\r\n        esxi_hostname: <esxi_hostname>\r\n        service_name: 'TSM-SSH'\r\n        service_policy: 'off'\r\n        state: 'unchanged'\r\n```\r\n\r\n<!--- HINT: You can also paste gist.github.com links for larger files -->\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_service_manager\nshort_description: Manage services on a given ESXi host\ndescription:\n- This module can be used to manage (start, stop, restart) services on a given ESXi host.\n- If cluster_name is provided, specified service will be managed on all ESXi host belonging to that cluster.\n- If specific esxi_hostname is provided, then specified service will be managed on given ESXi host only.\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 the cluster.\n    - Service settings are applied to every ESXi host system/s in given cluster.\n    - If C(esxi_hostname) is not given, this parameter is required.\n    type: str\n  esxi_hostname:\n    description:\n    - ESXi hostname.\n    - Service settings are applied to this ESXi host system.\n    - If C(cluster_name) is not given, this parameter is required.\n    type: str\n  state:\n    description:\n    - Desired state of service.\n    - \"State value 'start' and 'present' has same effect.\"\n    - \"State value 'stop' and 'absent' has same effect.\"\n    choices: [ absent, present, restart, start, stop ]\n    type: str\n    default: 'start'\n  service_policy:\n    description:\n    - Set of valid service policy strings.\n    - If set C(on), then service should be started when the host starts up.\n    - If set C(automatic), then service should run if and only if it has open firewall ports.\n    - If set C(off), then Service should not be started when the host starts up.\n    choices: [ 'automatic', 'off', 'on' ]\n    type: str\n  service_name:\n    description:\n    - Name of Service to be managed. This is a brief identifier for the service, for example, ntpd, vxsyslogd etc.\n    - This value should be a valid ESXi service name.\n    required: True\n    type: str\nextends_documentation_fragment:\n- community.vmware.vmware.documentation\n\n'''\n\nEXAMPLES = r'''\n- name: Start ntpd service setting for all ESXi Host in given Cluster\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    cluster_name: '{{ cluster_name }}'\n    service_name: ntpd\n    state: present\n  delegate_to: localhost\n\n- name: Start ntpd setting for an ESXi Host\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    service_name: ntpd\n    state: present\n  delegate_to: localhost\n\n- name: Start ntpd setting for an ESXi Host with Service policy\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    service_name: ntpd\n    service_policy: on\n    state: present\n  delegate_to: localhost\n\n- name: Stop ntpd setting for an ESXi Host\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    service_name: ntpd\n    state: absent\n  delegate_to: localhost\n'''\n\nRETURN = r'''#\n'''\n\ntry:\n    from pyVmomi import vim, vmodl\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 VmwareServiceManager(PyVmomi):\n    def __init__(self, module):\n        super(VmwareServiceManager, self).__init__(module)\n        cluster_name = self.params.get('cluster_name', None)\n        esxi_host_name = self.params.get('esxi_hostname', None)\n        self.options = self.params.get('options', dict())\n        self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)\n        self.desired_state = self.params.get('state')\n        self.desired_policy = self.params.get('service_policy', None)\n        self.service_name = self.params.get('service_name')\n        self.results = {}\n\n    def service_ctrl(self):\n        changed = False\n        host_service_state = []\n        for host in self.hosts:\n            actual_service_state, actual_service_policy = self.check_service_state(host=host, service_name=self.service_name)\n            host_service_system = host.configManager.serviceSystem\n            if host_service_system:\n                changed_state = False\n                self.results[host.name] = dict(service_name=self.service_name,\n                                               actual_service_state='running' if actual_service_state else 'stopped',\n                                               actual_service_policy=actual_service_policy,\n                                               desired_service_policy=self.desired_policy,\n                                               desired_service_state=self.desired_state,\n                                               error='',\n                                               )\n                try:\n                    if self.desired_state in ['start', 'present']:\n                        if not actual_service_state:\n                            if not self.module.check_mode:\n                                host_service_system.StartService(id=self.service_name)\n                            changed_state = True\n                    elif self.desired_state in ['stop', 'absent']:\n                        if actual_service_state:\n                            if not self.module.check_mode:\n                                host_service_system.StopService(id=self.service_name)\n                            changed_state = True\n                    elif self.desired_state == 'restart':\n                        if not self.module.check_mode:\n                            host_service_system.RestartService(id=self.service_name)\n                        changed_state = True\n\n                    if self.desired_policy:\n                        if actual_service_policy != self.desired_policy:\n                            if not self.module.check_mode:\n                                host_service_system.UpdateServicePolicy(id=self.service_name,\n                                                                        policy=self.desired_policy)\n                            changed_state = True\n\n                    host_service_state.append(changed_state)\n                    self.results[host.name].update(changed=changed_state)\n                except (vim.fault.InvalidState, vim.fault.NotFound,\n                        vim.fault.HostConfigFault, vmodl.fault.InvalidArgument) as e:\n                    self.results[host.name].update(changed=False,\n                                                   error=to_native(e.msg))\n\n        if any(host_service_state):\n            changed = True\n        self.module.exit_json(changed=changed, host_service_status=self.results)\n\n    def check_service_state(self, host, service_name):\n        host_service_system = host.configManager.serviceSystem\n        if host_service_system:\n            services = host_service_system.serviceInfo.service\n            for service in services:\n                if service.key == service_name:\n                    return service.running, service.policy\n\n        msg = \"Failed to find '%s' service on host system '%s'\" % (service_name, host.name)\n        cluster_name = self.params.get('cluster_name', None)\n        if cluster_name:\n            msg += \" located on cluster '%s'\" % cluster_name\n        msg += \", please check if you have specified a valid ESXi service name.\"\n        self.module.fail_json(msg=msg)\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='str', required=False),\n        state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop']),\n        service_name=dict(type='str', required=True),\n        service_policy=dict(type='str', choices=['automatic', 'off', 'on']),\n    )\n\n    module = AnsibleModule(\n        argument_spec=argument_spec,\n        required_one_of=[\n            ['cluster_name', 'esxi_hostname'],\n        ],\n        supports_check_mode=True\n    )\n\n    vmware_host_service = VmwareServiceManager(module)\n    vmware_host_service.service_ctrl()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "plugins/modules/vmware_host_service_manager.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_service_manager\nshort_description: Manage services on a given ESXi host\ndescription:\n- This module can be used to manage (start, stop, restart) services on a given ESXi host.\n- If cluster_name is provided, specified service will be managed on all ESXi host belonging to that cluster.\n- If specific esxi_hostname is provided, then specified service will be managed on given ESXi host only.\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 the cluster.\n    - Service settings are applied to every ESXi host system/s in given cluster.\n    - If C(esxi_hostname) is not given, this parameter is required.\n    type: str\n  esxi_hostname:\n    description:\n    - ESXi hostname.\n    - Service settings are applied to this ESXi host system.\n    - If C(cluster_name) is not given, this parameter is required.\n    type: str\n  state:\n    description:\n    - Desired state of service.\n    - \"State value 'start' and 'present' has same effect.\"\n    - \"State value 'stop' and 'absent' has same effect.\"\n    - State value C(unchanged) is added in version 1.14.0 to allow defining startup policy without defining or changing service state.\n    choices: [ absent, present, restart, start, stop, unchanged ]\n    type: str\n    default: 'start'\n  service_policy:\n    description:\n    - Set of valid service policy strings.\n    - If set C(on), then service should be started when the host starts up.\n    - If set C(automatic), then service should run if and only if it has open firewall ports.\n    - If set C(off), then Service should not be started when the host starts up.\n    choices: [ 'automatic', 'off', 'on' ]\n    type: str\n  service_name:\n    description:\n    - Name of Service to be managed. This is a brief identifier for the service, for example, ntpd, vxsyslogd etc.\n    - This value should be a valid ESXi service name.\n    required: True\n    type: str\nextends_documentation_fragment:\n- community.vmware.vmware.documentation\n\n'''\n\nEXAMPLES = r'''\n- name: Start ntpd service setting for all ESXi Host in given Cluster\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    cluster_name: '{{ cluster_name }}'\n    service_name: ntpd\n    state: present\n  delegate_to: localhost\n\n- name: Start ntpd setting for an ESXi Host\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    service_name: ntpd\n    state: present\n  delegate_to: localhost\n\n- name: Start ntpd setting for an ESXi Host with Service policy\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    service_name: ntpd\n    service_policy: on\n    state: present\n  delegate_to: localhost\n\n- name: Stop ntpd setting for an ESXi Host\n  community.vmware.vmware_host_service_manager:\n    hostname: '{{ vcenter_hostname }}'\n    username: '{{ vcenter_username }}'\n    password: '{{ vcenter_password }}'\n    esxi_hostname: '{{ esxi_hostname }}'\n    service_name: ntpd\n    state: absent\n  delegate_to: localhost\n'''\n\nRETURN = r'''#\n'''\n\ntry:\n    from pyVmomi import vim, vmodl\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 VmwareServiceManager(PyVmomi):\n    def __init__(self, module):\n        super(VmwareServiceManager, self).__init__(module)\n        cluster_name = self.params.get('cluster_name', None)\n        esxi_host_name = self.params.get('esxi_hostname', None)\n        self.options = self.params.get('options', dict())\n        self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)\n        self.desired_state = self.params.get('state')\n        self.desired_policy = self.params.get('service_policy', None)\n        self.service_name = self.params.get('service_name')\n        self.results = {}\n\n    def service_ctrl(self):\n        changed = False\n        host_service_state = []\n        for host in self.hosts:\n            actual_service_state, actual_service_policy = self.check_service_state(host=host, service_name=self.service_name)\n            host_service_system = host.configManager.serviceSystem\n            if host_service_system:\n                changed_state = False\n                self.results[host.name] = dict(service_name=self.service_name,\n                                               actual_service_state='running' if actual_service_state else 'stopped',\n                                               actual_service_policy=actual_service_policy,\n                                               desired_service_policy=self.desired_policy,\n                                               desired_service_state=self.desired_state,\n                                               error='',\n                                               )\n                try:\n                    if self.desired_state in ['start', 'present']:\n                        if not actual_service_state:\n                            if not self.module.check_mode:\n                                host_service_system.StartService(id=self.service_name)\n                            changed_state = True\n                    elif self.desired_state in ['stop', 'absent']:\n                        if actual_service_state:\n                            if not self.module.check_mode:\n                                host_service_system.StopService(id=self.service_name)\n                            changed_state = True\n                    elif self.desired_state == 'restart':\n                        if not self.module.check_mode:\n                            host_service_system.RestartService(id=self.service_name)\n                        changed_state = True\n\n                    if self.desired_policy:\n                        if actual_service_policy != self.desired_policy:\n                            if not self.module.check_mode:\n                                host_service_system.UpdateServicePolicy(id=self.service_name,\n                                                                        policy=self.desired_policy)\n                            changed_state = True\n\n                    host_service_state.append(changed_state)\n                    self.results[host.name].update(changed=changed_state)\n                except (vim.fault.InvalidState, vim.fault.NotFound,\n                        vim.fault.HostConfigFault, vmodl.fault.InvalidArgument) as e:\n                    self.results[host.name].update(changed=False,\n                                                   error=to_native(e.msg))\n\n        if any(host_service_state):\n            changed = True\n        self.module.exit_json(changed=changed, host_service_status=self.results)\n\n    def check_service_state(self, host, service_name):\n        host_service_system = host.configManager.serviceSystem\n        if host_service_system:\n            services = host_service_system.serviceInfo.service\n            for service in services:\n                if service.key == service_name:\n                    return service.running, service.policy\n\n        msg = \"Failed to find '%s' service on host system '%s'\" % (service_name, host.name)\n        cluster_name = self.params.get('cluster_name', None)\n        if cluster_name:\n            msg += \" located on cluster '%s'\" % cluster_name\n        msg += \", please check if you have specified a valid ESXi service name.\"\n        self.module.fail_json(msg=msg)\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='str', required=False),\n        state=dict(type='str', default='start', choices=['absent', 'present', 'restart', 'start', 'stop', 'unchanged']),\n        service_name=dict(type='str', required=True),\n        service_policy=dict(type='str', choices=['automatic', 'off', 'on']),\n    )\n\n    module = AnsibleModule(\n        argument_spec=argument_spec,\n        required_one_of=[\n            ['cluster_name', 'esxi_hostname'],\n        ],\n        supports_check_mode=True\n    )\n\n    vmware_host_service = VmwareServiceManager(module)\n    vmware_host_service.service_ctrl()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "plugins/modules/vmware_host_service_manager.py"}]}