Makefile - how to add command flags conditionally

Viewed 305

Example using makefile with ansible(but question is for any command):

deploy:
      ansible-playbook ansible/playbook-deploy.yml \
        -i ansible/environments/$(ENV)/inventory \
      -e "$(ARGS)" \
      --tags="$(TAGS)" \
      --skip-tags="$(SKIP_TAGS)" \
      $2 2>&1 | tee -a ${LOG_PATH}

Now I want to skip adding -e , --tags, --skip-tags flags if the variables are correspondingly empty ARGS/TAGS/SKIP_TAGS

Something like this will not work ifdef ARGS -e "$(ARGS)" \ endif

I am begginer to makefiles so errors are expected, so please advise me for resources how to implement this case, thanks

I don't want to add \ then in next line --tags=... if TAGS variable is not defined, same for the others

2 Answers

A simple way is to use make's $(if ...) function, like this:

ansible-args = $(if $(ARGS),-e '$(ARGS)') \
               $(if $(TAGS),--tags='$(TAGS)') \
               $(if $(SKIP_TAGS),--skip-tags='$(SKIP_TAGS)')

deploy:
        ansible-playbook ansible/playbook-deploy.yml \
               -i ansible/environments/$(ENV)/inventory \
               $(ansible-args) $2 2>&1 | tee -a ${LOG_PATH}

This will work, found first solution but is very ugly and I don't like it. Want to learn most elegant solution so looking for answers.


ifdef ARGS
    $(eval args=-e='$(ARGS)')
endif
ifdef TAGS
    $(eval tags=--tags='$(TAGS)')
endif
ifdef SKIP_TAGS
    $(eval skipTags=--skip-tags='$(SKIP_TAGS)')
endif

    ansible-playbook ansible/playbook-deploy.yml \
        -i ansible/environments/$(ENV)/inventory \
      $(args) \
      $(tags) \
      $(skipTags) \
      $2 2>&1 | tee -a ${LOG_PATH}

Also here command will be super ugly if no args tags skiptags specified like

ansible-playbook ansible/playbook-deploy.yml \
        -i ansible/environments/development/inventory \
       \
   \
       \
       2>&1 | tee -a logs/development/2021-07-04_17_46_45.log

Related