如何在Ansible中使用环境变量?

时间:2019-03-07 09:39:26

标签: docker docker-compose ansible

我有一个要转换为Ansible的docker-compose项目。

一切正常,但是我想将下面的命令从docker compose转换为Ansible。 我尝试通过(env,envfile命令),但仍无法正常工作。这是docker compose中的命令

  Environment:
 - NGINX_HOST=http://nginx:80

在Ansible剧本中是否可以选择和使用环境变量? Ansible中此命令的语法是什么?

我的剧本

- hosts: all
  connection: local
  tasks:

  - name: 3
    command: docker build --network host -t man /home/my/Documents/2/mysite/

  - name: php
    docker_container:
      name: 1-php
      image: php:fpm
      state: started
      volumes:
       - ./file:/var/www/html/x.com

  - name: nginx-vts-exporter
    docker_container:
      name: x-Exporter
      image: sophos/nginx-vts-exporter:latest
      state: started
      ports:
       - 9913:9913


  - name: prom
    docker_container:
      name: x-prometheus
      image: prom/prometheus:latest
      state: started
      ports:
       - 9090:9090
      volumes:
       - ./monitor/prometheus.yml:/etc/prometheus/prometheus.yml
      links:
       - x-Exporter

  - name: nginx
    docker_container:
      name: x-Nginx
      image: nginx:latest
      volumes:
        - ./site.conf:/etc/nginx/conf.d/x.conf:ro
        - ./file:/var/www/html/x.com
      ports:
        - 80:80
      links:
        - 1-php
        - x-Exporter

1 个答案:

答案 0 :(得分:0)

如果您使用vars中的变量。您可以使用类似“ {{repo}}”的语法,环境变量的键也是env,而不是Environment。

- hosts: fix
  remote_user: root
  vars:
    repo: test
  tasks:
    - name: prom
      docker_container
        env:
          REPO: "{{repo}}"
          HOSTIP: "{{ ansible_eth0.ipv4.address }}"
          NGINX_HOST: http://nginx:80