第十三章:Ansible Galaxy

学习使用 Ansible Galaxy 共享和复用社区角色。

最后更新: 2024-01-27
页面目录

Ansible Galaxy

Ansible Galaxy 是 Ansible 的社区角色市场,提供大量预构建的角色供复用。

Galaxy 概述

┌─────────────────────────────────────────────────────────────────┐
│                    Ansible Galaxy                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ┌────────────────────────────────────────────────────────┐   │
│   │              ansible-galaxy.com                          │   │
│   │                                                         │   │
│   │   🔍 Search Roles                                       │   │
│   │   ⭐ Popular Roles                                      │   │
│   │   📦 Collections                                       │   │
│   │   👥 Community                                          │   │
│   │                                                         │   │
│   └────────────────────────────────────────────────────────┘   │
│                                                                  │
│   galaxy.ansible.com                                             │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

基本命令

安装角色

# 安装角色
ansible-galaxy install username.rolename

# 安装到指定目录
ansible-galaxy install username.rolename -p roles/

# 安装特定版本
ansible-galaxy install username.rolename,1.2.3

# 从 requirements 文件安装
ansible-galaxy install -r requirements.yml

requirements.yml

# requirements.yml
---
# 从 Galaxy 安装
- src: geerlingguy.redis
  version: "3.2.0"
  name: redis

- src: geerlingguy.nginx
  version: "~3.1.0"
  name: nginx

# 从 Git 安装
- src: git+https://github.com/username/ansible-role.git
  version: main
  name: custom_role

# 从 GitHub 安装
- src: https://github.com/username/ansible-role.git
  scm: git
  version: 1.0.0

# 本地角色
- src: file:///path/to/local/role
  name: local_role

管理已安装角色

# 列出已安装的角色
ansible-galaxy list

# 移除角色
ansible-galaxy remove username.rolename

# 搜索角色
ansible-galaxy search nginx

# 查看角色信息
ansible-galaxy info username.rolename

常用 Galaxy 角色

Nginx

# requirements.yml
- src: geerlingguy.nginx
  version: "3.1.0"
# playbook 使用
---
- name: Install Nginx
  hosts: webservers
  become: yes

  roles:
    - role: geerlingguy.nginx
      vars:
        nginx_vhosts:
          - server_name: "example.com"
            listen: "80"
            root: "/var/www/html"
        nginx_remove_default_vhost: true

MySQL

# requirements.yml
- src: geerlingguy.mysql
  version: "3.0.0"
# playbook 使用
---
- name: Install MySQL
  hosts: dbservers
  become: yes

  roles:
    - role: geerlingguy.mysql
      vars:
        mysql_root_password: "{{ vault_mysql_root_password }}"
        mysql_databases:
          - name: myapp
            encoding: utf8mb4
            collation: utf8mb4_unicode_ci
        mysql_users:
          - name: myapp
            host: "localhost"
            password: "{{ vault_myapp_password }}"
            priv: "myapp.*:ALL"

Redis

# requirements.yml
- src: geerlingguy.redis
  version: "3.2.0"
# playbook 使用
---
- name: Install Redis
  hosts: dbservers
  become: yes

  roles:
    - role: geerlingguy.redis
      vars:
        redis_bind_address: "0.0.0.0"
        redis_maxmemory: "256mb"
        redis_maxmemory_policy: "allkeys-lru"

Docker

# requirements.yml
- src: geerlingguy.docker
  version: "4.0.0"
# playbook 使用
---
- name: Install Docker
  hosts: servers
  become: yes

  roles:
    - role: geerlingguy.docker
      vars:
        docker_users:
          - deploy
        docker_install_compose: yes
        docker Compose_version: "2.20.0"

Collections

Collections 概述

┌─────────────────────────────────────────────────────────────────┐
│                      Collections                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   Collection                                                      │
│   ├── roles/                                                     │
│   │   └── role1, role2                                          │
│   ├── plugins/                                                  │
│   │   ├── modules/                                              │
│   │   ├── inventory/                                            │
│   │   └── callbacks/                                            │
│   └── playbooks/                                                │
│       └── site.yml                                              │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

安装 Collections

# 安装 Collection
ansible-galaxy collection install namespace.collection

# 安装特定版本
ansible-galaxy collection install namespace.collection:1.0.0

# 从 requirements.yml 安装
ansible-galaxy collection install -r requirements.yml

requirements.yml 格式

# requirements.yml (Collections)
---
collections:
  - name: community.general
    version: "6.0.0"
  - name: community.crypto
    version: "2.10.0"
  - name: ansible.posix
    version: "1.5.0"
  - name: azure.azcollection
    version: "1.15.0"
  - name: amazon.aws
    version: "5.0.0"

使用 Collections

# playbook 使用 Collection
---
- name: Use Collection modules
  hosts: all
  
  tasks:
    - name: Using community.general module
      community.general.homematic:
        host: "{{ homematic_host }}"
        password: "{{ homematic_password }}"
    
    - name: Using community.crypto module
      community.crypto.x509_certificate:
        csr_path: /tmp/my.csr
        certificate: /tmp/cert.pem
        private_key: /tmp/key.pem

常用 Collections

community.general

# 安装
ansible-galaxy collection install community.general
# 使用模块
---
tasks:
  # 查找模块
  - name: Find files
    community.general.find:
      paths: /var/log
      patterns: "*.log"
      age: "7d"
    register: found_files

  # 主机名管理
  - name: Set hostname
    community.general.hostname:
      name: myserver

  # ims_dvg 管理
  - name: Manage IMS DVG
    community.general.ims_dvg:
      name: "DVG1"
      state: present

amazon.aws

# 安装
ansible-galaxy collection install amazon.aws
# 使用模块
---
tasks:
  - name: Launch EC2 instance
    amazon.aws.ec2_instance:
      name: my-instance
      instance_type: t3.micro
      image:
        id: ami-12345678
      count_tag:
        Name: my-instance
      tags:
        Environment: production
      wait: yes

azure.azcollection

# 安装
ansible-galaxy collection install azure.azcollection
# 使用模块
---
tasks:
  - name: Create Azure VM
    azure.azcollection.azure_rm_virtualmachine:
      resource_group: myResourceGroup
      name: myVM
      vm_size: Standard_DS1_v2
      admin_username: azureuser
      image:
        offer: UbuntuServer
        publisher: Canonical
        sku: '18.04-LTS'

创建和发布角色

创建角色

# 使用 scaffold 创建
ansible-galaxy init myrole --init-path roles/

# 手动创建
mkdir -p roles/myrole/{defaults,files,handlers,meta,tasks,templates,vars}

role 目录结构

roles/myrole/
├── defaults/
   └── main.yml
├── files/
├── handlers/
   └── main.yml
├── meta/
   └── main.yml
├── README.md
├── tasks/
   └── main.yml
├── templates/
├── tests/
   ├── inventory
   └── test.yml
└── vars/
    └── main.yml

meta/main.yml

---
# 角色元数据
galaxy_info:
  author: yourname
  description: Your role description
  company: Your Company
  license: MIT
  min_ansible_version: "2.9"
  platforms:
    - name: EL
      versions:
        - "8"
        - "9"
    - name: Ubuntu
      versions:
        - bionic
        - focal
  galaxy_tags:
    - web
    - nginx
    - configuration

dependencies: []

README.md

# My Role

A brief description of the role.

## Requirements

Any pre-requisites that may not be covered by Ansible itself.

## Role Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `var_name` | Description | `default_value` |

## Dependencies

List of roles that this role depends on.

## Example Playbook

```yaml
- hosts: servers
  roles:
    - role: myrole
      vars:
        var_name: value

### 发布到 Galaxy

```bash
# 登录 Galaxy
ansible-galaxy login

# 导入角色
ansible-galaxy role import github_username repo_name

# 或创建 import 文件
ansible-galaxy role setup --force --role_name=myrole --github_repo=username/repo

Collections 发布

目录结构

mycollection/
├── docs/
├── galaxy.yml
├── plugins/
│   └── README.md
├── roles/
├── playbooks/
│   └── files/
│   └── templates/
└── tests/

galaxy.yml

namespace: mynamespace
name: mycollection
version: 1.0.0
readme: README.md
authors:
  - name <email>
description: My collection description
license:
  - MIT
license_files:
  - LICENSE
tags:
  - mytag
repository: https://github.com/username/mycollection
documentation: https://docs.example.com
homepage: https://example.com
issues: https://github.com/username/mycollection/issues
dependencies:
  ansible.netcommon: ">=1.0"

发布 Collection

# 构建 Collection
ansible-galaxy collection build

# 发布到 Galaxy
ansible-galaxy collection publish path/to/namespace-mycollection-1.0.0.tar.gz

# 安装自己发布的 Collection
ansible-galaxy collection install namespace.collection

最佳实践

1. 使用 requirements 管理

# requirements.yml
---
roles:
  - name: geerlingguy.nginx
  - name: geerlingguy.mysql

collections:
  - name: community.general
  - name: amazon.aws

2. 版本控制

# 固定版本确保稳定性
- name: geerlingguy.nginx
  version: "3.1.0"

# 使用语义版本范围
- name: geerlingguy.nginx
  version: ">=3.0.0,<4.0.0"

3. 检查角色质量

# 查看角色信息
ansible-galaxy info username.rolename

# 检查角色
ansible-lint roles/username.rolename

# 使用 molecule 测试
molecule test

下一步

现在你已经掌握了 Ansible Galaxy 的使用。接下来让我们学习最佳实践。

👉 最佳实践