Ansible Essentials

Linux Logo

Ansible Essentials

Install

sudo apt install ansible -y
Reading package lists… Done
Building dependency tree
Reading state information… Done

The following NEW packages will be installed:
ansible python3-argcomplete python3-crypto python3-dnspython python3-jinja2 python3-kerberos python3-libcloud python3-netaddr
python3-ntlm-auth python3-requests-kerberos python3-requests-ntlm python3-selinux python3-winrm python3-xmltodict
0 to upgrade, 14 to newly install, 0 to remove and 7 not to upgrade.
Need to get 8,114 kB of archives.
After this operation, 80.1 MB of additional disk space will be used.

Inventory

nano inventory

[servers]
10.10.10.10
192.168.1.10

Config File

nano ansible.cfg

[defaults]
inventory = inventory
private_key_file = ~/.ssh/ansible
remote_user = ec2_user

Test Connectivity

Assuming inventory, private key, and remote user are set in ansible.cfg

ansible all -m ping

Providing all the minimum values

ansible all -i inventory --key-file ~/.ssh/ansible -u ec2_user -m ping

Providing all the minimum values and specifying inventory group “servers”

ansible all -i inventory servers --key-file ~/.ssh/ansible -u ec2_user -m ping

Running ad-hoc Commands

Ansible defaults to the “-m command”

ansible all -m command -a "free -h" -u ec2_user
ansible all -a "free -h" -u ec2_user
ansible all -a "date" -u pi

Ad Hoc Examples

Service

ansible webservers -m service -a "name=httpd state=started enabled=yes"

Playbook

Run

ansible-playbook playbook.yml

Tags

ansible-playbook --list-tags playbook.yml

Limiting Scope

Using Tags

–tags
Anything with this label will be run only

ansible-playbook main.yml --tags linux

–skip-tags
Anything with this label will be skipped

ansible-playbook main.yml --skip-tags windows

–tags & –skip-tags

ansible-playbook main.yml --tags ubuntu --skip-tags groovygorilla

Using –limit

–limit
Can be used on ad-hoc commands also

ansible-playbook main.yml --limit hostname,groupname
ansible all -m ping --limit hostname,groupname

Tags & –Limit

ansible-playbook main.yml --tags ubuntu,redhat --skip-tags groovygorilla,bionicbeaver --limit hostname,groupname

Output to File

ansible-playbook get-facts.yml --limit computer1 &> ~/Desktop/computer1.yml
  • https://docs.ansible.com/ansible/latest/index.html
  • https://docs.ansible.com/ansible/latest/modules/service_module.html
  • https://docs.ansible.com/ansible/latest/modules/ufw_module.html
,