Playbooks to a new Lilik
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.6 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function
  4. from ansible.module_utils.basic import *
  5. DOCUMENTATION = '''
  6. ---
  7. module: container_file_write
  8. author: Edoardo Putti
  9. short_description: Write to a file in a container
  10. description:
  11. - Write the content to a file
  12. options:
  13. name:
  14. required: true
  15. description:
  16. - Name of the container
  17. path:
  18. required: true
  19. description:
  20. - path of the file to check
  21. text:
  22. required: true
  23. description:
  24. - content to write
  25. append:
  26. required: false
  27. default: false
  28. description:
  29. - append instead of overwrite
  30. '''
  31. def write_file_in_container(args):
  32. (path, text) = args
  33. with open(path, 'w') as out:
  34. out.write(text)
  35. return 0
  36. def append_file_in_container(path, text):
  37. with open(path, 'a') as out:
  38. out.write(text)
  39. return 0
  40. def main():
  41. module = AnsibleModule(
  42. argument_spec = dict(
  43. name = dict(
  44. required = True,
  45. type = 'str',
  46. ),
  47. path = dict(
  48. required = True,
  49. type = 'str',
  50. ),
  51. text = dict(
  52. required = True,
  53. type = 'str',
  54. ),
  55. append = dict(
  56. default = False,
  57. required = False,
  58. type = 'bool',
  59. ),
  60. ),
  61. )
  62. try:
  63. import lxc
  64. except ImportError:
  65. module.fail_json(
  66. changed = False,
  67. failed = True,
  68. msg = 'Error importing lxc, is python-lxc installed?',
  69. )
  70. container_name = module.params.get('name')
  71. file_path = module.params.get('path')
  72. text = module.params.get('text')
  73. append = module.params.get('append')
  74. result = {}
  75. result['name'] = container_name
  76. result['path'] = file_path
  77. if container_name in lxc.list_containers():
  78. container = lxc.Container(container_name)
  79. if append:
  80. writing_function = append_file_in_container
  81. else:
  82. writing_function = write_file_in_container
  83. file_exists = container.attach_wait(
  84. writing_function,
  85. (file_path, text,),
  86. env_policy = lxc.LXC_ATTACH_CLEAR_ENV,
  87. )
  88. else:
  89. result['changed'] = False
  90. result['failed'] = True
  91. result['msg'] = "Target container does not exists"
  92. module.exit_json(**result)
  93. if __name__ == '__main__':
  94. main()