如何将环境变量传递到.sql文件?

时间:2019-06-26 11:56:42

标签: postgresql docker environment-variables

我正在Dockerfile中设置环境变量,我想在.sql文件中引用该变量。该文件位于/docker-entrypoint-initdb.d中,因为initdb将运行它。

如何传递环境变量? (例如SELECT * FROM $myEnvironmentVariableHere;

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点,但最简单的方法可能是使用带有HEREDOC的简单shell脚本:

这是脚本,在scripts / test.sh中调用

#!/bin/bash

psql << EOF
SELECT * FROM $MYVAR LIMIT 1;
EOF

运行方法如下:

docker run --rm  --name test_pg -v $PWD/scripts:/docker-entrypoint-initdb.d -e "MYVAR=pg_class" postgres:latest

在各种启动消息中,您将看到以下几行:

/usr/local/bin/docker-entrypoint.sh: sourcing /docker-entrypoint-initdb.d/test.sh
   relname    | relnamespace | reltype | reloftype | relowner | relam | relfilenode | reltablespace | relpages | reltuples | relallvisible | reltoastrelid | relhasindex | relisshared | relpersistence | relkind | relnatts | relchecks | relhasoids | relhasrules | relhastriggers | relhassubclass | relrowsecurity | relforcerowsecurity | relispopulated | relreplident | relispartition | relrewrite | relfrozenxid | relminmxid |           relacl            | reloptions | relpartbound
--------------+--------------+---------+-----------+----------+-------+-------------+---------------+----------+-----------+---------------+---------------+-------------+-------------+----------------+---------+----------+-----------+------------+-------------+----------------+----------------+----------------+---------------------+----------------+--------------+----------------+------------+--------------+------------+-----------------------------+------------+--------------
 pg_statistic |           11 |   11319 |         0 |       10 |     0 |        2619 |             0 |       16 |       398 |            16 |          2840 | t           | f           | p              | r       |       26 |         0 | f          | f           | f              | f              | f              | f                   | t              | n            | f              |          0 |          562 |          1 | {postgres=arwdDxt/postgres} |            |
(1 row)