Category : Devops | Sub Category : Devops | By Prasad Bonam Last updated: 2023-07-23 20:16:51 Viewed : 63
Various examples of Ansible scripts (playbooks) :
Here are some various examples of Ansible scripts (playbooks) for different use cases:
Example 1: Installing Packages
yaml---
- name: Install packages on remote hosts
hosts: your_remote_servers
become: yes
tasks:
- name: Install required packages
apt:
name:
- package1
- package2
state: present # Use "absent" to uninstall packages
when: ansible_os_family == Debian # For Debian/Ubuntu systems
- name: Install required packages
yum:
name:
- package1
- package2
state: present # Use "absent" to uninstall packages
when: ansible_os_family == RedHat # For RedHat/CentOS systems
Example 2: Managing Services
yaml---
- name: Manage services on remote hosts
hosts: your_remote_servers
become: yes
tasks:
- name: Ensure Nginx is started and enabled
service:
name: nginx
state: started
enabled: yes
Example 3: Managing Users
yaml---
- name: Manage users on remote hosts
hosts: your_remote_servers
become: yes
tasks:
- name: Create a new user
user:
name: john
state: present # Use "absent" to remove the user
groups: sudo
append: yes
- name: Set SSH key for the user
authorized_key:
user: john
key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAB..."
Example 4: Managing Files
yaml---
- name: Manage files on remote hosts
hosts: your_remote_servers
become: yes
tasks:
- name: Copy a file to remote host
copy:
src: /path/to/local/file
dest: /path/on/remote/host
owner: john
group: john
mode: `0644` # File permissions
Example 5: Running Shell Commands
yaml---
- name: Execute shell command on remote hosts
hosts: your_remote_servers
become: yes
tasks:
- name: Run a shell command
shell: echo "Hello, Ansible!"
Example 6: Using Variables
yaml---
- name: Use variables in playbook
hosts: your_remote_servers
become: yes
vars:
my_var: "Hello, Ansible!"
tasks:
- name: Print a variable
debug:
var: my_var
Example 7: Using Loops
yaml---
- name: Use loop in playbook
hosts: your_remote_servers
become: yes
vars:
my_packages:
- package1
- package2
- package3
tasks:
- name: Install packages using loop
package:
name: "{{ item }}"
state: present
loop: "{{ my_packages }}"
These are just a few examples of what you can do with Ansible. The possibilities are vast, and Ansible provides a rich set of modules and features to manage various aspects of your infrastructure and automate tasks efficiently.