1. 什么是 Ansible 集合?

Ansible 集合是 Ansible 内容的分发格式,用于打包和分发 Playbook、角色、模块和插件。集合解决了特定问题,并包含所有相关的任务、变量、默认值、处理器、模块和插件。对于用户来说,集合可以通过 Ansible Galaxy 轻松下载和共享;对于开发者来说,集合可以通过 Ansible Galaxy 轻松上传和共享。

2. 什么是 Ansible Galaxy?

Ansible Galaxy 是一个免费的网站,用于查找、下载、评价和审查社区开发的 Ansible 角色和集合。它提供了一个优秀的框架,帮助用户快速开始自动化项目。

3. 下载和使用 community.general 集合

community.general 是一个包含通用模块和插件的 Ansible 集合。以下是下载和使用该集合的步骤:


步骤 1:准备 requirements.yml 文件

创建一个 requirements.yml 文件,指定要下载的集合:

---
collections:
  - name: community.general
    source: https://galaxy.ansible.com

步骤 2:下载集合

使用 ansible-galaxy 命令下载集合:

ansible-galaxy install -r requirements.yml

执行后,集合将被下载到默认路径(通常是 ~/.ansible/collections/)。

步骤 3:创建 Playbook

创建一个 Playbook 文件(例如 collection.yml),并引用集合中的模块:

---
- name: modprobe module demo
  hosts: localhost
  become: true
  vars:
    module_name: "dummy"
    ansible_connection: local
  tasks:
    - name: load the module
      community.general.modprobe:
        name: "{{ module_name }}"
        state: present

步骤 4:运行 Playbook

运行 Playbook 以使用集合中的模块:

ansible-playbook collection.yml

示例操作

1. 未安装集合时的错误

在未下载集合之前,直接运行 Playbook 会导致错误:

$ ansible-playbook collection/collection.yml 
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
ERROR! couldn't resolve module/action 'community.general.modprobe'. This often indicates a misspelling, missing collection, or incorrect module path.

2. 下载集合

运行以下命令下载集合:

$ ansible-galaxy install -r collection/requirements.yml 
Starting galaxy collection install process
Process install dependency map
Starting collection install process
Downloading https://galaxy.ansible.com/download/community-general-4.5.0.tar.gz to /home/devops/.ansible/tmp/ansible-local-24543cs6dck7/tmpaccd0umv/community-general-4.5.0-5msjuuoa
Installing 'community.general:4.5.0' to '/home/devops/.ansible/collections/ansible_collections/community/general'
community.general:4.5.0 was installed successfully

3. 列出已安装的集合

运行以下命令列出已安装的集合:

$ ansible-galaxy collection list

# /home/devops/.ansible/collections/ansible_collections
Collection        Version
----------------- -------
community.general 4.5.0  

4. 运行 Playbook

下载集合后,运行 Playbook:

$ ansible-playbook collection/collection.yml 
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [modprobe module demo] ***************************************************

TASK [Gathering Facts] ******************************************************
ok: [localhost]

TASK [load the module] ******************************************************
changed: [localhost]

PLAY RECAP ******************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

总结

通过上述步骤,您可以轻松下载并使用 Ansible Galaxy 上的 community.general 集合。您可以根据需要调整 Playbook 中的任务和其他参数,以满足您的具体需求。