Ansible Playbook Examples
Ansible Playbook Examples
You:
Share with me example codes for ansible playbook different use cases.I want complete code along with all use
cases information
------------------
ChatGPT:
Sure, I can provide you with some example Ansible playbook code for different use cases. However, please note
that the code might need to be adjusted based on your specific environment and requirements. Ansible playbooks
are written in YAML format and consist of tasks that define what actions should be taken on remote hosts. Let's
look at a few common use cases:
In this use case, we'll create a playbook to install a package on remote servers.
yaml
---
- name: Install Apache on Web Servers
hosts: webservers
become: yes
tasks:
- name: Update apt cache (for Debian/Ubuntu)
apt:
update_cache: yes
when: ansible_os_family == 'Debian'
handlers:
- name: Restart Apache
service:
name: apache2
state: restarted
This playbook will create a new user and deploy their SSH public key.
yaml
---
- name: Manage Users and SSH Keys
hosts: all
become: yes
tasks:
- name: Create user
user:
name: john
password: "{{ 'password' | password_hash('sha512') }}"
state: present
https://chat.openai.com 1/3
8/25/2023 Ansible Playbook Examples
user: john
key: "{{ lookup('file', '/path/to/john.pub') }}"
Here's an example playbook to deploy a web application by copying files and restarting the web server.
yaml
---
- name: Deploy Web App
hosts: webservers
become: yes
tasks:
- name: Copy app files
copy:
src: /path/to/app
dest: /var/www/html/app
yaml
---
- name: Backup Database
hosts: dbserver
become: yes
tasks:
- name: Dump database
command: mysqldump -u root -p{{ db_root_password }} dbname > /tmp/dbbackup.sql
vars:
db_root_password: your_db_root_password
yaml
---
- name: Deploy Docker Container
hosts: dockerhost
become: yes
tasks:
- name: Pull Docker image
docker_image:
name: nginx
source: pull
https://chat.openai.com 2/3
8/25/2023 Ansible Playbook Examples
Remember to replace placeholders like host names, paths, passwords, and other specific details with your actual
information. Additionally, these playbooks are basic examples and might require adjustments to suit your
environment and security requirements. Always ensure to thoroughly test in a controlled environment before
deploying to production.
------------------
https://chat.openai.com 3/3