从 YAML 文件中读取 JSON 数据

Read JSON data from the YAML file

我有一个 .gitlab-ci.yml 文件,用于在发布阶段安装一些插件(craftcms/aws-s3、craftcms/redactor 等)。该文件提供如下(部分):

# run the staging deploy, commands may be different baesed on the project
deploy-staging:
  stage: publish
  variables:
    DOCKER_HOST: 127.0.0.1:2375

    # ...............
    # ...............


    # TODO: temporary fix to the docker/composer issue
    - docker-compose -p "ci-$CI_PROJECT_ID" --project-directory $CI_PROJECT_DIR -f build/docker-compose.staging.yml exec -T craft composer --working-dir=/data/craft require craftcms/aws-s3
    - docker-compose -p "ci-$CI_PROJECT_ID" --project-directory $CI_PROJECT_DIR -f build/docker-compose.staging.yml exec -T craft composer --working-dir=/data/craft require craftcms/redactor

我有一个 JSON 文件,其中包含插件的数据。下面提供的文件是.butler.json.

{
  "customer_number": "007",
  "project_number": "999",
  "site_name": "Welance",
  "local_url": "localhost",
  "db_driver": "mysql",


  "composer_require": [
      "craftcms/redactor",
      "craftcms/aws-s3",
      "nystudio107/craft-typogrify:1.1.17"
],
  "local_plugins": [
  "welance/zeltinger",
    "ansmann/ansport"
 ]
}

如何从 "composer_require""local_plugins" 文件中获取插件名称并在 .gitlab-ci.yml 文件中创建一个 for 循环来安装插件?

您无法在 .gitlab-ci.yml创建循环,因为 YAML 不是一种编程语言。它仅描述数据。你可以使用像 jq to query for your values (cat .butler.json | jq '.composer_require') inside a script, but you cannot set variables from there (there is a feature request 这样的工具。

您可以使用像 Jinja (which is often used with YAML, e.g. by Ansible and SaltStack) to generate your .gitlab-ci.yml from a template. There exists a command line tool j2cli 这样的模板引擎,它将变量作为 JSON 输入,您可以像这样使用它:

j2 gitlab-ci.yml.j2 .butler.json > .gitlab-ci.yml

然后您可以使用 Jinja 表达式循环遍历您的数据并在 gitlab-ci.yml.j2:

中创建相应的 YAML
{% for item in composer_require %}
  # build your YAML
{% endfor %}

缺点是您需要将已处理的 .gitlab-ci.yml 签入您的存储库。这可以通过 pre-commit-hook 完成(在每次提交之前,重新生成 .gitlab-ci.yml 文件,如果它发生更改,则将其与其他更改一起提交)。