Elastic Beanstalk configuration using ebextensions container_commands combining leader_only and test
It turns out there is an environment variable called EB_IS_COMMAND_LEADER which can be used in a test. See e.g. this post on AWS forums.
So, the two container commands from the OP can be replaced by this:
container_commands:
  0100_execute_command_on_leader_only_but_never_on_worker:
    command: foo bar
    test: '[[ $ENV_NAME != &quot;worker&quot; &amp;&amp; $EB_IS_COMMAND_LEADER == &quot;true&quot; ]]'

I believe this environment variable is only available during deployment, although I could not find any documentation.
NOTE: The original question was aimed at Amazon Linux AMI (AL1), which is now deprecated. In the new Amazon Linux 2 we can use shell scripts in .platform/hooks/ as an alternative to container_commands. The EB_IS_COMMAND_LEADER variable can be used there as well.