Low Orbit Flux Logo 2 F

Ansible - Basics

This is just a quick sample/demo of the core features it is meant to:

Everything on this page will be covered in more detail in the following sections.

You will want to start out by creating an inventory file.

Example inventory file:

/etc/ansible/hosts
192.0.3.25 server1.lab.net server2.lab.net [group2] server3.lab.net server4.lab.net [webservers] web1 web2 web3

You can ping all hosts in inventory with this command:



ansible all -m ping

Another test:



ansible all -a "/bin/echo Hello World"
ansible all -a "uname -a"

Basic playbook example:

test-task1.yaml
--- - name: A Test Playbook hosts: all tasks: - name: First Test command: "touch /home/user1/testing.txt"

Running a playbook:



ansible-playbook mytask.yaml

Using the ping module and sudo:



ansible all -m ping -u user1 -k             # specify user, ask password
ansible all -m ping -u user1 -k -b -K       # sudo to root

Run shell commands and copy files:



ansible group2 -m ansible.builtin.shell -a 'echo test > output.txt'
ansible group2 -m ansible.builtin.copy -a "src=/etc/hosts dest=/tmp/hosts"

Ensure started, stopped, restarted:



ansible webservers -m ansible.builtin.apt -a "name=nginx update_cache=yes" -b
ansible webservers -m ansible.builtin.apt -a "name=nginx state=absent" -b

ansible webservers -m ansible.builtin.service -a "name=nginx state=started" -b
ansible webservers -m ansible.builtin.service -a "name=nginx state=restarted" -b
ansible webservers -m ansible.builtin.service -a "name=nginx state=stopped" -b

See all facts:



ansible all -m ansible.builtin.setup

Useful Example

Playbook to install an NGINX web server and deploy a web page from a template:

web_deploy.yaml
--- - name: A Test Playbook hosts: webservers become: yes vars: var1: "TEST STRING" tasks: - name: Update repo cache and install nginx package ansible.builtin.apt: name: nginx update_cache: yes - name: Make sure a service is started, enabled, and not masked ansible.builtin.systemd: state: started name: nginx enabled: true masked: no - template: src: templates/index.html.j2 dest: /var/www/html/index.html mode: a+r

The actual template:

templates/index.html.j2
This is a sample page. Here is the test value: {{ var1 }} That is it.

Run the playbook as root on the remote hosts:



ansible-playbook -k -b -K web_deploy.yaml