Docker-compose - setting environment variables tha

2020-04-10 03:18发布

问题:

I have setup Jenkins within a Docker container and I am trying to access that my private Bitbucket repo with that server. I need to copy my SSH key into that container so that Bitbucket recognizes it and I can have my Jenkins server access the repo then.

I have in my docker-compose.yml file the following:

services:
  jenkins:
    build: .
    volumes:
      - jenkins-data:/var/jenkins_home
    environment:
      - SSH_PRIVATE_KEY=$(cat ~/.ssh/id_rsa)
    ports:
      - "8080:8080"
      - "50000:50000"

volumes:
  jenkins-data:

However, echo $SSH_PRIVATE_KEY gives /.ssh/id_rsa literally instead of the value stored inside. I have heard the problem with doing this inside the Dockerfile instead would be that it still can be viewed in one of the layers of the image that will be pushed.

My question is how can I set the value of SSH_PRIVATE_KEY to the value of the contents of my file?

I believe this could be a duplicate of How to set environment variable into docker container using docker-compose however that solution does not appear to change anything for me.

回答1:

You could create an Environment variable in your shell from which you are running your compose :

export SSH_PRIVATE_KEY=$(cat ~/.ssh/id_rsa)

and then use it in your compose like :

services:
  jenkins:
    build: .
    volumes:
      - jenkins-data:/var/jenkins_home
    environment:
      - SSH_PRIVATE_KEY
    ports:
      - "8080:8080"
      - "50000:50000"

It should pick up the value for your environment variable for container from shell environment as specified in the docs :

The value of the variable in the container is taken from the value for the same variable in the shell in which Compose is run.



回答2:

Possible solution:

    environment:
      - SSH_PRIVATE_KEY

and call the docker-compose like this:

SSH_PRIVATE_KEY=$(cat ~/.ssh/id_rsa) docker-compose build

Unfortunately, it's currently not possible to use multiline variables in .env.

Another possibility would be:

services:
  jenkins:
    build: .
    volumes:
      - jenkins-data:/var/jenkins_home
      - "/home/user/.ssh/id_rsa:/home/user/.ssh/id_rsa:ro"      
    ports:
      - "8080:8080"
      - "50000:50000"

volumes:
  jenkins-data: