Search code examples
ansiblecommand-line-interface

How do I access the command line arguments used to invoke Ansible?


I'd like to print out the command line arguments used to invoke ansible-playbook. E.g., if I do

ansible-playbook foo.yml -e bar=quux

, I'd like to have access to the above string, so that I can do as a task

- shell: slack_notify.sh "{{ ansible_cli_invocation }}"

where ansible_cli_invocation is a string with the value "ansible-playbook foo.yml -e bar=quux". Is there a way to do this?


Solution

  • I'm not sure you can do it out of the box.
    But you can write a tiny action plugin:

    from ansible.plugins.action import ActionBase
    import sys
    
    class ActionModule(ActionBase):
    
        TRANSFERS_FILES = False
    
        def run(self, tmp=None, task_vars=None):
            return { 'changed': False, 'ansible_facts': { 'argv': sys.argv } }
    

    Save it as ./action_plugins/get_argv.py and also make an empty file ./library/get_argv.py. This creates local action get_argv that populates argv fact with arguments list.

    Then in your playbook:

    - get_argv:
    - shell: slack_notify.sh "{{ argv | join(' ') }}"