Debian Codegraph @

ansible_collections/community/general/plugins/modules/nomad_job.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, FERREIRA Christophe <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: nomad_job
11 author: FERREIRA Christophe (@chris93111)
12 version_added: "1.3.0"
13 short_description: Launch a Nomad Job
14 description:
15 - Launch a Nomad job.
16 - Stop a Nomad job.
17 - Force start a Nomad job.
18 requirements:
19 - python-nomad
20 extends_documentation_fragment:
21 - community.general._nomad
22 - community.general._attributes
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: none
28 options:
29 name:
30 description:
31 - Name of job for delete, stop and start job without source.
32 - Name of job for delete, stop and start job without source.
33 - Either this or O(content) must be specified.
34 type: str
35 state:
36 description:
37 - Deploy or remove job.
38 choices: ["present", "absent"]
39 required: true
40 type: str
41 force_start:
42 description:
43 - Force job to started.
44 type: bool
45 default: false
46 content:
47 description:
48 - Content of Nomad job.
49 - Either this or O(name) must be specified.
50 type: str
51 content_format:
52 description:
53 - Type of content of Nomad job.
54 choices: ["hcl", "json"]
55 default: hcl
56 type: str
57 seealso:
58 - name: Nomad jobs documentation
59 description: Complete documentation for Nomad API jobs.
60 link: https://www.nomadproject.io/api-docs/jobs/
61 """
62
63 EXAMPLES = r"""
64 - name: Create job
65 community.general.nomad_job:
66 host: localhost
67 state: present
68 content: "{{ lookup('ansible.builtin.file', 'job.hcl') }}"
69 timeout: 120
70
71 - name: Connect with port to create job
72 community.general.nomad_job:
73 host: localhost
74 port: 4645
75 state: present
76 content: "{{ lookup('ansible.builtin.file', 'job.hcl') }}"
77 timeout: 120
78
79 - name: Stop job
80 community.general.nomad_job:
81 host: localhost
82 state: absent
83 name: api
84
85 - name: Force job to start
86 community.general.nomad_job:
87 host: localhost
88 state: present
89 name: api
90 timeout: 120
91 force_start: true
92 """
93
94 import json
95
96 from ansible.module_utils.basic import AnsibleModule
97 from ansible.module_utils.common.text.converters import to_native
98
99 from ansible_collections.community.general.plugins.module_utils._nomad import argument_spec as nomad_argument_spec
100 from ansible_collections.community.general.plugins.module_utils._nomad import nomad, setup_nomad_client
101
102
103 def run():
104 module = AnsibleModule(
105 argument_spec={
106 **nomad_argument_spec,
107 "state": dict(required=True, choices=["present", "absent"]),
108 "name": dict(type="str"),
109 "content_format": dict(choices=["hcl", "json"], default="hcl"),
110 "content": dict(type="str"),
111 "force_start": dict(type="bool", default=False),
112 },
113 supports_check_mode=True,
114 mutually_exclusive=[["name", "content"]],
115 required_one_of=[["name", "content"]],
116 )
117
118 nomad_client = setup_nomad_client(module)
119
120 if module.params["state"] == "present":
121 if module.params["name"] and not module.params["force_start"]:
122 module.fail_json(msg="For start job with name, force_start is needed")
123
124 changed = False
125 if module.params["content"]:
126 if module.params["content_format"] == "json":
127 job_json = module.params["content"]
128 try:
129 job_json = json.loads(job_json)
130 except ValueError as e:
131 module.fail_json(msg=f"{e}")
132 job = {"job": job_json}
133 try:
134 job_id = job_json.get("ID")
135 if job_id is None:
136 module.fail_json(msg="Cannot retrieve job with ID None")
137 plan = nomad_client.job.plan_job(job_id, job, diff=True)
138 if plan["Diff"].get("Type") != "None":
139 changed = True
140 if not module.check_mode:
141 result = nomad_client.jobs.register_job(job)
142 else:
143 result = plan
144 else:
145 result = plan
146 except Exception as e:
147 module.fail_json(msg=f"{e}")
148
149 if module.params["content_format"] == "hcl":
150 try:
151 job_hcl = module.params["content"]
152 job_json = nomad_client.jobs.parse(job_hcl)
153 job = {"job": job_json}
154 except nomad.api.exceptions.BadRequestNomadException as err:
155 module.fail_json(msg=f"{err.nomad_resp.reason} {err.nomad_resp.text}")
156 try:
157 job_id = job_json.get("ID")
158 plan = nomad_client.job.plan_job(job_id, job, diff=True)
159 if plan["Diff"].get("Type") != "None":
160 changed = True
161 if not module.check_mode:
162 result = nomad_client.jobs.register_job(job)
163 else:
164 result = plan
165 else:
166 result = plan
167 except Exception as e:
168 module.fail_json(msg=f"{e}")
169
170 if module.params["force_start"]:
171 try:
172 if module.params["name"]:
173 job_name = module.params["name"]
174 else:
175 job_name = job_json["Name"]
176 job_json = nomad_client.job.get_job(job_name)
177 if job_json["Status"] == "running":
178 result = job_json
179 else:
180 job_json["Status"] = "running"
181 job_json["Stop"] = False
182 job = {"job": job_json}
183 if not module.check_mode:
184 result = nomad_client.jobs.register_job(job)
185 else:
186 result = nomad_client.validate.validate_job(job)
187 if result.status_code != 200:
188 module.fail_json(msg=to_native(result.text))
189 result = json.loads(result.text)
190 changed = True
191 except Exception as e:
192 module.fail_json(msg=f"{e}")
193
194 if module.params["state"] == "absent":
195 try:
196 if module.params["name"] is not None:
197 job_name = module.params["name"]
198 else:
199 if module.params["content_format"] == "hcl":
200 job_json = nomad_client.jobs.parse(module.params["content"])
201 job_name = job_json["Name"]
202 if module.params["content_format"] == "json":
203 job_json = module.params["content"]
204 job_name = job_json["Name"]
205 job = nomad_client.job.get_job(job_name)
206 if job["Status"] == "dead":
207 changed = False
208 result = job
209 else:
210 if not module.check_mode:
211 result = nomad_client.job.deregister_job(job_name)
212 else:
213 result = job
214 changed = True
215 except Exception as e:
216 module.fail_json(msg=f"{e}")
217
218 module.exit_json(changed=changed, result=result)
219
220
221 def main():
222 run()
223
224
225 if __name__ == "__main__":
226 main()