键/值键中的Ansible变量

时间:2017-11-08 05:58:53

标签: ansible ansible-template

我将env变量传递给ansible playbook中的Docker容器,如何在env的键/值中的键中设置Ansible变量?

所以这个:

- name: webproxy container
  docker_container:
    name: "webproxy"
    image: "webproxy"
    env:
      SERVICE_443_NAME: "webproxy"

成为这个:

- name: webproxy container
  docker_container:
    name: "webproxy"
    image: "webproxy"
    env:
      SERVICE_{{ port_number }}_NAME: "webproxy"

2 个答案:

答案 0 :(得分:6)

使用JSON表示法定义包含环境变量的字典:

- name: webproxy container
  docker_container:
    name: "webproxy"
    image: "webproxy"
    env: '{ "SERVICE_{{ port_number }}_NAME": "webproxy" }' 

答案 1 :(得分:-1)

这个答案是另类,我希望这对你有所帮助。

<强> 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 ,它与main.yml位于同一目录

---
env:
  SERVICE_{{ port_number }}_NAME: "webproxy"