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

#!/usr/bin/python 

# -*- coding: utf-8 -*- 

 

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

# Copyright: (c) 2017, Ansible Project 

# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 

 

from __future__ import absolute_import, division, print_function 

__metaclass__ = type 

 

ANSIBLE_METADATA = {'metadata_version': '1.1', 

'status': ['stableinterface'], 

'supported_by': 'core'} 

 

 

DOCUMENTATION = ''' 

--- 

module: file 

version_added: "historical" 

short_description: Sets attributes of files 

extends_documentation_fragment: files 

description: 

- Sets attributes of files, symlinks, and directories, or removes 

files/symlinks/directories. Many other modules support the same options as 

the C(file) module - including M(copy), M(template), and M(assemble). 

- For Windows targets, use the M(win_file) module instead. 

notes: 

- For Windows targets, use the M(win_file) module instead. 

- See also M(copy), M(template), M(assemble) 

author: 

- Ansible Core Team 

- Michael DeHaan 

options: 

path: 

description: 

- 'path to the file being managed. Aliases: I(dest), I(name)' 

required: true 

aliases: [ dest, name ] 

state: 

description: 

- If C(directory), all immediate subdirectories will be created if they 

do not exist, since 1.7 they will be created with the supplied permissions. 

If C(file), the file will NOT be created if it does not exist, see the M(copy) 

or M(template) module if you want that behavior. If C(link), the symbolic 

link will be created or changed. Use C(hard) for hardlinks. If C(absent), 

directories will be recursively deleted, and files or symlinks will be unlinked. 

Note that C(absent) will not cause C(file) to fail if the C(path) does not exist 

as the state did not change. 

If C(touch) (new in 1.4), an empty file will be created if the C(path) does not 

exist, while an existing file or directory will receive updated file access and 

modification times (similar to the way `touch` works from the command line). 

default: file 

choices: [ absent, directory, file, hard, link, touch ] 

src: 

description: 

- path of the file to link to (applies only to C(state=link) and C(state=hard)). Will accept absolute, 

relative and nonexisting paths. Relative paths are not expanded. 

recurse: 

description: 

- recursively set the specified file attributes (applies only to state=directory) 

type: bool 

default: 'no' 

version_added: "1.1" 

force: 

description: 

- 'force the creation of the symlinks in two cases: the source file does 

not exist (but will appear later); the destination exists and is a file (so, we need to unlink the 

"path" file and create symlink to the "src" file in place of it).' 

type: bool 

default: 'no' 

follow: 

description: 

- 'This flag indicates that filesystem links, if they exist, should be followed.' 

- 'Previous to Ansible 2.5, this was C(no) by default.' 

type: bool 

default: 'yes' 

version_added: "1.8" 

''' 

 

EXAMPLES = ''' 

# change file ownership, group and mode. When specifying mode using octal numbers, first digit should always be 0. 

- file: 

path: /etc/foo.conf 

owner: foo 

group: foo 

mode: 0644 

- file: 

path: /work 

owner: root 

group: root 

mode: 01777 

- file: 

src: /file/to/link/to 

dest: /path/to/symlink 

owner: foo 

group: foo 

state: link 

- file: 

src: '/tmp/{{ item.src }}' 

dest: '{{ item.dest }}' 

state: link 

with_items: 

- { src: 'x', dest: 'y' } 

- { src: 'z', dest: 'k' } 

 

# touch a file, using symbolic modes to set the permissions (equivalent to 0644) 

- file: 

path: /etc/foo.conf 

state: touch 

mode: "u=rw,g=r,o=r" 

 

# touch the same file, but add/remove some permissions 

- file: 

path: /etc/foo.conf 

state: touch 

mode: "u+rw,g-wx,o-rwx" 

 

# create a directory if it doesn't exist 

- file: 

path: /etc/some_directory 

state: directory 

mode: 0755 

''' 

 

import errno 

import os 

import shutil 

import time 

 

# import module snippets 

from ansible.module_utils.basic import AnsibleModule 

from ansible.module_utils.six import b 

from ansible.module_utils._text import to_bytes, to_native 

 

 

def get_state(b_path): 

''' Find out current state ''' 

 

139 ↛ 150line 139 didn't jump to line 150, because the condition on line 139 was never false if os.path.lexists(b_path): 

140 ↛ 141line 140 didn't jump to line 141, because the condition on line 140 was never true if os.path.islink(b_path): 

return 'link' 

142 ↛ 143line 142 didn't jump to line 143, because the condition on line 142 was never true elif os.path.isdir(b_path): 

return 'directory' 

144 ↛ 145line 144 didn't jump to line 145, because the condition on line 144 was never true elif os.stat(b_path).st_nlink > 1: 

return 'hard' 

 

# could be many other things, but defaulting to file 

return 'file' 

 

return 'absent' 

 

 

def recursive_set_attributes(module, b_path, follow, file_args): 

changed = False 

for b_root, b_dirs, b_files in os.walk(b_path): 

for b_fsobj in b_dirs + b_files: 

b_fsname = os.path.join(b_root, b_fsobj) 

if not os.path.islink(b_fsname): 

tmp_file_args = file_args.copy() 

tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict') 

changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False) 

else: 

tmp_file_args = file_args.copy() 

tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict') 

changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False) 

if follow: 

b_fsname = os.path.join(b_root, os.readlink(b_fsname)) 

if os.path.isdir(b_fsname): 

changed |= recursive_set_attributes(module, b_fsname, follow, file_args) 

tmp_file_args = file_args.copy() 

tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict') 

changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False) 

return changed 

 

 

def main(): 

 

module = AnsibleModule( 

argument_spec=dict( 

state=dict(choices=['file', 'directory', 'link', 'hard', 'touch', 'absent'], default=None), 

path=dict(aliases=['dest', 'name'], required=True, type='path'), 

original_basename=dict(required=False), # Internal use only, for recursive ops 

recurse=dict(default=False, type='bool'), 

force=dict(required=False, default=False, type='bool'), 

follow=dict(required=False, default=False, type='bool'), 

diff_peek=dict(default=None), # Internal use only, for internal checks in the action plugins 

validate=dict(required=False, default=None), # Internal use only, for template and copy 

src=dict(required=False, default=None, type='path'), 

), 

add_file_common_args=True, 

supports_check_mode=True 

) 

 

params = module.params 

state = params['state'] 

recurse = params['recurse'] 

force = params['force'] 

diff_peek = params['diff_peek'] 

src = params['src'] 

b_src = to_bytes(src, errors='surrogate_or_strict') 

follow = params['follow'] 

 

# modify source as we later reload and pass, specially relevant when used by other modules. 

path = params['path'] 

b_path = to_bytes(path, errors='surrogate_or_strict') 

 

# short-circuit for diff_peek 

208 ↛ 209line 208 didn't jump to line 209, because the condition on line 208 was never true if diff_peek is not None: 

appears_binary = False 

try: 

f = open(b_path, 'rb') 

head = f.read(8192) 

f.close() 

if b("\x00") in head: 

appears_binary = True 

except: 

pass 

module.exit_json(path=path, changed=False, appears_binary=appears_binary) 

 

prev_state = get_state(b_path) 

 

# state should default to file, but since that creates many conflicts, 

# default to 'current' when it exists. 

224 ↛ 225line 224 didn't jump to line 225, because the condition on line 224 was never true if state is None: 

if prev_state != 'absent': 

state = prev_state 

elif recurse: 

state = 'directory' 

else: 

state = 'file' 

 

# source is both the source of a symlink or an informational passing of the src for a template module 

# or copy module, even if this module never uses it, it is needed to key off some things 

234 ↛ 244line 234 didn't jump to line 244, because the condition on line 234 was never false if src is None: 

235 ↛ 236line 235 didn't jump to line 236, because the condition on line 235 was never true if state in ('link', 'hard'): 

if follow and state == 'link': 

# use the current target of the link as the source 

src = to_native(os.path.realpath(b_path), errors='strict') 

b_src = to_bytes(os.path.realpath(b_path), errors='strict') 

else: 

module.fail_json(msg='src and dest are required for creating links') 

 

# original_basename is used by other modules that depend on file. 

244 ↛ 245line 244 didn't jump to line 245, because the condition on line 244 was never true if state not in ("link", "absent") and os.path.isdir(b_path): 

basename = None 

if params['original_basename']: 

basename = params['original_basename'] 

elif src is not None: 

basename = os.path.basename(src) 

if basename: 

params['path'] = path = os.path.join(path, basename) 

b_path = to_bytes(path, errors='surrogate_or_strict') 

prev_state = get_state(b_path) 

 

# make sure the target path is a directory when we're doing a recursive operation 

256 ↛ 257line 256 didn't jump to line 257, because the condition on line 256 was never true if recurse and state != 'directory': 

module.fail_json(path=path, msg="recurse option requires state to be 'directory'") 

 

file_args = module.load_file_common_arguments(params) 

 

changed = False 

diff = {'before': {'path': path}, 

'after': {'path': path}, 

} 

 

state_change = False 

267 ↛ 272line 267 didn't jump to line 272, because the condition on line 267 was never false if prev_state != state: 

diff['before']['state'] = prev_state 

diff['after']['state'] = state 

state_change = True 

 

272 ↛ 289line 272 didn't jump to line 289, because the condition on line 272 was never false if state == 'absent': 

273 ↛ 287line 273 didn't jump to line 287, because the condition on line 273 was never false if state_change: 

274 ↛ 285line 274 didn't jump to line 285, because the condition on line 274 was never false if not module.check_mode: 

275 ↛ 276line 275 didn't jump to line 276, because the condition on line 275 was never true if prev_state == 'directory': 

try: 

shutil.rmtree(b_path, ignore_errors=False) 

except Exception as e: 

module.fail_json(msg="rmtree failed: %s" % to_native(e)) 

else: 

try: 

os.unlink(b_path) 

except Exception as e: 

module.fail_json(path=path, msg="unlinking failed: %s " % to_native(e)) 

module.exit_json(path=path, changed=True, diff=diff) 

else: 

module.exit_json(path=path, changed=False) 

 

elif state == 'file': 

 

if state_change: 

if follow and prev_state == 'link': 

# follow symlink and operate on original 

b_path = os.path.realpath(b_path) 

path = to_native(b_path, errors='strict') 

prev_state = get_state(b_path) 

file_args['path'] = path 

 

if prev_state not in ('file', 'hard'): 

# file is not absent and any other state is a conflict 

module.fail_json(path=path, msg='file (%s) is %s, cannot continue' % (path, prev_state)) 

 

changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) 

module.exit_json(path=path, changed=changed, diff=diff) 

 

elif state == 'directory': 

if follow and prev_state == 'link': 

b_path = os.path.realpath(b_path) 

path = to_native(b_path, errors='strict') 

prev_state = get_state(b_path) 

 

if prev_state == 'absent': 

if module.check_mode: 

module.exit_json(changed=True, diff=diff) 

changed = True 

curpath = '' 

 

try: 

# Split the path so we can apply filesystem attributes recursively 

# from the root (/) directory for absolute paths or the base path 

# of a relative path. We can then walk the appropriate directory 

# path to apply attributes. 

for dirname in path.strip('/').split('/'): 

curpath = '/'.join([curpath, dirname]) 

# Remove leading slash if we're creating a relative path 

if not os.path.isabs(path): 

curpath = curpath.lstrip('/') 

b_curpath = to_bytes(curpath, errors='surrogate_or_strict') 

if not os.path.exists(b_curpath): 

try: 

os.mkdir(b_curpath) 

except OSError as ex: 

# Possibly something else created the dir since the os.path.exists 

# check above. As long as it's a dir, we don't need to error out. 

if not (ex.errno == errno.EEXIST and os.path.isdir(b_curpath)): 

raise 

tmp_file_args = file_args.copy() 

tmp_file_args['path'] = curpath 

changed = module.set_fs_attributes_if_different(tmp_file_args, changed, diff, expand=False) 

except Exception as e: 

module.fail_json(path=path, msg='There was an issue creating %s as requested: %s' % (curpath, to_native(e))) 

 

# We already know prev_state is not 'absent', therefore it exists in some form. 

elif prev_state != 'directory': 

module.fail_json(path=path, msg='%s already exists as a %s' % (path, prev_state)) 

 

changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) 

 

if recurse: 

changed |= recursive_set_attributes(module, to_bytes(file_args['path'], errors='surrogate_or_strict'), follow, file_args) 

 

module.exit_json(path=path, changed=changed, diff=diff) 

 

elif state in ('link', 'hard'): 

 

if not os.path.islink(b_path) and os.path.isdir(b_path): 

relpath = path 

else: 

b_relpath = os.path.dirname(b_path) 

relpath = to_native(b_relpath, errors='strict') 

 

absrc = os.path.join(relpath, src) 

b_absrc = to_bytes(absrc, errors='surrogate_or_strict') 

if not force and not os.path.exists(b_absrc): 

module.fail_json(path=path, src=src, msg='src file does not exist, use "force=yes" if you really want to create the link: %s' % absrc) 

 

if state == 'hard': 

if not os.path.isabs(b_src): 

module.fail_json(msg="absolute paths are required") 

elif prev_state == 'directory': 

if not force: 

module.fail_json(path=path, msg='refusing to convert between %s and %s for %s' % (prev_state, state, path)) 

elif os.listdir(b_path): 

# refuse to replace a directory that has files in it 

module.fail_json(path=path, msg='the directory %s is not empty, refusing to convert it' % path) 

elif prev_state in ('file', 'hard') and not force: 

module.fail_json(path=path, msg='refusing to convert between %s and %s for %s' % (prev_state, state, path)) 

 

if prev_state == 'absent': 

changed = True 

elif prev_state == 'link': 

b_old_src = os.readlink(b_path) 

if b_old_src != b_src: 

diff['before']['src'] = to_native(b_old_src, errors='strict') 

diff['after']['src'] = src 

changed = True 

elif prev_state == 'hard': 

if not (state == 'hard' and os.stat(b_path).st_ino == os.stat(b_src).st_ino): 

changed = True 

if not force: 

module.fail_json(dest=path, src=src, msg='Cannot link, different hard link exists at destination') 

elif prev_state == 'file': 

changed = True 

if not force: 

module.fail_json(dest=path, src=src, msg='Cannot link, %s exists at destination' % prev_state) 

elif prev_state == 'directory': 

changed = True 

if os.path.exists(b_path): 

if state == 'hard' and os.stat(b_path).st_ino == os.stat(b_src).st_ino: 

module.exit_json(path=path, changed=False) 

elif not force: 

module.fail_json(dest=path, src=src, msg='Cannot link, different hard link exists at destination') 

else: 

module.fail_json(dest=path, src=src, msg='unexpected position reached') 

 

if changed and not module.check_mode: 

if prev_state != 'absent': 

# try to replace atomically 

b_tmppath = to_bytes(os.path.sep).join( 

[os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))] 

) 

try: 

if prev_state == 'directory' and state == 'link': 

os.rmdir(b_path) 

elif prev_state == 'directory' and state == 'hard': 

if os.path.exists(b_path): 

os.remove(b_path) 

if state == 'hard': 

os.link(b_src, b_tmppath) 

else: 

os.symlink(b_src, b_tmppath) 

os.rename(b_tmppath, b_path) 

except OSError as e: 

if os.path.exists(b_tmppath): 

os.unlink(b_tmppath) 

module.fail_json(path=path, msg='Error while replacing: %s' % to_native(e, nonstring='simplerepr')) 

else: 

try: 

if state == 'hard': 

os.link(b_src, b_path) 

else: 

os.symlink(b_src, b_path) 

except OSError as e: 

module.fail_json(path=path, msg='Error while linking: %s' % to_native(e, nonstring='simplerepr')) 

 

if module.check_mode and not os.path.exists(b_path): 

module.exit_json(dest=path, src=src, changed=changed, diff=diff) 

 

changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) 

module.exit_json(dest=path, src=src, changed=changed, diff=diff) 

 

elif state == 'touch': 

if not module.check_mode: 

 

if prev_state == 'absent': 

try: 

open(b_path, 'wb').close() 

except (OSError, IOError) as e: 

module.fail_json(path=path, msg='Error, could not touch target: %s' % to_native(e, nonstring='simplerepr')) 

elif prev_state in ('file', 'directory', 'hard'): 

try: 

os.utime(b_path, None) 

except OSError as e: 

module.fail_json(path=path, msg='Error while touching existing target: %s' % to_native(e, nonstring='simplerepr')) 

else: 

module.fail_json(msg='Cannot touch other than files, directories, and hardlinks (%s is %s)' % (path, prev_state)) 

try: 

module.set_fs_attributes_if_different(file_args, True, diff, expand=False) 

except SystemExit as e: 

if e.code: 

# We take this to mean that fail_json() was called from 

# somewhere in basic.py 

if prev_state == 'absent': 

# If we just created the file we can safely remove it 

os.remove(b_path) 

raise e 

 

module.exit_json(dest=path, changed=True, diff=diff) 

 

module.fail_json(path=path, msg='unexpected position reached') 

 

472 ↛ exitline 472 didn't exit the module, because the condition on line 472 was never falseif __name__ == '__main__': 

main()