Ansible, a powerful DevOps tools for Automation. Installed Ansible in a management Node, can use SSH to connect devices to perform complex business logic.
Installation
Install ansible in CentOS
sudo yum -y install ansible
Check Ansible version
ansible --version
Basic command
Create Inventory file, e.g. host
1
2
3
4
5host.ini
[webserver]
host1 ansible_host=192.168.150.132
host2 ansible_host=192.168.150.131Run with specify inventory
ansible -i host host1 -m ping
Modify the config file for one off change
Ansible Playbook
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18test.yml
- hosts: webserver
gather_facts: false
become: true
tasks:
- name: install th latest version of Apache
yum:
name: httpd
state: absent
register: result
- debug:
msg:
- '{{result}}'Run Ansible Playbook
ansible-playbook test_playbook
Run ad-hoc command
ansible webserver -m yum -a "name=httpd state=absent" --become
Parameterize Playbook
Parameterzie Playbook
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18test.yml
- hosts: '{{device_name}}'
gather_facts: false
become: true
tasks:
- name: install th latest version of Apache
yum:
name: httpd
state: absent
register: result
- debug:
msg:
- '{{result}}'Run with specify parameters
ansible-playbook playbooks/test.yml --extra-var '{"device_name": ["webserver"]}'
Custom module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29test_module.py
from ansible.module_utils.basic import *
def main():
module_args = dict(
a=dict(type='str', required=True),
b=dict(type='str', required=True),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
a = module.params['a']
b = module.params['b']
response = {
"tasks": {
"key_b": b,
"key_a": a,
}
}
module.exit_json(changed=True, meta=response)
if __name__ == '__main__':
main()Run custom module with ad-hoc
ansible webserver -m test_module -a "a=1 b=2"
Run custom module inside playbook
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18test.yml
- hosts: '{{device_name}}'
gather_facts: false
become: true
tasks:
- name: Test Custom Module
test_module:
a: "Hello, "
b: "World"
register: result
- debug:
msg:
- '{{result}}'Command to run playbook
ansible-playbook playbooks/test.yml --extra-var '{"device_name": ["webserver"]}'
Ref
Ansible: https://www.ansible.com/