如何使用azure管道变量为我的docker映像设置环境变量



我有一个azure管道,我想用它来部署我的rails应用程序。该应用程序有一个Dockerfile和一个docker compose文件。

我正在尝试将RAILS_MASTER_KEY设置为管道中的一个秘密变量,然后在我的docker compose文件中将其引用为环境变量。

我可以确认代理正在使用管道yaml中的echo正确设置变量。然而,环境变量并没有被正确地传递/设置到我的docker compose,最终也没有被传递到Dockerfile。

我已经解决了这几天阅读azure文档,堆栈溢出和它不工作。

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Batch#秘密变量

这是我的代码:

azure-pipelines.yaml:

steps:
- script: echo "test $(RAILS_MASTER_KEY)"
- script: echo "test $(testvar)"
- task: DockerCompose@0
inputs:
containerregistrytype: 'Azure Container Registry'
azureSubscription: 'de-identified'
azureContainerRegistry: '{"loginServer":""de-identified"", "id" : "de-identified"}'
dockerComposeFile: '**/docker-compose.yml'
dockerComposeFileArgs: |
RAILS_MASTER_KEY=$(RAILS_MASTER_KEY)
testvar=$(testvar)
action: 'Build services'
env:
RAILS_MASTER_KEY: $(RAILS_MASTER_KEY)

docker-compose.yml:

version: "3.3"
services:
web:
build: .
command: command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0' && echo ${RAILS_MASTER_KEY}"
volumes:
- .:/app
ports:
- "3000:3000"
environment:
RAILS_MASTER_KEY: ${RAILS_MASTER_KEY}
testvar: ${testvar}

Dockerfile:

FROM ruby:3.1.0-slim
RUN apt-get update && apt-get install -y --no-install-recommends 
build-essential 
libpq-dev 
postgresql-client 
git 
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
ENV BUNDLER_VERSION 2.3.5
ENV RAILS_ENV production
ENV RAILS_MASTER_KEY ${RAILS_MASTER_KEY}
ENV testvar ${testvar}
ENV RAILS_SERVE_STATIC_FILES true
ENV RAILS_LOG_TO_STDOUT true
RUN echo "----------------key is 1. ${RAILS_MASTER_KEY}"
RUN echo "----------------key is 11. $( testvar )"
RUN echo "----------------key is 12. $testvar"
RUN echo "----------------key is 2. $[variables.RAILS_MASTER_KEY]"
RUN echo "----------------key is 4. $(RAILS_MASTER_KEY)"
RUN gem install bundler -v $BUNDLER_VERSION
RUN bundle config set --local without 'development test'
RUN bundle install
COPY . .
RUN rm -f /app/tmp/pids/server.pid
EXPOSE 3000
CMD ["bundle", "exec", "rails", "s", "-e", "production", "-b", "0.0.0.0"]

正如你所看到的,我在尝试调试时有echo尝试,所以请忽略所有的echo语句。如有任何帮助/指导,我们将不胜感激。非常感谢。

从上面的片段来看,您似乎在使用dockerComposeFileArgs来指定环境变量。对于类似的情况(以及用于本地调试的目的(,一个很有用的选项是在Dockerfile中使用ARG。例如

FROM ruby:3.1.0-slim
RUN ...
ARG RAILS_MASTER_KEY
ENV RAILS_MASTER_KEY=$RAILS_MASTER_KEY
...

因此,您可以在构建时使用Azure DevOps 中的secret变量指定RAILS_MASTER_KEY

在这里你可以找到一些关于ENVARGS的有用帖子关键词:

  • https://vsupalov.com/docker-build-time-env-values/
  • https://blog.bitsrc.io/how-to-pass-environment-info-during-docker-builds-1f7c5566dd0e

最新更新