问题
I'm passing env variables to a Docker container in an ansible playbook, how do I set an Ansible variable in the key in the key/value of an env?
So this:
- name: webproxy container
docker_container:
name: "webproxy"
image: "webproxy"
env:
SERVICE_443_NAME: "webproxy"
becomes this:
- name: webproxy container
docker_container:
name: "webproxy"
image: "webproxy"
env:
SERVICE_{{ port_number }}_NAME: "webproxy"
回答1:
Use JSON notation to define a dictionary with environment variables:
- name: webproxy container
docker_container:
name: "webproxy"
image: "webproxy"
env: '{ "SERVICE_{{ port_number }}_NAME": "webproxy" }'
回答2:
This answer is alternative, I hope this help you.
main.yml
---
- name: test
hosts: localhost
vars:
port_number: 443
pre_tasks:
- name: make the playbook from template
template:
src: /path/to/webproxy.j2
dest: /path/to/webproxy_vars.yml
tasks:
- include_vars: /path/to/webproxy_vars.yml
- name: webproxy container dummy
shell: echo $SERVICE_{{ port_number }}_NAME
environment: "{{ env }}"
webproxy.j2 , it placed at same directory with main.yml
---
env:
SERVICE_{{ port_number }}_NAME: "webproxy"
来源:https://stackoverflow.com/questions/47172551/ansible-variable-in-key-value-key