Ansible_collections
Ansible Collections
Section titled “Ansible Collections”Overview
Section titled “Overview”Ansible Collections are a distribution format for Ansible content that can include playbooks, roles, modules, and plugins. They provide a way to package and distribute reusable Ansible content.
Why Collections?
Section titled “Why Collections?”- Modularity: Package related content together
- Distribution: Easy sharing via Ansible Galaxy
- Versioning: Semantic versioning for content
- Dependencies: Handle role/module dependencies
- Namespacing: Avoid name conflicts
Collection Structure
Section titled “Collection Structure”my_collection/├── docs/├── galaxy.yml├── LICENSE├── meta/│ └── runtime.yml├── playbooks/│ ├── files/│ ├── templates/│ └── tasks/├── plugins/│ ├── modules/│ ├── inventory/│ ├── callbacks/│ └── filters/├── roles/│ ├── role1/│ └── role2/└── tests/ ├── integration/ └── units/galaxy.yml
Section titled “galaxy.yml”namespace: myorgname: my_collectionversion: 1.0.0description: My custom collectionreadme: README.mdauthors: - Your Name <your@email.com>license: - GPL-3.0-or-laterlicense_file: LICENSEtags: - system - networking - cloudrepository: https://github.com/myorg/ansible-collectiondocumentation: https://github.com/myorg/ansible-collection/docshomepage: https://github.com/myorg/ansible-collectionissues: https://github.com/myorg/ansible-collection/issuesdependencies: community.general: ">=3.0.0" ansible.posix: ">=1.0.0"Installing Collections
Section titled “Installing Collections”From Ansible Galaxy
Section titled “From Ansible Galaxy”# Install collectionansible-galaxy collection install namespace.collection
# Install specific versionansible-galaxy collection install namespace.collection:1.2.3
# Install to specific pathansible-galaxy collection install namespace.collection -p ./collections
# Install from tarballansible-galaxy collection install namespace-collection-1.0.0.tar.gzFrom Git
Section titled “From Git”# Install from Gitansible-galaxy collection install git+https://github.com/org/repo.git,main
# Install from localansible-galaxy collection install ./path/to/collectionrequirements.yml
Section titled “requirements.yml”collections: # From Galaxy - name: community.general version: ">=3.0.0"
# From Git - name: https://github.com/ansible-collections/amazon.aws type: git
# From local path - name: myorg.my_collection source: ./local/collectionUsing Collections
Section titled “Using Collections”In Playbooks
Section titled “In Playbooks”---- name: Using collections hosts: all collections: - myorg.my_collection - community.general
tasks: # Use module from collection - name: Run module from collection myorg.my_module: option1: value1 option2: value2
# Use role from collection - name: Include role from collection import_role: name: myorg.my_roleFully Qualified Names
Section titled “Fully Qualified Names”# Using FQCN (Fully Qualified Collection Names)- name: Use AWS module amazon.aws.ec2_instance: name: my-instance instance_type: t3.micro image_id: ami-12345678
- name: Use community module community.general.homematic: host: 192.168.1.1In Roles
Section titled “In Roles”# meta/main.yml in roledependencies: - role: myorg.my_collection.my_role vars: role_var: value - collection: community.generalCreating Collections
Section titled “Creating Collections”Create Collection Skeleton
Section titled “Create Collection Skeleton”# Create collection structureansible-galaxy collection init myorg.my_collection
# Create role inside collectionansible-galaxy role init myorg.my_collection.role_nameCustom Modules
Section titled “Custom Modules”#!/usr/bin/python# DOCUMENTATION"""module: my_module
short_description: This is my module
description: - This is my custom module
options: name: description: - The name type: str required: trueauthor: - Your Name"""
from ansible.module_utils.basic import AnsibleModule
def run_module(): module_args = dict( name=dict(type='str', required=True) )
module = AnsibleModule( argument_spec=module_args, supports_check_mode=True )
result = dict( changed=False, message='' )
result['message'] = f"Hello {module.params['name']}!" result['changed'] = True
module.exit_json(**result)
def main(): run_module()
if __name__ == '__main__': main()Custom Inventory Plugin
Section titled “Custom Inventory Plugin”from ansible.plugins.inventory import BaseInventoryPlugin
DOCUMENTATION = ''' inventory: my_inventory short_description: My custom inventory description: - My custom inventory plugin options: plugin: description: Token required: True choices: ['my_inventory']'''
class InventoryModule(BaseInventoryPlugin): NAME = 'my_inventory'
def verify_file(self, path): return path.endswith(('my_inv.yaml', 'my_inv.yml'))
def parse(self, inventory, loader, path): super().parse(inventory, loader, path)
self._read_config_data(path)
# Parse and add hosts data = self._get_cache_data(path) for host in data.get('hosts', []): self.inventory.add_host(host)Collection Dependencies
Section titled “Collection Dependencies”runtime.yml
Section titled “runtime.yml”requires_ansible: ">=2.9"dependencies: community.general: ">=3.0.0"
plugin_routing: modules: old_module_name: redirect: namespace.collection.new_module_name inventory: old_inventory: redirect: namespace.collection.new_inventoryPublishing Collections
Section titled “Publishing Collections”Build Collection
Section titled “Build Collection”# Build collectionansible-galaxy collection build
# Creates: myorg-my_collection-1.0.0.tar.gzPublish to Galaxy
Section titled “Publish to Galaxy”# Login to Galaxyansible-galaxy login
# Publish collectionansible-galaxy collection publish myorg-my_collection-1.0.0.tar.gz
# Or with tokenansible-galaxy collection publish myorg-my_collection-1.0.0.tar.gz --token=<token>GitHub Actions for Publishing
Section titled “GitHub Actions for Publishing”name: Publish Collection
on: release: types: [published]
jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
- name: Build collection run: | ansible-galaxy collection build
- name: Publish collection uses: ansible/galaxy-collection-publish@v1.0.0 with: api_key: ${{ secrets.GALAXY_API_KEY }}Using Community Collections
Section titled “Using Community Collections”AWS Collection
Section titled “AWS Collection”# Install AWS collectionansible-galaxy collection install amazon.aws
# Use AWS modules- name: Launch EC2 instance amazon.aws.ec2_instance: name: web-server instance_type: t3.micro image_id: ami-0c55b159cbfafe1f0 security_group: web-sg key_name: my-keyKubernetes Collection
Section titled “Kubernetes Collection”# Installansible-galaxy collection install community.kubernetes
# Use k8s modules- name: Create namespace community.kubernetes.k8s: name: myapp kind: namespace state: presentBest Practices
Section titled “Best Practices”1. Use FQCN
Section titled “1. Use FQCN”# Always use fully qualified names- name: Ensure container is running containers.podman.podman_container: name: web image: nginx2. Pin Versions
Section titled “2. Pin Versions”# requirements.yml - pin versionscollections: - name: amazon.aws version: ">=5.0.0" - name: community.general version: ">=6.0.0"3. Use Execution Environments
Section titled “3. Use Execution Environments”version: 3name: my-eecollections: - name: amazon.aws - name: community.general4. Document Collections
Section titled “4. Document Collections”# My Collection
## Requirements
- ansible >= 2.9
## Installation
ansible-galaxy collection install myorg.my_collection
## Usage
### Modules
#### my_module
Do something.
## License
GPL-3.0-or-laterSummary
Section titled “Summary”Ansible Collections enable:
- Distribution: Package and share Ansible content
- Modularity: Organize related content
- Dependencies: Manage content dependencies
- Versioning: Semantic versioning
- Reusability: Share across teams
Key concepts:
- FQCN: Fully Qualified Collection Names
- Galaxy: Ansible content repository
- Dependencies: Collection requirements
- runtime.yml: Collection metadata