趁周末把ansible action plugin 写了一个简单的例子,我们日常工作中可能很少会用到action plugin ,但是如果我们能通过action plugin 做一些初始化的工作,例如设定一些默认值,这样我们的ansible playbook 可能会简介很多
例如我们写了一个module需要传递2个参数,如果我们这个module 要写很多次,例如10次,那么我就要传递20次参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
- name: this is a test module backup: src: /srv/online/1.html backupsrc: /srv/backup - name: this is a test module backup: src: /srv/online/2.html backupsrc: /srv/backup - name: this is a test module backup: src: /srv/online/3.html backupsrc: /srv/backup |
这里我们有个backupsrc 其实是一摸一样的,我们可以写一个action plugin,在调用module之前把backupsrc统一设定为 /srv/back
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
- name: this is a test module backup: src: /srv/online/1.html - name: this is a test module backup: src: /srv/online/2.html - name: this is a test module backup: src: /srv/online/3.html |
所以可以简化为上边的版本
我写了一个简单的action plugin ,叫hello , 作用和shell module一摸一样,就是你传递命令过去,他给你返回值
首先,说一下action plugin存放的目录,可以放到环境变量里,也可以修改ansbile.cfg, 最简单的就是在我们的playbook所在的目录下创建一个文件夹叫“:action_plugins
1 2 |
action_plugins └── hello.py |
hello.py的源码:
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 |
#!/usr/bin/python EXAMPLES = ''' # this is the first action plugin - hello: src: src/ansible-mssql/files/enable_always_on.sql dest: /root/enable_alwasy_on.sql '''.replace('\t', ' ') RETURN = ''' name: description: The name of the user that was added returned: success type: string sample: foo '''.replace('\t', ' ') import os import subprocess from ansible.plugins.action import ActionBase, AnsibleActionFail from ansible.errors import AnsibleAction class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect new_module_args = self._task.args.copy() changed = False module_return = dict(changed=False) cmd = self._task.args.get('cmd', None) new_module_args["_raw_params"] = cmd new_module_args["_uses_shell"] = "true" new_module_args.pop("cmd", None) print(new_module_args) try: module_return = self._execute_module(module_name='command', module_args=new_module_args, task_vars=task_vars) except AnsibleAction as e: result.update(e.result) return result print(module_return) if module_return.get('changed'): changed = True if module_return: result.update(module_return) else: result.update(dict(cmd=cmd, changed=changed)) return result |
代码很简单,就是调用了一下command 这个module
测试用的test.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
--- - hosts: localhost tasks: - name: test debug: var: inventory_hostname - hello: cmd: date register: d - debug: var: d.stdout - hello: cmd: whoami register: w - debug: var: w.stdout |
抛砖引玉…..
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021