First Ansible
How to install - Ubuntu
apt-get install ansible
ansible --version
ansible 2.0.0.2
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
pip2 install ansible-lint
https://github.com/willthames/ansible-lint
ansible-lint is python tool that checks playbooks for practices and behaviour that could potentially be improved.
Ansible concept
ansible.cfg: Ansible config.
Inventory: Remote server information
Playbooks: It like a script that is you want to deploy your environment on remote server.
Task: contains the main list of tasks to be executed by the role.
Handler: To trigger serivce status,e.g. restart, stop service.
Role: Roles are ways of automatically loading certain vars_files, tasks, and handlers based on a known file structure.
Example project structure:
site.yml
webservers.yml
fooservers.yml
roles/
common/
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webservers/
tasks/
defaults/
meta/
Prepare:
Managed Node
- IP
- User account
- Set public SSH key on each node
- Python > 2.7
Control Machine
- vim /etc/ansible/ansible.cfg
[defaults]
host_key_checking = False
Inventory
- Define managed node config
- Default on /etc/ansible/hosts
Playbook
- It is described by YAML
- Task
- Handler
- Role
Let's GO: Hello world
Create an Ansible project
mkdir hello-world
cd hello-world
Inventory: Set host and managed node config
vim /etc/ansible/ansible.cfg
[defaults]
hostfile = hosts
nano hosts
[apache] # Group Name
192.168.10.100 ansible_ssh_user=wongyt
Test connection:
ansible apache -m ping #python2
python3 /usr/bin/ansible apache -m ping #python3
192.168.10.100 | SUCCESS => {
"changed": false,
"failed": false,
"invocation": {
"module_args": {
"data": "pong"
}
},
"ping": "pong"
}
Playbook
nano playbook.yaml
---
- hosts: apache # group name
become: true # use sudo
tasks: # task array
- name: install apache2 # task name
apt: name=apache2 update_cache=yes state=latest # apt is ansible module
- name: enabled mod_rewrite
apache2_module: name=rewrite state=present
notify:
- restart apache2
handlers:
- name: restart apache2
service: name=apache2 state=restarte
Run ansible-playbook
ansible-playbook playbook.yaml # python2
python3 /usr/bin/ansible-playbook playbook.yaml # python3
#if you have another inventory, you can use -i
python3 /usr/bin/ansible-playbook -i hosts playbook.yaml