Ansible variable in key/value key
Asked Answered
C

2

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"
Cognoscenti answered 8/11, 2017 at 5:58 Comment(0)
M
16

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" }' 
Milli answered 8/11, 2017 at 13:9 Comment(0)
M
-1

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"
Maggiore answered 8/11, 2017 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.