In this and following tutorials, we’ll use 4 systems like:
- localhost as control node (CentOS 8.2 x64)
- zeus (CentOS 8.2 x64)
- ares (CentOS 8.2 x64)
- hades (CentOS 8.3 x64)
I won’t explain key based authentication for the nodes, so you should do it your own before work on tasks.
1-) Create Ansible configuration file /home/deniz/.ansible.cfg to apply following requirements:
- Inventory file should be existed in /home/deniz/inventory
- Use ‘deniz’ as remote user
- Enable privilege escalation
- Use ‘root’ for become user
- Use ‘sudo’ for become method
Use SSH public key authentication to prevent password prompt.
Export ANSIBLE_CONFIG environment variable to set .ansible.cfg file.
2-) Create the inventory file with following requirements:
- ‘zeus’ is a member of the development host group.
- ‘ares’ is a member of the stage host group.
- ‘hades’ is a member of the production host group.
- ‘zeus’ and ‘ares’ are members of the test host group.
Verify the hosts after these changes.
3-) Gather the facts and show ansible_hostname fact of each host.
4-) Create a playbook /home/deniz/task_1.yml that must be performed following requirements:
- Change ‘motd’ file as ‘This is Dev environment’ for development group.
- Change ‘motd’ file as ‘This is Stage environment’ for stage group.
- Change ‘motd’ file as ‘This is Production environment’ for production group.
Let’s create configuration file and edit it with vi.
vi /home/deniz/ansible.cfg
First of all, we must define default settings.
[defaults]
inventory = /home/deniz/inventory
remote_user = deniz
ask_pass = false
With this configuration we provided inventory file, remote user and passwordless authentication.
Now let’s apply privilege escalation section.
[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false
We provided what was desired for Ansible configuration. The final version should be like this screenshot:
Export ANSIBLE_CONFIG variable:
export ANSIBLE_CONFIG=/home/deniz/.ansible.cfg
Now we can move on to the second question.
Create inventory file and edit it:
vi /home/deniz/inventory
[development]
zeus
[stage]
ares
[production]
hades
[test:children]
development
stage
‘zeus’ and ‘ares’ are used as a subgroup for the test environment.
Verify the changes.
ansible-inventory list
Seems good. Now we can run ad-hoc command to get hostname fact.
ansible all -m setup | grep -i hostname
Let’s continue with fourth question. Create the playbook and edit:
vi /home/deniz/task_1.yml
Task is same for all environments, only difference is we should arrange environment string according to hostname. This can be done with Jinja2 but let’s do it with ‘when’ condition.
- name: dev
copy:
content: 'This is Dev environment'
dest: /etc/motd
when: "'development' in group_names"
So playbook should be:
Seems fine. Run the playbook:
ansible-playbook /home/deniz/task_1.yml
We can see ‘changed’ information. Let’s check if it really has changed.
Done!
To be continued.