Applying Loops to Automate Repetitive Tasks
Ansible loops are incredibly versatile and can be applied to a wide range of automation tasks. In this section, we'll explore some common use cases and demonstrate how to leverage loops to streamline your automation efforts.
Provisioning Infrastructure
Ansible loops can simplify the process of provisioning multiple servers, virtual machines, or cloud resources. By using a loop, you can create and configure multiple instances with a single playbook.
- name: Provision EC2 instances
ec2:
key_name: mykey
instance_type: t2.micro
image: "{{ item }}"
wait: true
group: webserver
count: 3
vpc_subnet_id: subnet-abcd1234
assign_public_ip: yes
with_items:
- ami-0c94755bb95c71c99
- ami-0c55b159cbfafe1f0
- ami-0d1cd67c26f5fca19
This example uses the with_items
loop to provision three EC2 instances, each with a different Amazon Machine Image (AMI).
Configuring Network Devices
Ansible loops can also be used to configure multiple network devices, such as switches, routers, or firewalls, in a consistent and scalable manner.
- name: Configure network interfaces
ios_interface:
name: "{{ item.name }}"
description: "{{ item.description }}"
state: present
with_items:
- { name: "GigabitEthernet0/0", description: "Uplink to router" }
- { name: "GigabitEthernet0/1", description: "Internal network" }
- { name: "GigabitEthernet0/2", description: "DMZ network" }
This example demonstrates how to use a loop to configure multiple network interfaces on an Cisco IOS device.
Deploying Applications
Ansible loops can simplify the process of deploying multiple applications or services, ensuring consistency and reducing the risk of manual errors.
- name: Deploy web applications
template:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
with_items:
- { src: "app1.conf.j2", dest: "/etc/nginx/conf.d/app1.conf" }
- { src: "app2.conf.j2", dest: "/etc/nginx/conf.d/app2.conf" }
- { src: "app3.conf.j2", dest: "/etc/nginx/conf.d/app3.conf" }
In this example, the with_items
loop is used to deploy multiple web application configuration files to an Nginx server.
By applying Ansible loops to these and other automation tasks, you can significantly improve the efficiency and consistency of your infrastructure management and application deployment processes.