I am putting labels on a container with ansible. The labels I want (in docker compose syntax) are as follows:
labels:
com.datadoghq.ad.check_names: '["portainer"]'
com.datadoghq.ad.init_configs: '[{}]'
com.datadoghq.ad.instances: '[{"host": "%%host%%","port":"9999"}]'
Note that the labels are pure strings that contain some json-like formatting.
Now to do this with ansible, my naïve syntax was this:
- docker_container:
name: portainer
# ....
labels:
com.datadoghq.ad.check_names: "[\"portainer\"]"
com.datadoghq.ad.init_configs: "[{}]"
com.datadoghq.ad.instances: "[{\"host\": \"%%host%%\", \"port\":\" {{ host_port }}\" }]"
This fails with
"msg": "Error creating container: 500 Server Error for http+docker://localhost/v1.41/containers/create?name=portainer: Internal Server Error ("json: cannot unmarshal array into Go struct field ContainerConfigWrapper.Labels of type string")"
After some trial and error I have found the reason to be that the 3rd label somehow is parsed as json, as evident from this log output from ansible-playbook -vvv:
"labels": {
"com.datadoghq.ad.check_names": "[\"portainer\"]",
"com.datadoghq.ad.init_configs": "[{}]",
"com.datadoghq.ad.instances": [
{
"host": "%%host%%",
"port": " 9000"
}
]
},
You can see check_names and init_configs are properly parsed as strings, while instances has been converted to a structure suggesting it was parsed as json.
Two tested methods that don't work in my case:
!unsafe will work but disallows template_variables which I depend on (host_port).
| to_json will work if the original string is in a template_variable, but I don't want that.
My question is, how can I avoid ansible parsing strings as json?