LAB 6: Basic Commands of Ansible


LAB 6: Basic Commands of Ansible

Host Patterns

vi /etc/ansible/hosts

//“all” pattern referes to all the machines in an inventory
ansible all --list-hosts
ansible <group name> --list-hosts
ansible <group name>[0] --list-hosts

//You can refer to hosts within the group by adding a subscript to the group name while giving the pattern
Groupname[0]  -> Picks the first machine in the group
Groupname[1]  -> Picks the second machine in the group
Groupname[-1] -> Picks the last machine in the group
Groupname[0:1] -> Picks first 2 machine in the group

//Group separated by colon can be used to use hosts from multiple groups

Ansible ad-hoc commands

  • Use of ad-hoc tasks really quick and don’t want to save for later
  • These are quick one-liner without writing a playbook
  • To run an arbitrary command use (-a)
ansible all --list-hosts
ansible demo –a “ls”
ansible demo –a “ls-al”
ansible demo –a “touch myfile” (re run and verify idempotence)
ansible demo –a “yum install httpd –y” (shows permission denied)
  • To run anything with sudo, use –b
ansible demo –b –a “yum install httpd –y”
ansible demo –b –a “yum remove httpd –y” 

Ansible Modules

  • To run an arbitrary cmd use –a & use –m to run a module
ansible [group] –m <module> -z <cmd>
ansible demo –m ping
ansible demo –b –m yum –a “pkg=httpd state=present”
ansible demo –b –m yum –a “pkg=httpd state=latest”
ansible demo –b –m yum –a “pkg=httpd state=absent”

// State=present will install it
// State=latest will update
//State=absent will remove it
  • Start/Stop a service
ansible demo –b –m service –a “name=httpd state=started”
ansible demo –b –m service –a “name=httpd state=restarted”
ansible demo –b –m service –a “name=httpd state=stopped”
  • Create/Delete a user account
ansible demo –b –m user –a “name=raj”
ansible demo –b –m user –a “name=raj state=absent”
  • Gathering facts (Idempotence)
ansible demo –m setup
ansible demo –m setup –a ‘filter=*ipv4*’


  • Playbook is like a file where you write code. Playbooks are expressed in YAML format
ansible-playbook <playbook>.yml
  • For Ansible, nearly every YAML file starts with a list
  • Each item in the list is a list of key/value pairs, commonly called a “dictionary”
  • All YAML files have to begin with “—” and end with “ —”
  • All members of a list lines must begin with same indentation level starting with “-”
---# A list of tasty fruits
  - Apple
  - Orange
  - Straberry
  - Mango
  • A dictionary is represented in a simple key:value form
---#An employee record
  name: Ram
  job: DevOps Engineer
  skill: Elite