Ansible by Chris - vidyasekaran/current_learning GitHub Wiki

Excerpts from Udemy - Master ansible by Chris Lunsford

https://docs.ansible.com/

Followed below steps to install Ansible

https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html#installing-ansible-on-ubuntu

List all hosts - this info comes from /etc/ansible/hosts (its ansible provided for us to play but we deleted all hosts)

root@ip-172-31-41-166:~# ansible --list-hosts all

Instead of keeping host names in /etc/ansible/hosts we need to have an inventory file which should be git committed and maintained

so create a directory and have below info /home/ubuntu/ansible/dev

[loadbalancer] lb01

[webserver] app01 app02

[database] db01

[control] control

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts all [provide **dev **file having host as input]

sudo vi /etc/ansible/ansible.cfg

Refer below the inventory file is pointed here, we are going to override this by creating our own cfg file

ansible.cfg

[default] inventory=./dev

which helps us to set /home/ubuntu/ansible/dev as default inventroy file #inventory = /etc/ansible/hosts

Now you execute below command without -i argument it works as we have overriden /etc/ansible/hosts with

/home/ubuntu/ansible/ansible.cfg root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts all

https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html

Executing part of the servers from our inventory file

Hit all targets root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts "*"

Hit individual group in dev file

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts loadbalancer

hosts (1): lb01

Hit single server

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts db01 [WARNING]: Found both group and host with same name: control hosts (1): db01

Hit Multiple servers starting with app*

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts app* [WARNING]: Found both group and host with same name: control hosts (2): app01 app02

List servers under database and webserver

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts database:webserver

1st Server under WebServer group

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts webserver[0]

List everything other than control group

root@ip-172-31-41-166:/home/ubuntu/ansible# ansible -i dev --list-hosts !control

Ansible Playbooks

A Playbook is a yml file having set of target hosts and commands to run against those hosts

Create a user called ansadmin (on Control node and Managed host)

useradd ansible passwd ansible

Below command grant sudo access to ansible user. But we strongly recommended using "visudo" command if you are aware vi or nano editor. (on Control node and Managed host)

echo "ansible ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers sudo su - ansible