Ansible: Command Line Arguments
While running your Ansible playbook, we can have the option of passing the argument from the command line. With the help of this, we define a generic playbook and use command line arguments to control the play. Let see how
Let's first start with the playbook, where we have defined the variable x is the playbook.
---
- hosts: all
vars:
x: 45
tasks:
- debug: var=x
In this playbook, we will pass the value of x from the command line arguments with the help -e “value”.
---
- hosts: all
tasks:
- debug: var=x
>> ansible-playbook playbook_nmae.yml -e "x=56"
Now let's write a playbook which can uninstall/install a package with the help of command line arguments.
---
- name: Install/Unistall pacakges with command line
hosts: all
became: 'yes'
tasks:
- name: 'working with {{pkg}}'
apt:
name: '{{pkg}}'
state: '{{req_state}}'
Now, from the command line, we can pass the package name and state of the package.
>>ansible-playbook playbook_name.yml -e "pkg=nginx req_state=present"
>>ansible-playbook playbook_name.yml -e "pkg=nginx req_state=absent"
Cheers!