工作中学习的kolla-ansible用法
1. 添加module
ansible/library/test.py,用法就在EXAMPLES中
#!/usr/bin/env python
DOCUMENTATION = '''
---
module: test
short_description: This is a test module
description:
- This is a test module
options:
a:
description:
- a
required: True
type: str
b:
description:
- b
default: True
type: bool
author: test
'''
EXAMPLES = '''
Distribute a file from single to many hosts:
- hosts: test
tasks:
- name: Test module
test:
a: 'aaa'
b: True
'''
def main():
argument_spec = dict(
b=dict(default=True, type='bool'),
a=dict(type='str')
)
module = AnsibleModule(argument_spec)
b = module.params.get('b')
if b:
module.exit_json(msg=module.params.get('a'))
module.fail_json(msg='error')
# import module snippets
from ansible.module_utils.basic import * # noqa
if __name__ == '__main__':
main()
2. module中执行命令
rc表示命令执行的数字结果,err表示错误内容,out表示正确的输出结果
(rc, out, err) = module.run_command("cat /etc/hosts")
if rc != 0:
module.fail_json(msg=str(err))
module.exit_json(msg=out)
3. kolla-ansible创建新命令
ansible/test.yml
hosts表示执行的节点
---
- name:Test command
hosts: localhost
roles:
- test
创建test role
ansible/roles/test/
defaults/mian.yml为定义的一些默认值
tasks/mian.yml为kolla-ansible执行的任务
test
|- defaults
| |- main.yml
|- tasks
| |- main.yml
defaults/mian.yml
a: "aaa"
tasks/mian.yml
- name: Test command
debug:
var: "{{ a }}"
tools/kolla-ansible中添加对应的值
Commands:
......
test test command
......
EOF
}
function bash_completion {
cat <<EOF
......
test
......
EOF
(test)
ACTION="Test command"
PLAYBOOK="${BASEDIR}/ansible/test.yml"
;;
}
kolla-ansible test执行即可
4. 发送文件到其他节点
可以将想共享的值放文件里面,然后发送到其他节点,其他节点直接读取文件即可,实现跨节点变量访问
- name: Send file to other node
hosts: all
become: true
copy:
content: "test"
dest: "/tmp/{{ item }}"
mode: 0644
delegate_to: "{{ item }}"
with_items: "{{ groups['control'] }}"
when:
- inventory_hostname == 'localhost'