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

GitLab CI script needs entry in /etc/hosts

我有一个 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 --> sudo: a password is required)

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

以下说法是错误的:

"But that just fails because the gitlab-runner user doesn't have permissions to write to that file."

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

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

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

更新

如果 gitlab-runner 显示为 whoami 的结果,则 docker-executor 未被使用,而是 shell-executor 已接手工作。