Ansible introduction
Modules
- Command module: Takes the command and executes it
- Shell module: Executes through a shell like /bin/sh
- Script module: Runs a local script on a remote node after transferring it.
- raw: executes a ssh command. useful for installation python3
Adhoc commands
Examples:
- ansible all - ping
- ansible web -m command -a “uptime”
- ansible localhost -m setup
Static inventory
Sample inventory:
|
|
Test adhoc commands
- ansible all -i hosts.ini -u vagrant -m ping: to test if systems are up
- ansible all -i hosts.ini -u vagrant -m setup: to test if system is setup
- ansible webservers -i hosts -u vagrant -m yum -a “name=python36 state=present” -b: installing packages python. -a is for args for yum module, -b become root
- Ansible is idempotent
- ansible webservers -i hosts -u vagrant -m yum -a “name=python36 state=absent” -b: to remove python
Variables
Ansible can work with metadata from various sources and manage their context in the form of variable. Can be facts, filepaths, package versions, etc.
Variable precedence (ansible 2.x):
- Extra vars
- Task vars
- Block vars
- 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
get_url: download an archive git: clone a source code repo
Tasks
Example tasks in a play
|
|
Handler Tasks
Handlers are special tasks that run at the end of the play if notified by another task (caused by change of state). If a configuration file gets changed notify a service restart it needs to run.
|
|
Plays and Playbooks
Plays are ordered sets of taks to execute against host selections from your inventory. A playbook is a file containing one or more plays
Playbook example:
|
|
Playbook files
site.yml(or main.yml)
|
|
- ansible-playbook -i hosts site.yml: to run playbook (execute tasks from top to bottom)
Transition playbooks to roles
Roles are a packages of closely related ansible content that can be shared more easily than plays alone
Roles directory structure
- defaults:
- files:
- handlers:
- meta:
- molecule:
- tasks:
- templates:
- vars:
Creating a new role
- ansible-galaxy init –help
- ansible-galaxy init role_name
- meta: flush_handler: runs the handler right now
Running multiple roles in a playbook
Example:
|
|