Ansible and Templated Commands

I was working to automate some checks for the CIS Docker CE benchmark and was having trouble passing commands that resemble the following:

docker inspect --format '{{ .Id }}: Devices={{ .HostConfig.Devices }}'

Trying to pass that to either a shell or a command statement in ansible results in a templating error.

So what’s the problem?

Basically, you’re passing a command that has its own template expectations through something that’s also parsing templates and thus you end up with a collision of sorts.

How do you fix it?

Basically, you have to break down the template you’re trying to pass into it’s component parts and pass them through ansible’s templating system.

So the above would become:

docker inspect --format '{{ '{{' }} .Id {{ '}}' }}{{ ':' }} Devices={{ '{{' }} .HostConfig.Devices {{ '}}' }}'

But the whole command from the benchmark is:

docker ps --quiet --all | xargs docker inspect --format '{{ .Id }}: Devices={{ .HostConfig.Devices }}'

So a couple of other things need to be put in place, namely a play to run the docker ps command and register the results. Then, because we need to replace the xargs command, we need to iterate through the registered results from the previous play and then pass each result to the current play which means we pass {{ item }} at the end of templated command:

docker inspect --format '{{ '{{' }} .Id {{ '}}' }}{{ ':' }} Devices={{ '{{' }} .HostConfig.Devices {{ '}}' }}' {{ item }}

Leave a Reply

Your email address will not be published. Required fields are marked *