Escaping colons in Docker Compose value

Hi,

I’m trying to pass some parameters to my healthcheck test :

version: '3.8'

services:
    mongodb:
        image: mongo
        container_name: mongodb
        environment:
            - MONGO_INITDB_ROOT_USERNAME=${MONGODB_USER}
            - MONGO_INITDB_ROOT_PASSWORD=${MONGODB_PASS}
        volumes:
            - ./db:/data/db
        networks:
            - proxy
        restart: unless-stopped
        healthcheck:
            test: test $$(echo "rs.initiate({_id: 'rs0', members: [{_id: 1, 'host': 'mongodb:27017'}]}).ok || rs.status().ok" | mongosh -u $${MONGO_INITDB_ROOT_USERNAME} -p $${MONGO_INITDB_ROOT_PASSWORD} --quiet) -eq 1
            interval: 10s
            start_period: 30s

I’m getting this error :

yaml: mapping values are not allowed in this context

If I remove the colons ( : ) it works. How can I escape these colons in my test value ?

The first link in the google search result list for “escape colon in yaml” shows plenty of variations: escaping - How to escape indicator characters (colon and hyphen) in YAML - Stack Overflow.

Personalty, I would just wrap it in single quotes, as plain style (as in unquoted) does not allow escaping.

@meyay gave you the actual answer to your question. I just want to add a relevant link in case someone finds the topic searching for “colon” and “docker compose value”. In some values colons have meaning. Like in volume mounts and you can’t really “escape” it, only change the source path.

1 Like

My bad, I kept including “docker compose” in my keywords when searching, I’m forgetting YAML is not exclusive to Docker… I was able to solve the issue. The working code is this :

healthcheck:
            test: test $$(echo 'rs.initiate({_id':' "rs0", members':' [{_id':' 1, "host"':' "mongodb':'27017"}]}) || rs.status().ok' | mongosh -u $${MONGO_INITDB_ROOT_USERNAME} -p $${MONGO_INITDB_ROOT_PASSWORD} --quiet) -eq 1

Thanks a lot !