7

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"
techraf
  • 64,883
  • 27
  • 193
  • 198
Alex Laverty
  • 485
  • 1
  • 7
  • 16

2 Answers2

15

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" }' 
techraf
  • 64,883
  • 27
  • 193
  • 198
-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"
Daein Park
  • 4,393
  • 2
  • 12
  • 21