如何动态标记container_image



我对巴泽尔世界有点陌生。我的目标是标记图像并将其推送到注册表,但要使用动态标记。在没有Bazel的情况下,我过去常常用git-commit SHA(6-7个字符(作为我的版本的后缀,例如1.0.0-a68hg4我想对container_push规则做同样的操作。

container_push(
name = "publish",
format = "Docker",
image = ":image",
registry = DOCKER_REGISTRY,
repository = "app1",
skip_unchanged_digest = True,
tag_file = "image.json.sha256",
)

代码是从这里复制的。我可以使用SHA,这使我的标签在构建之间是唯一的,但我可以连接字符串来制作我想要的东西吗。即1.0.0-a68h4(<a_custrongtr>-<SHA256_6_char>

提前感谢

您可以通过stamping获得git提交,rules_docker支持该操作。例如,将其放在workspace_status.sh:中

#!/bin/bash
echo "STABLE_GIT_COMMIT $(git rev-parse HEAD)"

然后,如果使用--workspace_status_command=workspace_status.sh构建,则可以编写tag = "something-{STABLE_GIT_COMMIT}"(并在container_push上设置stamp = True(。如果需要的话,git describe而不是git rev-parse可以用来包含当前标记或分支的名称。

如果你想把它和sha256结合起来,我会使用genrule创建一个这样的文件:

genrule(
name = "create_tag_file",
srcs = [
"image.json.sha256",
],
stamp = True,
outs = [ "my_tag_file" ],
cmd = "cat $(location image.json.sha256) > $@ && cat bazel-out/volatile-status.txt | grep STABLE_GIT_COMMIT | awk '{print $2}' >> $@",
)
container_push(
<same as before>
tag_file = ":my_tag_file",
)

在一个单独的文件中编写脚本(将其放在tools中,并使用$(location)获取其运行位置(将使字符串操作比像这样将其全部内联在cmd属性中更容易读取。

如果您想添加一个任意的标识字符串作为标记的一部分,bazel命令行上的--embed_label将在stable-status.txt中设置BUILD_EMBED_LABEL密钥。

感谢Brain Silverman提供的详细答案。

如果有人正在寻找一个简单的解决方案,就在这里。

build.sh(将docker映像推送到注册表的脚本(

version="1.0.0"
docker login -u "$USERNAME" -p "$PASSWORD" "$REGISTRY"
bazel run --workspace_status_command="echo VERSION $version-$(git rev-parse HEAD | cut -c 1-8)" //docker: publish

BUILD.bazel

container_push(
name = "publish",
format = "Docker",
image = ":image",
registry = DOCKER_REGISTRY,
repository = "app1",
skip_unchanged_digest = True,
tag_file = "{VERSION}",
)

对于快照,我建议基于源文件的SHA256进行版本控制。通过这种方法,只有当图像内容真正发生变化时,才会发布新标签。

看看https://github.com/mgosk/bazel-scala-example/blob/master/example-bin/BUILD

# https://github.com/mgosk/bazel-scala-example/blob/master/example-bin/BUILD
git_tag_with_sha_multitargets(
name = "version",
targets = [
":image",
"@java_base//image",
],
)
container_push(
name = "image-push",
format = "Docker",
image = ":image",
registry = "docker.io",
repository = "mgosk/example-bin",
tag_file = ":version",
)
# https://github.com/mgosk/bazel-scala-example/blob/master/tools/version.bzl
def git_tag_with_sha_multitargets(name, targets, postfix = "", **kwargs):
super_stable_status = "//:super_stable_status"
native.genrule(
name = name,
srcs = targets + [super_stable_status],
outs = [name + ".txt"],
cmd = """
STABLE_RELEASE_VERSION=$$(cat $(location """ + super_stable_status + """) | grep 'STABLE_RELEASE_VERSION' | awk '{print $$2}' || :)
POSTFIX=""" + postfix + """
if [[ -z "$$STABLE_RELEASE_VERSION" ]]; then
SHA256=$$(sha256sum $(location """ + " ) $(location ".join(targets) + """) | awk '{print $$1;}' | sha256sum | awk '{print $$1;}')
echo $$SHA256-SNAPSHOT > $(OUTS);
else
echo $$STABLE_RELEASE_VERSION$$POSTFIX > $(OUTS);
fi
""",
**kwargs
)

最新更新