Ansible - Basics
You will want a user and ssh key on every host.
You will want to start out by creating an inventory file.
Example inventory file:
/etc/ansible/hosts192.0.3.25 server1.lab.net server2.lab.net
You can ping all hosts in inventory with this command:
ansible all -m ping
Another test:
ansible all -a "/bin/echo Hello World"
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 # specify user
ansible all -m ping -u user1 --become # sudo to root
ansible all -m ping -u user1 --become --become-user admin # sudo to admin
Ad hoc commands:
ansible group1 -a "/sbin/reboot" # as current user
ansible group1 -a "/sbin/reboot" -f 10 # as current user, 10 parallel forks
ansible group1 -a "/sbin/reboot" -f 10 -u username # as this user
ansible group1 -a "/sbin/reboot" -f 10 -u username --become # as this user, then sudo to root
ansible group1 -a "/sbin/reboot" -f 10 -u username --become --ask-become-pass # ask sudo password
ansible group1 -a "/sbin/reboot" -f 10 -u username --become --K # .
Shell module:
- can use pipes and redirects
- be careful quoting variables
ansible group2 -m ansible.builtin.shell -a 'echo test > output.txt'
ansible group2 -m ansible.builtin.copy -a “src=/etc/hosts dest=/tmp/hosts”
Permissions / ownership:
ansible webservers -m ansible.builtin.file -a "dest=/srv/foo/a.txt mode=600"
ansible webservers -m ansible.builtin.file -a "dest=/srv/foo/b.txt mode=600 owner=mdehaan group=mdehaan"
Create directory:
ansible webservers -m ansible.builtin.file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory"
Delete recursively:
ansible webservers -m ansible.builtin.file -a "dest=/path/to/c state=absent"
Install without updating:
ansible webservers -m ansible.builtin.yum -a "name=acme state=present"
Ensure specific version is installed:
ansible webservers -m ansible.builtin.yum -a "name=acme-1.5 state=present"
Latest version:
ansible webservers -m ansible.builtin.yum -a "name=acme state=latest"
Ensure package is not installed:
ansible webservers -m ansible.builtin.yum -a "name=acme state=absent"
Users:
ansible all -m ansible.builtin.user -a "name=foo password=<crypted password here>"
ansible all -m ansible.builtin.user -a "name=foo state=absent"
Ensure started, stopped, restarted:
ansible webservers -m ansible.builtin.service -a "name=httpd state=started"
ansible webservers -m ansible.builtin.service -a "name=httpd state=restarted"
ansible webservers -m ansible.builtin.service -a "name=httpd state=stopped"
See all facts:
ansible all -m ansible.builtin.setup