jreid42
jreid42

Reputation: 1250

Dynamic Makefile targets with dynamic prerequisites

If I have a list of things such as this:

nodes = A B C 

How would I generate dynamic targets that have dynamic prerequisites. For example (this isn't working but might help explain what I want).

# node.csr is a file that already exists, like a template
# this would create outputs like node-A-csr.json, node-B-csr.json
# I am basically guessing at the syntax here 
node-%-csr.json: node-csr.json
    sed 's/$${node}/$*' node-csr.json > $@

# this would create outputs like node-A-key.pem node-A.pem and would require node-A-csr.json
node-%-key.pem node-%.pem: node-%-csr.json
    # some command that generates node-NAME-key.pem and node-NAME-csr.pem

$(nodes): node-%-key.pem node-%.pem

Id basically like to be able to run make all and have those targets run for everything in my list.

I am very new to Makefiles and I just dont see how something like this would work and the documentation and syntax of Make is extremely confusing to me.

I am willing to use any tool to do this but seems like Make is very standard.

Upvotes: 1

Views: 769

Answers (1)

dash-o
dash-o

Reputation: 14493

You can use Make's Substitution References to generate the 'all' target. This will be enough to start processing of all rules.

Notice minor change: the 'node-csr.json' should have the token NODE where the actual node name is to be inserted

# First rule is the default
default: all

nodes = A B C

        # use node-csr as a template, replacing NODE with current ID: A, B, C
node-%-csr.json: node-csr.json
        sed 's/__NODE__/$*/' node-csr.json > $@

# this would create node-A-key.pem node-A.pem from node-A-csr.json
        # Put real commands here
node-%-key.pem node-%.pem: node-%-csr.json
        ls -l node-$*-csr.json > node-$*-key.csr
        ls -l node-$*-csr.json > node-$*.pem

    # all will be node-A-key.pem, node-B-key.pem, ... node-C.pem

all: $(nodes:%=node-%-key.pem) $(nodes:%=node-%.pem)
        echo "done"

# Using pathsubst:   all: $(patsubst %,node-%-key.pem,$(nodes)) $(pathsubst 

Please pay attention to tab/spaces, some version are sensitive. You will have to put back tabs before all commands (sed, ls, ...)

Substitution References man: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html

pathsubst function: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html

Upvotes: 1

Related Questions