Day: March 18, 2022

Learning – Ansible 101 – Episode 1 – Introduction to Ansible

Learning - Ansible 101 - Episode 1 - Introduction to Ansible

Introduction to Ansible

Installation

pip3 install ansible
ansible --version

Create inventory file

Create a file called inventory

[example]
107.20.106.183

Run command

ansible -i inventory example -m ping -u centos

Create ansible.cfg file

[defaults]
INVENTORY=inventory

Run command with not inventory option

ansible example -m ping -u centos

Run ad-hoc commnad

ansible example -a "date" -u centos
ansible example -a "free -h" -u centos

In fact, above commands used default module -m command, and the -a option is giving the command arguments.

Install VirtualBox and Vagrant

Then initialize vagrant

vagrant init geerlingguy/centos7

This will create a file called Vagrantfile in current directory.

Vargent VM commands

  • create vm
vagrant up
  • ssh into vm
vagrant ssh
  • show ssh configuration
vagrant ssh-config

This configuration can be used to update ssh configuration

  • shutdown vm
vagrant halt
  • delete vm
vagrant destroy

Create Vagrantfile

Vagrant.configure("2") do |config|
  config.vm.box = "geerlingguy/centos7"

  config.vm.provsion "ansible" do |ansible|
    ansible.playbook = "playbook.yml"
  end
end

Create playbook.yml

---
- name: Set up NTP on all servers.
  hosts: all
  become: yes
  tasks:
    - name: Ensure NTP is installed.
      yum: name=ntp state=present
    - name: Ensure NTP is running.
      service: name=ntpd state=started enabled=yes

The name is optional

    - yum: name=ntp state=present
    - service: name=ntpd state=started enabled=yes

Run provision command

vagrant provision

Idempotence

The command can be run many times without change the result if success before.

But following command in playbook will run every time when triggered playbook.

  - command: yum install -y ntp

To overcome this, change to following

  - shell: |
      if ! rpm -qa | grep -qw ntp; then
        yum install -y ntp
      fi

References

Ansible 101 - Episode 1 - Introduction to Ansible