一、Ansibledoc是什么
Ansibledoc 是 Ansible 的一个功能,旨在自动生成 Ansible 模块以及插件的文档。通过 Ansibledoc 可以自动生成标准的文件头部信息、模块的简介以及各项参数的描述与样例。Ansibledoc 采用 yum 的风格来进行文档描述,并且支持自定义标签。
二、Ansibledoc应用场景
Ansibledoc 可以应用于文档维护以及开发测试场景中:
1、 编写 Ansible 模块代码时,可以使用 Ansible doc 对参数的解释和参数的使用进行说明,提高代码的可阅读性,规范代码开发。
2、 对于 Ansible Role 模块,使用 Ansibledoc 可以自动生成 Markdown 格式的文档页面,方便用户查看使用方法和参数介绍。
三、Ansibledoc示例-生成Ansible Role模块文档
在 Ansible Role 模块中,我们通常将 Ansibledoc 插入到 role 文件夹下的 README.md 文件中,然后通过 GitHub Pages 或者使用其他 Markdown 渲染工具来查看文档。
示例:我们创建 ansibledoc_demo 角色,并设计一些参数:
- name: ansibledoc_demo
hosts: all
vars:
username: debugtalk
password: p@ssword
roles:
- role: ansible_role_test
然后我们为这个角色创建 README.md 文件,并插入 Ansibledoc 代码:
# Ansible Role: ansible_role_test Insert your introduction here. ## Role variables ### Required variables | Variable Name | Variable Description | Default Value | |---------------|----------------------|---------------| |`username` | | | |`password` | | | ## Example Playbook
- name: ansibledoc_demo hosts: all vars: username: debugtalk password: p@ssword roles: - role: ansible_role_test
## License
Licensed under the [MIT License](https://opensource.org/licenses/MIT).
接下来我们可以使用命令 ansible-doc ansible_role_test 来生成文档,并且查看生成的日志信息:
$ ansible-doc ansible_role_test
这个命令会将文档生成到 /etc/ansible/roles/ansible_role_test/README.md 文件中。打开 README.md 文件,我们可以查看生成的文档信息:
# Module: ansible_role_test Insert your description here. ## Role variables ### Required variables | Variable Name | Default | Description | |---------------|---------|-------------| | username | | | | password | | | ## Example Insert your example here. ## License Licensed under the [MIT License](https://opensource.org/licenses/MIT).
四、自定义Ansibledoc标签
Ansibledoc 支持无限制的自定义标签。如果您将自定义标签应用于多个模块或插件中,您可以通过使用 ansible-doc –metadata 来预定义标签。
示例:我们创建一个自定义标签,用于描述 Ansible Role 模块的兼容性:
# Ansible Role: ansible_role_test Insert your introduction here. ## Role variables ### Required variables | Variable Name | Variable Description | Default Value | |---------------|----------------------|---------------| |`username` | | | |`password` | | | ## Compatibility | When used with | Versions | |----------------|----------| | Ubuntu | 18.04 | | CentOS | 7 | ## Example Playbook
- name: ansibledoc_demo hosts: all vars: username: debugtalk password: p@ssword roles: - role: ansible_role_test
## License
Licensed under the [MIT License](https://opensource.org/licenses/MIT).
接下来,我们可以使用 –metadata 标记来添加自定义标签,在运行 ansible-role-doc 命令时将会自动应用。
$ ansible-doc ansible_role_test --metadata 'tags=dict ansible_version=2.2'
以上命令将会应用新的自定义标签,并且关闭标准 Ansibledoc 标签。
结论
Ansibledoc 作为 Ansible 的一个功能,可以帮助我们更好地维护文档及规范代码。通过对 Ansibledoc 的详细了解,在使用 Ansibledoc 进行文档开发时,我们可以很方便的开始,先自行阅读定义好的标签并且应用到文档中。在实际使用中,您还可以使用 Ansibledoc 来生成其他类型的模块或插件的文档,例如 Ansible Playbook 以及 Ansible Plugin。祝大家愉快的编写 Ansible 脚本!
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/280800.html