Asible
Determine the version of Ansible that is installed:
$ ansible --version
The output will give you location of cfg as config file = /home/user100/.ansible.cfg. That file will give you location of inventory and you can check that file as follow:
$ cat /home/user100/.ansible.cfg
...
inventory = /home/user100/my_inventory/inventory.txt
...
$ cat /home/user100/my_inventory/inventory.txt
ansible_user=user1
ansible_ssh_pass=s3cret
ansible_port=22
[web]
node1 ansible_host=x.x.x.x
node2 ansible_host=x.x.x.x
node3 ansible_host=x.x.x.x
[control]
ansible ansible_host=x.x.x.x
Ad Hoc Commands
- list all hosts in inventory >
$ ansible all --list-hosts - ping all hosts in web group >
$ ansible web -m ping - get uptime from hosts in web group >
ansible web -m command -a "uptime" -o - get uptime from specific host only >
ansible node1 -m command -a "uptime" -o - install apache with yum on all hosts in web group >
$ ansible web -m yum -a "name=httpd state=present" -b -o - start apache on all hosts in web group >
$ ansible web -m service -a "name=httpd state=started" -b
Playbook
install_apache.yaml
---
- name: Install the apache web service
hosts: web
become: yes
tasks:
- name: install apache
yum:
name: httpd
state: present
- name: start httpd
service:
name: httpd
state: started
Tasks
Task run sequentially
| Module | Description |
|---|---|
| file | Create directory |
| yum | Install packages |
| service | Start/Stop services |
| template | Render template file from template |
| get_url | Fetch file from url |
| git | clone git from a repo |
Hnadlers
if task has notify: handler_name then handlers are called after task completion, e.g.:
tasks:
- name: " package is present"
yum:
name: ""
state: latest
notify: restart webserver
- name: latest index.html file is present
copy:
src: files/index.html
dest: /var/www/html/
handlers:
- name: restart webserver
service:
name: ""
state: restarted
Variables
Variables with same name defined in multiple sources are overwritten in specific order:
- Extra vars
- Task vars (only for task)
- Block vars (only for tasks in block)
- Role and include vars
- Play vars_files
- Play vars_prompt
- Play vars
- set_facts
- Registered vars
- Host facts
- Playbook host_vars
- Playbook group_vars
- Inventory host_vars
- Inventory group_vars
- Inventory vars
- Role defaults
Roles
Packaging of closely related ansible content in a directory structure to be shared easily.
Ansible galaxy
Online hub for finding, reusing and sharing ansible roles.
# ansible-galaxy init role-name