This is my docker-compose.yml
which I hard-code the information of database,
I want to input in it from a file env.ini
of mine before pushing it to GitLab for safety but dont know how to do it.
version: "3.8"
services:
db:
image: postgres
environment:
- POSTGRES_DB=####### Hide these information and take it from
- POSTGRES_USER=##### another file when running it
- POSTGRES_HOST=172#####
- POSTGRES_PASSWORD=#########
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
Plus: my file env.ini
is quite complicated since its contains a lot of others information, it looks like this:
[sv_info]
host = #########
user = ########
password = ########
database = #
venus_base_url = #################
venus_auth_key =
cargo_base_url = #################
cargo_awb_acckey = #################
cargo_awb_cusnum = #################
cargo_awb_user = #################
cargo_awb_revkey = #################
[heremap_info]
url = #################
api_key = #################
Usually, I use from configparser import ConfigParser
in Python
to work with this env.ini
in my code.
[default]
username=@@USERNAME@@
password=@@PASSWORD@@
THE_USERNAME
and THE_PASSWORD
in your project. Now in gitlab-ci.yml
on this section before_script
do:
sed -e 's/@@USERNAME@@/'$THE_USERNAME'/' -e 's/@@PASSWORD@@/'$THE_PASSWORD'/' settings.ini.template > settings.ini.
First of all, your file with environment variable should be named .env
and it's content would be like the following:
POSTGRES_DB=cookies
POSTGRES_USER=jamie
POSTGRES_PASSWORD=oliver
POSTGRES_HOST=127.0.0.1
Those environment variables should be passed to containers. To achieve that, you should update docker compose config as follows:
version: "3.8"
services:
db:
image: postgres
environment:
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_HOST=${POSTGRES_HOST}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
And then in your django settings:
import os
# ...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': os.environ['POSTGRES_HOST'],
'PORT': 5432,
},
}
I also highly recommend to use environs package to read values of environment variables.
from environs import Env
env = Env()
IS_ENABLED = env.bool('IS_ENABLED', default=True)
That means, even when environment variable IS_ENABLED
value is True
(string) - environs
will convert it to bool
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.