Skip to content
Ansible

Ansible

This article collects some approaches that I have used when setting up new Ansible automation projects - it’s light on explanation because it’s more of an aide-mémoire for myself than anything else.

Inventory

inventory/
└── location1/
    ├── group_vars/
    │   └── all
    └── hosts
└── location2/
    ├── group_vars/
    │   └── all
    └── hosts

Collection

Using an Ansible Collection from a single collection repository, I can keep all my roles in one place1.

ansible-collection/
└── rhu
    ├── host
    │   └── roles
    │       ├── 01-common
    │       ├── ansible-pull
    │       ├── backup
    │       ├── dotfiles
    │       ├── logging
    │       └── security
    ├── service
    │   └── roles
    │       ├── auth			(authentik)
    │       ├── auth-dns		(nsd)
    │       ├── backup
    │       ├── dashboard
    │       ├── dhcp-ipam
    │       ├── dns-resolver	(unbound)
    │       ├── docker
    │       ├── forge			(forgejo)
    │       ├── http
    │       ├── k8s
    │       ├── matrix
    │       ├── ntfy
    │       ├── pihole
    │       ├── reverse-proxy 	(caddy)
    │       ├── s3				(garage)
    │       ├── tunnel
    │       └── ...
--------------------------- Future --------
    ├── team1
    │   └── roles
    │       ├── appA
    │       └── appB
    └── team2
        └── roles
            ├── appC
            └── appD

Roles

  1. Use Ansible Galaxy2 to create a conventional set of files.

    ansible-galaxy role init [--role-skeleton=/path/to/skeleton] role_name

Testing within a Role/Playbook

There are several useful patterns that can help with testing3.

  • wait_for:
    tasks:
    
      - ansible.builtin.wait_for:
          host: "{{ inventory_hostname }}"
          port: 22
        delegate_to: localhost
  • uri:
    tasks:
    
      - action: uri url=https://www.example.com return_content=yes
        register: webpage
    
      - fail:
          msg: 'service is not happy'
        when: "'AWESOME' not in webpage.content"
  • assert:
    tasks:
    
      - ansible.builtin.shell: /usr/bin/some-command --parameter value
        register: cmd_result
    
      - ansible.builtin.assert:
          that:
            - "'not ready' not in cmd_result.stderr"
            - "'gizmo enabled' in cmd_result.stdout"

Testing Roles

TODO: Return to testing with molecule

See Also


  1. (TODO: publish Collection to /ansible-collection) ↩︎

  2. the CLI that makes it easier to work with Roles, not the Ansible Galaxy website which is a service for sharing Ansible automation content. ↩︎

  3. Lifted from https://docs.ansible.com/projects/ansible/latest/reference_appendices/test_strategies.html#modules-that-are-useful-for-testing ↩︎

Last updated on