Ansible variable in key/value key

谁说胖子不能爱 提交于 2021-02-20 13:44:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!