skip to Main Content

See below code:

I want to pass a variable from Dockerfile or wherever to my init.sql file.
How can I do this?

Dockerfile

FROM postgres
ADD init.sql /docker-entrypoint-initdb.d/

init.sql

CREATE TABLE ${SOME_ARGUMENT_HERE}(
id SERIAL PRIMARY KEY,
name VARCHAR(500) NOT NULL,
completed BOOLEAN NOT NULL);

2

Answers


  1. Chosen as BEST ANSWER

    Ok so far I've created this

    docker-compose.yml

    build:
      context: .
      args:
       - PG_TABLE=${PG_TABLE}      # Comes from .env variable
    

    seed.sql

    CREATE TABLE ${PG_TABLE}(
    id SERIAL PRIMARY KEY,
    name VARCHAR(500) NOT NULL,
    completed BOOLEAN NOT NULL);
    

    script.sh

    #!/usr/bin/env bash
    sed  -i "s/${$1}/$2/g" dump.sql
    

    Dockerfile

    FROM postgres
    ARG PG_TABLE
    
    ADD seed.sql /docker-entrypoint-initdb.d/seed.sql
    
    # pass variable PG_TABLE to script.sh to replace ${PG_TABLE} with .env variable in seed.sql
    WORKDIR /scripts
    COPY script.sh .
    RUN chmod +x script.sh
    RUN /scripts/script.sh PG_TABLE "${PG_TABLE}"
    

    Finally fixed. I realised the problem was because my script.sh was not targeting the destination of /docker-entrypoint-initdb.d/seed.sql


  2. You can use for example script or execute shell command using sed/awk to replace your variable ${SOME_ARGUMENT_HERE} with some other variable that has been passed to the Dockerfile

    Example of command

    sed  -i 's/${SOME_ARGUMENT_HERE}/TEST-REPLACE/g' init.sql
    

    Example of shell script (replace.sh)

    #!/usr/bin/env bash
    sed  -i 's/${SOME_ARGUMENT_HERE}/TEST-REPLACE/g' init.sql
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search