Created
May 22, 2018 19:11
-
-
Save krdlab/77d92a6535a099945c7a5759336f0aac to your computer and use it in GitHub Desktop.
Ansible モジュールのサンプル (check mode と diff 無しバージョン)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from tempfile import gettempdir | |
from ansible.module_utils.basic import AnsibleModule | |
def read(path): | |
with open(path, 'r') as f: | |
return f.read() | |
def write(path, text): | |
with open(path, 'w') as f: | |
f.write(text) | |
def ensure_present(path, text): | |
if os.path.exists(path): | |
curr_text = read(path) | |
if curr_text == text: | |
return False | |
else: | |
write(path, text) | |
return True | |
else: | |
write(path, text) | |
return True | |
def ensure_absent(path): | |
if os.path.exists(path): | |
os.remove(path) | |
return True | |
else: | |
return False | |
def main(): | |
module = AnsibleModule( | |
argument_spec=dict( | |
name=dict(required=True, type='path'), | |
text=dict(required=True), | |
state=dict(choices=['present', 'absent'], default=None) | |
) | |
) | |
name = module.params['name'] | |
text = module.params['text'] | |
state = module.params['state'] | |
path = os.path.join(gettempdir(), name) | |
changed = False | |
if state == 'present': | |
changed = ensure_present(path, text) | |
else: | |
changed = ensure_absent(path) | |
result = dict( | |
changed=changed, | |
tmpfile=dict( | |
name=name, | |
path=path, | |
text=text, | |
state=state | |
) | |
) | |
module.exit_json(**result) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment