Practical Example: Iterating Over Server Hostnames
π·οΈ Loops and Iteration / The For Loop
π§ Context Introduction
When managing infrastructure, you often need to perform the same action across multiple serversβwhether it's checking their status, deploying updates, or gathering logs. Instead of writing repetitive code for each server, you can use a for loop to iterate over a list of hostnames and execute the same logic for each one. This makes your scripts cleaner, more scalable, and easier to maintain.
βοΈ What We're Building
We'll create a simple script that loops through a list of server hostnames and prints a status message for each one. This is a foundational pattern you'll use again and again in automation tasks.
π οΈ Step-by-Step Breakdown
1. Define a List of Hostnames
Start by storing your server hostnames in a Python list. Each hostname is a string enclosed in quotes, separated by commas.
- Example list: server_hostnames = ["web-01", "db-01", "cache-01", "app-01"]
2. Write the For Loop
Use the for keyword followed by a variable name (like host) and the in keyword to iterate over the list.
- Structure: for host in server_hostnames:
3. Add the Action Inside the Loop
Indent the code you want to run for each hostname. This is the body of the loop.
- Action: print(f"Checking status of {host}...")
4. Run the Script
When executed, the loop will run once for every hostname in the list, printing a message for each.
- Expected output:
- Checking status of web-01...
- Checking status of db-01...
- Checking status of cache-01...
- Checking status of app-01...
π Comparison: Without Loop vs. With Loop
| Approach | Code Example | Scalability |
|---|---|---|
| Without Loop | print("Checking status of web-01...") print("Checking status of db-01...") print("Checking status of cache-01...") print("Checking status of app-01...") |
Poor β you must manually add or remove lines for each server |
| With Loop | for host in server_hostnames: print(f"Checking status of {host}...") |
Excellent β just update the list, and the loop handles the rest |
π΅οΈ Key Takeaways
- A for loop lets you repeat an action for every item in a list without writing duplicate code.
- The loop variable (e.g., host) takes the value of each list item one at a time.
- Indentation is critical in Pythonβeverything inside the loop must be indented consistently.
- This pattern works for any list: IP addresses, environment names, region codes, or even file paths.
π Next Steps
Once you're comfortable with this basic example, try expanding it:
- Add an if condition inside the loop to skip certain hostnames.
- Use a dictionary to store hostnames along with their IP addresses.
- Replace the print statement with a function call that actually pings or connects to each server.
Mastering the for loop with lists is a huge step toward writing real-world automation scripts.
This section shows how to use a for loop to process a list of server hostnames, a common task for engineers managing multiple machines.
π₯οΈ Example 1: Printing Each Hostname
This example prints each server hostname from a list, one at a time.
servers = ["web01", "db01", "app01"]
for hostname in servers:
print(hostname)
π€ Output: web01 db01 app01
π’ Example 2: Adding a Number to Each Hostname
This example appends a sequential number to each hostname to create unique identifiers.
servers = ["web", "db", "app"]
for i in range(1, 4):
hostname = servers[i-1] + str(i)
print(hostname)
π€ Output: web1 db1 app1
π Example 3: Building Full Domain Names
This example constructs a full domain name for each server by adding a common suffix.
servers = ["web01", "db01", "app01"]
domain = ".example.com"
for hostname in servers:
full_name = hostname + domain
print(full_name)
π€ Output: web01.example.com db01.example.com app01.example.com
π‘ Example 4: Checking Hostname Length
This example checks if each hostname is longer than 4 characters and prints a message.
servers = ["web01", "db01", "app01", "mon"]
for hostname in servers:
if len(hostname) > 4:
print(hostname + " is long")
else:
print(hostname + " is short")
π€ Output: web01 is long db01 is long app01 is long mon is short
π Example 5: Pinging Multiple Servers (Simulated)
This example simulates pinging each server and prints a status message.
servers = ["web01", "db01", "app01"]
status = ["up", "up", "down"]
for i in range(len(servers)):
hostname = servers[i]
current_status = status[i]
print("Pinging " + hostname + "... Status: " + current_status)
π€ Output: Pinging web01... Status: up Pinging db01... Status: up Pinging app01... Status: down
π Comparison Table: Loop Variations
| Example | Loop Type | What It Does |
|---|---|---|
| 1 | for item in list | Prints each hostname directly |
| 2 | for i in range() | Adds numbers to hostnames |
| 3 | for item in list | Builds full domain names |
| 4 | for item in list | Checks hostname length |
| 5 | for i in range() | Matches hostnames with status |
π§ Context Introduction
When managing infrastructure, you often need to perform the same action across multiple serversβwhether it's checking their status, deploying updates, or gathering logs. Instead of writing repetitive code for each server, you can use a for loop to iterate over a list of hostnames and execute the same logic for each one. This makes your scripts cleaner, more scalable, and easier to maintain.
βοΈ What We're Building
We'll create a simple script that loops through a list of server hostnames and prints a status message for each one. This is a foundational pattern you'll use again and again in automation tasks.
π οΈ Step-by-Step Breakdown
1. Define a List of Hostnames
Start by storing your server hostnames in a Python list. Each hostname is a string enclosed in quotes, separated by commas.
- Example list: server_hostnames = ["web-01", "db-01", "cache-01", "app-01"]
2. Write the For Loop
Use the for keyword followed by a variable name (like host) and the in keyword to iterate over the list.
- Structure: for host in server_hostnames:
3. Add the Action Inside the Loop
Indent the code you want to run for each hostname. This is the body of the loop.
- Action: print(f"Checking status of {host}...")
4. Run the Script
When executed, the loop will run once for every hostname in the list, printing a message for each.
- Expected output:
- Checking status of web-01...
- Checking status of db-01...
- Checking status of cache-01...
- Checking status of app-01...
π Comparison: Without Loop vs. With Loop
| Approach | Code Example | Scalability |
|---|---|---|
| Without Loop | print("Checking status of web-01...") print("Checking status of db-01...") print("Checking status of cache-01...") print("Checking status of app-01...") |
Poor β you must manually add or remove lines for each server |
| With Loop | for host in server_hostnames: print(f"Checking status of {host}...") |
Excellent β just update the list, and the loop handles the rest |
π΅οΈ Key Takeaways
- A for loop lets you repeat an action for every item in a list without writing duplicate code.
- The loop variable (e.g., host) takes the value of each list item one at a time.
- Indentation is critical in Pythonβeverything inside the loop must be indented consistently.
- This pattern works for any list: IP addresses, environment names, region codes, or even file paths.
π Next Steps
Once you're comfortable with this basic example, try expanding it:
- Add an if condition inside the loop to skip certain hostnames.
- Use a dictionary to store hostnames along with their IP addresses.
- Replace the print statement with a function call that actually pings or connects to each server.
Mastering the for loop with lists is a huge step toward writing real-world automation scripts.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
This section shows how to use a for loop to process a list of server hostnames, a common task for engineers managing multiple machines.
π₯οΈ Example 1: Printing Each Hostname
This example prints each server hostname from a list, one at a time.
servers = ["web01", "db01", "app01"]
for hostname in servers:
print(hostname)
π€ Output: web01 db01 app01
π’ Example 2: Adding a Number to Each Hostname
This example appends a sequential number to each hostname to create unique identifiers.
servers = ["web", "db", "app"]
for i in range(1, 4):
hostname = servers[i-1] + str(i)
print(hostname)
π€ Output: web1 db1 app1
π Example 3: Building Full Domain Names
This example constructs a full domain name for each server by adding a common suffix.
servers = ["web01", "db01", "app01"]
domain = ".example.com"
for hostname in servers:
full_name = hostname + domain
print(full_name)
π€ Output: web01.example.com db01.example.com app01.example.com
π‘ Example 4: Checking Hostname Length
This example checks if each hostname is longer than 4 characters and prints a message.
servers = ["web01", "db01", "app01", "mon"]
for hostname in servers:
if len(hostname) > 4:
print(hostname + " is long")
else:
print(hostname + " is short")
π€ Output: web01 is long db01 is long app01 is long mon is short
π Example 5: Pinging Multiple Servers (Simulated)
This example simulates pinging each server and prints a status message.
servers = ["web01", "db01", "app01"]
status = ["up", "up", "down"]
for i in range(len(servers)):
hostname = servers[i]
current_status = status[i]
print("Pinging " + hostname + "... Status: " + current_status)
π€ Output: Pinging web01... Status: up Pinging db01... Status: up Pinging app01... Status: down
π Comparison Table: Loop Variations
| Example | Loop Type | What It Does |
|---|---|---|
| 1 | for item in list | Prints each hostname directly |
| 2 | for i in range() | Adds numbers to hostnames |
| 3 | for item in list | Builds full domain names |
| 4 | for item in list | Checks hostname length |
| 5 | for i in range() | Matches hostnames with status |