'Creating multiple similar genrules and using their output

I have a genrule that looks like the below. It basically runs a simple go template tool that gets a resource name, a json file and template and outputs the rendered file. I have a bunch of resources that all need to be in separate files and ultimately packaged into a container.

resources = ["foo", "bar"]
[genrule(
    name = "generate_" + resource + "_config",
    srcs = [
        "//some:tool:config.tmpl",
        "//some:json",
    ],
    outs = [resource + ".hcl"],
    cmd = "$(location //some/tool:template) -resource " + resource + " -json_path=$(location //some:json) -template=$(location //some/tool:config.tmpl) -out=$@",
    tools = [
        "/some/tool:template",
    ],
) for resource in resources]

The above will generate a few rules named generate_foo_config and generate_bar_config and the files output correctly. I however cannot figure out how to use each one without specifying them directly in a filegroup or pkg_tar rule without enumerating each one. I would like to be able to add a new thing to the resources variable, and have it automatically included in the filegroup or tar for use in a build rule later. Is this possible?



Solution 1:[1]

Use a list comprehension, like you've got creating the genrules. Something like this:

pkg_tar(
    name = "all_resources",
    srcs = [":generate_" + resource + "_config" for resource in resources],
)

You can also put the list in a variable in the BUILD file to use it multiple times:

all_resources = [":generate_" + resource + "_config" for resource in resources]
pkg_tar(
    name = "all_resources",
    srcs = all_resources,
)
filegroup(
    name = "resources_filegroup",
    srcs = all_resources,
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Silverman