Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> 

# 

# This file is part of Ansible 

# 

# Ansible is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# Ansible is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with Ansible. If not, see <http://www.gnu.org/licenses/>. 

 

# Make coding more python3-ish 

from __future__ import (absolute_import, division, print_function) 

__metaclass__ = type 

 

import os 

 

from ansible import constants as C 

from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleAssertionError 

from ansible.module_utils.six import iteritems, string_types 

from ansible.module_utils._text import to_native 

from ansible.parsing.mod_args import ModuleArgsParser 

from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject, AnsibleMapping 

from ansible.plugins.loader import lookup_loader 

from ansible.playbook.attribute import FieldAttribute 

from ansible.playbook.base import Base 

from ansible.playbook.become import Become 

from ansible.playbook.block import Block 

from ansible.playbook.conditional import Conditional 

from ansible.playbook.loop_control import LoopControl 

from ansible.playbook.role import Role 

from ansible.playbook.taggable import Taggable 

 

 

try: 

from __main__ import display 

except ImportError: 

from ansible.utils.display import Display 

display = Display() 

 

__all__ = ['Task'] 

 

 

class Task(Base, Conditional, Taggable, Become): 

 

""" 

A task is a language feature that represents a call to a module, with given arguments and other parameters. 

A handler is a subclass of a task. 

 

Usage: 

 

Task.load(datastructure) -> Task 

Task.something(...) 

""" 

 

# ================================================================================= 

# ATTRIBUTES 

# load_<attribute_name> and 

# validate_<attribute_name> 

# will be used if defined 

# might be possible to define others 

 

_args = FieldAttribute(isa='dict', default=dict()) 

_action = FieldAttribute(isa='string') 

 

_async_val = FieldAttribute(isa='int', default=0, alias='async') 

_changed_when = FieldAttribute(isa='list', default=[]) 

_delay = FieldAttribute(isa='int', default=5) 

_delegate_to = FieldAttribute(isa='string') 

_delegate_facts = FieldAttribute(isa='bool', default=False) 

_failed_when = FieldAttribute(isa='list', default=[]) 

_loop = FieldAttribute() 

_loop_control = FieldAttribute(isa='class', class_type=LoopControl, inherit=False) 

_notify = FieldAttribute(isa='list') 

_poll = FieldAttribute(isa='int', default=10) 

_register = FieldAttribute(isa='string') 

_retries = FieldAttribute(isa='int', default=3) 

_until = FieldAttribute(isa='list', default=[]) 

 

# deprecated, used to be loop and loop_args but loop has been repurposed 

_loop_with = FieldAttribute(isa='string', private=True, inherit=False) 

 

def __init__(self, block=None, role=None, task_include=None): 

''' constructors a task, without the Task.load classmethod, it will be pretty blank ''' 

 

self._role = role 

self._parent = None 

 

95 ↛ 96line 95 didn't jump to line 96, because the condition on line 95 was never true if task_include: 

self._parent = task_include 

else: 

self._parent = block 

 

super(Task, self).__init__() 

 

def get_path(self): 

''' return the absolute path of the task with its line number ''' 

 

path = "" 

106 ↛ 108line 106 didn't jump to line 108, because the condition on line 106 was never false if hasattr(self, '_ds') and hasattr(self._ds, '_data_source') and hasattr(self._ds, '_line_number'): 

path = "%s:%s" % (self._ds._data_source, self._ds._line_number) 

elif hasattr(self._parent._play, '_ds') and hasattr(self._parent._play._ds, '_data_source') and hasattr(self._parent._play._ds, '_line_number'): 

path = "%s:%s" % (self._parent._play._ds._data_source, self._parent._play._ds._line_number) 

return path 

 

def get_name(self): 

''' return the name of the task ''' 

 

if self._role and self.name and ("%s : " % self._role._role_name) not in self.name: 

return "%s : %s" % (self._role.get_name(), self.name) 

117 ↛ 118line 117 didn't jump to line 118, because the condition on line 117 was never true elif self.name: 

return self.name 

else: 

if self._role: 

return "%s : %s" % (self._role.get_name(), self.action) 

else: 

return "%s" % (self.action,) 

 

def _merge_kv(self, ds): 

if ds is None: 

return "" 

elif isinstance(ds, string_types): 

return ds 

elif isinstance(ds, dict): 

buf = "" 

for (k, v) in iteritems(ds): 

if k.startswith('_'): 

continue 

buf = buf + "%s=%s " % (k, v) 

buf = buf.strip() 

return buf 

 

@staticmethod 

def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None): 

t = Task(block=block, role=role, task_include=task_include) 

return t.load_data(data, variable_manager=variable_manager, loader=loader) 

 

def __repr__(self): 

''' returns a human readable representation of the task ''' 

if self.get_name() == 'meta': 

return "TASK: meta (%s)" % self.args['_raw_params'] 

else: 

return "TASK: %s" % self.get_name() 

 

def _preprocess_with_loop(self, ds, new_ds, k, v): 

''' take a lookup plugin name and store it correctly ''' 

 

loop_name = k.replace("with_", "") 

155 ↛ 156line 155 didn't jump to line 156, because the condition on line 155 was never true if new_ds.get('loop') is not None or new_ds.get('loop_with') is not None: 

raise AnsibleError("duplicate loop in task: %s" % loop_name, obj=ds) 

157 ↛ 158line 157 didn't jump to line 158, because the condition on line 157 was never true if v is None: 

raise AnsibleError("you must specify a value when using %s" % k, obj=ds) 

new_ds['loop_with'] = loop_name 

new_ds['loop'] = v 

# FIXME: reenable afte 2.5 

# display.deprecated("with_ type loops are being phased out, use the 'loop' keyword instead", version="2.10") 

 

def preprocess_data(self, ds): 

''' 

tasks are especially complex arguments so need pre-processing. 

keep it short. 

''' 

 

170 ↛ 171line 170 didn't jump to line 171, because the condition on line 170 was never true if not isinstance(ds, dict): 

raise AnsibleAssertionError('ds (%s) should be a dict but was a %s' % (ds, type(ds))) 

 

# the new, cleaned datastructure, which will have legacy 

# items reduced to a standard structure suitable for the 

# attributes of the task class 

new_ds = AnsibleMapping() 

if isinstance(ds, AnsibleBaseYAMLObject): 

new_ds.ansible_pos = ds.ansible_pos 

 

# use the args parsing class to determine the action, args, 

# and the delegate_to value from the various possible forms 

# supported as legacy 

args_parser = ModuleArgsParser(task_ds=ds) 

try: 

(action, args, delegate_to) = args_parser.parse() 

except AnsibleParserError as e: 

raise AnsibleParserError(to_native(e), obj=ds, orig_exc=e) 

 

# the command/shell/script modules used to support the `cmd` arg, 

# which corresponds to what we now call _raw_params, so move that 

# value over to _raw_params (assuming it is empty) 

192 ↛ 193line 192 didn't jump to line 193, because the condition on line 192 was never true if action in ('command', 'shell', 'script'): 

if 'cmd' in args: 

if args.get('_raw_params', '') != '': 

raise AnsibleError("The 'cmd' argument cannot be used when other raw parameters are specified." 

" Please put everything in one or the other place.", obj=ds) 

args['_raw_params'] = args.pop('cmd') 

 

new_ds['action'] = action 

new_ds['args'] = args 

new_ds['delegate_to'] = delegate_to 

 

# we handle any 'vars' specified in the ds here, as we may 

# be adding things to them below (special handling for includes). 

# When that deprecated feature is removed, this can be too. 

206 ↛ 209line 206 didn't jump to line 209, because the condition on line 206 was never true if 'vars' in ds: 

# _load_vars is defined in Base, and is used to load a dictionary 

# or list of dictionaries in a standard way 

new_ds['vars'] = self._load_vars(None, ds.get('vars')) 

else: 

new_ds['vars'] = dict() 

 

for (k, v) in iteritems(ds): 

214 ↛ 216line 214 didn't jump to line 216, because the condition on line 214 was never true if k in ('action', 'local_action', 'args', 'delegate_to') or k == action or k == 'shell': 

# we don't want to re-assign these values, which were determined by the ModuleArgsParser() above 

continue 

elif k.startswith('with_') and k.replace("with_", "") in lookup_loader: 

# transform into loop property 

self._preprocess_with_loop(ds, new_ds, k, v) 

else: 

# pre-2.0 syntax allowed variables for include statements at the top level of the task, 

# so we move those into the 'vars' dictionary here, and show a deprecation message 

# as we will remove this at some point in the future. 

224 ↛ 225line 224 didn't jump to line 225, because the condition on line 224 was never true if action in ('include', 'include_tasks') and k not in self._valid_attrs and k not in self.DEPRECATED_ATTRIBUTES: 

display.deprecated("Specifying include variables at the top-level of the task is deprecated." 

" Please see:\nhttp://docs.ansible.com/ansible/playbooks_roles.html#task-include-files-and-encouraging-reuse\n\n" 

" for currently supported syntax regarding included files and variables", version="2.7") 

new_ds['vars'][k] = v 

229 ↛ 232line 229 didn't jump to line 232, because the condition on line 229 was never false elif k in self._valid_attrs: 

new_ds[k] = v 

else: 

display.warning("Ignoring invalid attribute: %s" % k) 

 

return super(Task, self).preprocess_data(new_ds) 

 

def _load_loop_control(self, attr, ds): 

237 ↛ 238line 237 didn't jump to line 238, because the condition on line 237 was never true if not isinstance(ds, dict): 

raise AnsibleParserError( 

"the `loop_control` value must be specified as a dictionary and cannot " 

"be a variable itself (though it can contain variables)", 

obj=ds, 

) 

 

return LoopControl.load(data=ds, variable_manager=self._variable_manager, loader=self._loader) 

 

def post_validate(self, templar): 

''' 

Override of base class post_validate, to also do final validation on 

the block and task include (if any) to which this task belongs. 

''' 

 

252 ↛ 255line 252 didn't jump to line 255, because the condition on line 252 was never false if self._parent: 

self._parent.post_validate(templar) 

 

super(Task, self).post_validate(templar) 

 

def _post_validate_loop(self, attr, value, templar): 

''' 

Override post validation for the loop field, which is templated 

specially in the TaskExecutor class when evaluating loops. 

''' 

return value 

 

def _post_validate_environment(self, attr, value, templar): 

''' 

Override post validation of vars on the play, as we don't want to 

template these too early. 

''' 

env = {} 

270 ↛ 301line 270 didn't jump to line 301, because the condition on line 270 was never false if value is not None: 

 

def _parse_env_kv(k, v): 

try: 

env[k] = templar.template(v, convert_bare=False) 

except AnsibleUndefinedVariable as e: 

if self.action in ('setup', 'gather_facts') and 'ansible_env' in to_native(e): 

# ignore as fact gathering sets ansible_env 

pass 

 

280 ↛ 292line 280 didn't jump to line 292, because the condition on line 280 was never false if isinstance(value, list): 

281 ↛ 282line 281 didn't jump to line 282, because the loop on line 281 never started for env_item in value: 

if isinstance(env_item, dict): 

for k in env_item: 

_parse_env_kv(k, env_item[k]) 

else: 

isdict = templar.template(env_item, convert_bare=False) 

if isinstance(isdict, dict): 

env.update(isdict) 

else: 

display.warning("could not parse environment value, skipping: %s" % value) 

 

elif isinstance(value, dict): 

# should not really happen 

env = dict() 

for env_item in value: 

_parse_env_kv(env_item, value[env_item]) 

else: 

# at this point it should be a simple string, also should not happen 

env = templar.template(value, convert_bare=False) 

 

return env 

 

def _post_validate_changed_when(self, attr, value, templar): 

''' 

changed_when is evaluated after the execution of the task is complete, 

and should not be templated during the regular post_validate step. 

''' 

return value 

 

def _post_validate_failed_when(self, attr, value, templar): 

''' 

failed_when is evaluated after the execution of the task is complete, 

and should not be templated during the regular post_validate step. 

''' 

return value 

 

def _post_validate_until(self, attr, value, templar): 

''' 

until is evaluated after the execution of the task is complete, 

and should not be templated during the regular post_validate step. 

''' 

return value 

 

def get_vars(self): 

all_vars = dict() 

326 ↛ 329line 326 didn't jump to line 329, because the condition on line 326 was never false if self._parent: 

all_vars.update(self._parent.get_vars()) 

 

all_vars.update(self.vars) 

 

331 ↛ 332line 331 didn't jump to line 332, because the condition on line 331 was never true if 'tags' in all_vars: 

del all_vars['tags'] 

333 ↛ 334line 333 didn't jump to line 334, because the condition on line 333 was never true if 'when' in all_vars: 

del all_vars['when'] 

 

return all_vars 

 

def get_include_params(self): 

all_vars = dict() 

340 ↛ 342line 340 didn't jump to line 342, because the condition on line 340 was never false if self._parent: 

all_vars.update(self._parent.get_include_params()) 

if self.action in ('include', 'include_tasks', 'include_role'): 

all_vars.update(self.vars) 

return all_vars 

 

def copy(self, exclude_parent=False, exclude_tasks=False): 

new_me = super(Task, self).copy() 

 

new_me._parent = None 

if self._parent and not exclude_parent: 

new_me._parent = self._parent.copy(exclude_tasks=exclude_tasks) 

 

new_me._role = None 

354 ↛ 357line 354 didn't jump to line 357, because the condition on line 354 was never false if self._role: 

new_me._role = self._role 

 

return new_me 

 

def serialize(self): 

data = super(Task, self).serialize() 

 

if not self._squashed and not self._finalized: 

if self._parent: 

data['parent'] = self._parent.serialize() 

data['parent_type'] = self._parent.__class__.__name__ 

 

if self._role: 

data['role'] = self._role.serialize() 

 

return data 

 

def deserialize(self, data): 

 

# import is here to avoid import loops 

from ansible.playbook.task_include import TaskInclude 

from ansible.playbook.handler_task_include import HandlerTaskInclude 

 

parent_data = data.get('parent', None) 

if parent_data: 

parent_type = data.get('parent_type') 

if parent_type == 'Block': 

p = Block() 

elif parent_type == 'TaskInclude': 

p = TaskInclude() 

elif parent_type == 'HandlerTaskInclude': 

p = HandlerTaskInclude() 

p.deserialize(parent_data) 

self._parent = p 

del data['parent'] 

 

role_data = data.get('role') 

if role_data: 

r = Role() 

r.deserialize(role_data) 

self._role = r 

del data['role'] 

 

super(Task, self).deserialize(data) 

 

def set_loader(self, loader): 

''' 

Sets the loader on this object and recursively on parent, child objects. 

This is used primarily after the Task has been serialized/deserialized, which 

does not preserve the loader. 

''' 

 

self._loader = loader 

 

if self._parent: 

self._parent.set_loader(loader) 

 

def _get_parent_attribute(self, attr, extend=False, prepend=False): 

''' 

Generic logic to get the attribute or parent attribute for a task value. 

''' 

 

extend = self._valid_attrs[attr].extend 

prepend = self._valid_attrs[attr].prepend 

try: 

value = self._attributes[attr] 

if self._parent and (value is None or extend): 

422 ↛ 436line 422 didn't jump to line 436, because the condition on line 422 was never false if getattr(self._parent, 'statically_loaded', True): 

# vars are always inheritable, other attributes might not be for the partent but still should be for other ancestors 

424 ↛ 427line 424 didn't jump to line 427, because the condition on line 424 was never false if attr != 'vars' and getattr(self._parent, '_inheritable', True) and hasattr(self._parent, '_get_parent_attribute'): 

parent_value = self._parent._get_parent_attribute(attr) 

else: 

parent_value = self._parent._attributes.get(attr, None) 

 

if extend: 

value = self._extend_value(value, parent_value, prepend) 

else: 

value = parent_value 

except KeyError: 

pass 

 

return value 

 

def _get_attr_any_errors_fatal(self): 

value = self._attributes['any_errors_fatal'] 

if value is None: 

value = self._get_parent_attribute('any_errors_fatal') 

if value is None: 

value = C.ANY_ERRORS_FATAL 

return value 

 

def get_dep_chain(self): 

447 ↛ 450line 447 didn't jump to line 450, because the condition on line 447 was never false if self._parent: 

return self._parent.get_dep_chain() 

else: 

return None 

 

def get_search_path(self): 

''' 

Return the list of paths you should search for files, in order. 

This follows role/playbook dependency chain. 

''' 

path_stack = [] 

 

dep_chain = self.get_dep_chain() 

# inside role: add the dependency chain from current to dependent 

461 ↛ 465line 461 didn't jump to line 465, because the condition on line 461 was never false if dep_chain: 

path_stack.extend(reversed([x._role_path for x in dep_chain])) 

 

# add path of task itself, unless it is already in the list 

task_dir = os.path.dirname(self.get_path()) 

466 ↛ 469line 466 didn't jump to line 469, because the condition on line 466 was never false if task_dir not in path_stack: 

path_stack.append(task_dir) 

 

return path_stack 

 

def all_parents_static(self): 

472 ↛ 474line 472 didn't jump to line 474, because the condition on line 472 was never false if self._parent: 

return self._parent.all_parents_static() 

return True 

 

def get_first_parent_include(self): 

from ansible.playbook.task_include import TaskInclude 

if self._parent: 

if isinstance(self._parent, TaskInclude): 

return self._parent 

return self._parent.get_first_parent_include() 

return None