Defining Operator logic in an Ansible Role

The memcached-operator watches the Memcached resource with APIVersion cache.example.com/v1apha1 and Kind Memcached. Now you'll define the Operator logic in Ansible terms.

For this example the memcached-operator will execute the following reconciliation logic for each 'Memcached' Custom Resource (CR):

  • Create a memcached Deployment if it doesn't exist
  • Ensure that the Deployment size matches that specified in the 'Memcached' CR

Installing an existing Role from Ansible Galaxy

To speed development of our Operator, we can reuse an existing Role. We will install a Role from Ansible Galaxy into our Operator: dymurray.memcached_operator_role.

Run the following to install the Ansible Role in the project:

ansible-galaxy install dymurray.memcached_operator_role -p ./roles
ls roles
dymurray.memcached_operator_role memcached

Since you'll be using the logic from dymurray.memcached_operator_role, we can safely delete the placeholder Role generated by operator-sdk. Run rm -rf ./roles/memcached to remove the memcached role.

Role Variables

This Role provides the user with a variable size which is an integer to specify the desired number of Deployment replicas. You can find the default for this variable in the memcached Role _defaults/main.yml_ file:

---
# defaults file for Memcached
size: 1

Role Tasks

Examine the memcached Role _tasks/main.yml_ file, which uses the _k8s_ (Kubernetes) Ansible module to create a Deployment of memcached.

---
# tasks file for Memcached
- name: start memcached
  k8s:
    definition:
      kind: Deployment
      apiVersion: apps/v1
      metadata:
        name: '{{ ansible_operator_meta.name }}-memcached'
        namespace: '{{ ansible_operator_meta.namespace }}'
      spec:
        replicas: "{{size}}"
        selector:
          matchLabels:
            app: memcached
  
  [ ... ]

Next, modify the necessary files to ensure that our Operator uses this Role instead of the generated scaffolding Role. First, modify watches.yaml. By default, the memcached-operator watches Memcached resource events as shown in watches.yaml and executes the Ansible Role Memcached. Since we have swapped out the original Role for one from Ansible Galaxy, change the Watches file's role specification to reflect this:

---
- version: v1alpha1
  group: cache.example.com
  kind: Memcached
  role: /opt/ansible/roles/dymurray.memcached_operator_role

In the next step, you'll build and run your Ansible Operator.