DEV Community

Tyler Auerbeck
Tyler Auerbeck

Posted on

Apply Labels to Molecule Platform Containers

I've recently found myself in need to apply labels to containers that are spun up as part of my Molecule tests. I was unable to quickly dig up any documentation around this use case, so I thought it might be useful to write this up so others don't find themselves in the same position.

For those who aren't familiar with Molecule, it is an Ansible testing framework that allows you to specify any number of scenarios to test your Ansible roles/collections/etc. as well as the environment that they will run against. The main configuration of a Molecule test is done in the molecule.yml file for a given scenario and tends to look something like this.

---
dependency:
  name: galaxy
driver:
  name: docker
platforms:
  - name: app
    image: dummy-app:v1.0.0
    command: "run.sh"
    pre_build_image: true
provisioner:
  name: ansible
verifier:
  name: ansible
scenario:
  name: default
  test_sequence:
    - lint
    - syntax
    - create
    - converge
    - destroy
Enter fullscreen mode Exit fullscreen mode

Defining Your Environment

As you can see from the above, the section for setting up your environment is contained under platforms. In my case, I was spinning up a number of containers and the app itself uses container labels to do some service-discovery. Without them, my tests fail because the app itself isn't able to find what it is looking for.

Adding Labels

To remedy this, I started making some educated guesses due to the lack of documentation (or lack of my ability to find the documentation). Ultimately I ended up with something like this:

platforms:
  - name: app
    image: dummy-app:v1.0.0
    command: "run.sh"
    pre_build_image: true
    labels:
      - hello: world
Enter fullscreen mode Exit fullscreen mode

After running my default scenario with molecule test, I was able to see that my container spun up with the appropriate labels! As you can see, all Molecule expects is a list of key-value pairs under the labels key. While this is a watered down example (hello: world), if you find yourself using more complex keys (special characters, etc.), I've found that you tend to be more successful by wrapping your key-values in quotes.

Hopefully this saves some others some time and as always, feel free to reach out with any questions (or if you have a better way of handling this yourself!).

Top comments (0)