Ansible Playbook Exercises
Limited Time Offer!
For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!
https://www.devopsschool.com/blog/ansible-playbook-lab-excercise-part-2/
# inventory
[web]
13.232.181.124
35.154.128.2
[web:vars]
ansible_user=centos
ansible_ssh_private_key_file=node.pem
ansible_become=yes
#assignment.yaml
- name: Playbook Assignment
hosts: web
tasks:
- name: Create group called deploy
group:
name: Deploy
state: present
- name: Create user in group with bin bash shell
user:
name: deploy-user
shell=/bin/bash
state: present
- name: Install the latest version of Apache
yum:
name: httpd
state: latest
- name: Create file second in var/www/html
file:
path: /var/www/html/second.html
state: file
- name: Copy file with owner and permissions
ansible.builtin.copy:
src: index.html
dest: /var/www/html/index.html
- name: Start service httpd, if not started
ansible.builtin.service:
name: httpd
state: started
- name: Install the latest version of git and wget
yum:
name: git
state: latest
yum:
name: wget
state: latest
- name: Playbook Assignment
hosts: localhost
tasks:
- name: Clone repository
git:
repo: 'https://github.com/scmgalaxy/ansible-role-template
dest = /home/centos/ansible/sanchita
clone: yes
- name: Start service httpd, if not started
reboot:
To run the playbook:
$ ansible-playbook -i inventory assignment.yaml
Playbook Variables
# playbook-variables.yaml
---
- name: Variable precedence
hosts: localhost
vars:
myname: Sanchita
vars_prompt:
- name: "myname"
prompt: "What is your name?"
private: false
vars_files:
- ext-vars.yaml
tasks:
- name: Print the vars
ansible.builtin.debug:
msg: My name {{ myname }}
- name: include default step variables
include_vars: var-include.yaml
- name: Print the vars
ansible.builtin.debug:
msg: My name {{ myname }}
- name: Ansible register variable basic example
shell: "find *.yaml"
args:
chdir: "/home/centos/ansible/sanchita"
register: find_output
- debug:
var: find_output.stdout_lines[0]
- name: Print the vars
ansible.builtin.debug:
msg: My name is {{ myname }}
Precedence of Variables
- Command Line variable takes precedence over all other.
- Variables using task include takes precedence over all, except command line variable.
- External variables take precedence over variable prompt.
- Variable using prompt takes precedence over embedded variables.