GitLab CI脚本需要在/ etc / hosts中输入

时间:2018-01-29 16:38:14

标签: docker gitlab gitlab-ci gitlab-ci-runner

我有一个GitLab CI docker runner用于在我推送时执行我的自动化测试。我的一个测试需要/ etc / hosts中的自定义条目。我无法弄清楚如何进入该文件。

这基本上是我的.gitlab-ci.yml文件的样子:

before_script:
  - cat /etc/hosts   # for debugging
  - ...              # install app dependencies
specs:
  script:
    - rspec          # <- a test in here fails without the /etc/hosts entry 

我的所有测试都通过,但需要/etc/hosts条目的测试除外。

假设我正在尝试将主机名myhost.local解析为IPv4地址XX.XX.XX.XX ...

我尝试在转轮配置中使用extra_hosts,但它似乎没有任何效果(got idea from here):

/etc/gitlab-runner/config.toml

concurrent = 1
check_interval = 0

[[runners]]
  name = "shell"
  url = "https://mygitlabinstance.com/"
  token = "THETOKEN"
  executor = "shell"
  [runners.cache]

[[runners]]
  name = "docker-ruby-2.5"
  url = "https://mygitlabinstance.com/"
  token = "THETOKEN"
  executor = "docker"
  [runners.docker]
    tls_verify = false
    image = "ruby:2.5"
    privileged = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
    extra_hosts = ["myhost.local:XX.XX.XX.XX"]
  [runners.cache]

但测试仍然失败。 cat /etc/hosts表明它没有变化:

# Your system has configured 'manage_etc_hosts' as True.
# As a result, if you wish for changes to this file to persist
# then you will need to either
# a.) make changes to the master file in /etc/cloud/templates/hosts.tmpl
# b.) change or remove the value of 'manage_etc_hosts' in
#     /etc/cloud/cloud.cfg or cloud-config from user-data
#
127.0.1.1 ip-172-31-2-54.ec2.internal ip-172-31-2-54
127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

我想我可以在before_script行中自己添加条目,但我似乎无法在容器中执行任何具有root权限的内容:

before_script:
  - echo 'XX.XX.XX.XX myhost.local' >> /etc/hosts
  ...

但这只是失败,因为gitlab-runner用户没有权限写入该文件。我尝试使用sudo,但gitlab-runner也不能这样做(echo 'XX.XX.XX.XX myhost.local' | sudo tee --non-interactive --append /etc/hosts - &gt; sudo: a password is required

总而言之,如何让我的容器拥有我需要的主机条目(或者如何以root身份执行before_script命令)?

1 个答案:

答案 0 :(得分:1)

以下陈述不正确:

  

“但这只是失败,因为gitlab-runner用户没有权限写入该文件。”

gitlab-runner不是执行before_script的用户,而是运行执行作业的容器的用户。

您正在使用ruby:2.5 Docker图片,并且在其父级USER中不包含任何Dockerfile引用。

尝试在whoami命令之前添加echo 'XX.XX.XX.XX myhost.local' >> /etc/hosts命令,以验证您是root

更新

如果gitlab-runner的结果显示为whoami docker-executor,则shell-executor未被使用,而{{1}}已取回作业。