Irina I
Irina I

Reputation: 33

Replace a text and IP address inside a file

I would like to write a script that reads a text file that has all the nodes listed in there:

node1 node2 node3 . . .

  1. It creates a .conf file for each node in the /etc/icinga2/zones.d/master/hosts/new/ directory

  2. Copies the content of the file name windows-template into each new conf file.

  3. Then finds the phrase "hostname.hostdomain.com" in each conf file and replaces that with the filename minus the .conf. So for example, for node1, I will have node1.conf in which there is a phrase "hostname.hostdomain.com" which needs to be replaced with node1

  4. Then pings the hostname which is technically the filename minus ".conf" and replaces the 10.20.20.1 with the correct hostname.

I tried wrirting the script and part 1 and 2 work, part 3 works too but it replaces the hostname.hostdomain.com with "$f" which is not right. And I have no clue how to do number 4.

Can you please help?

Thank you

This is my windows-template.conf file:

    object Host "hostname.hostdomain.com" {
    import "production-host"
    check_command = "hostalive"
    address = "10.20.20.1"
    vars.client_endpoint = name

    vars.disks["disk C:"] = {
      disk_partition = "C:"
    }

    vars.os = "Windows"
}

object Zone "hostname.hostdomain.com" {
    endpoints = [ "hostname.hostdomain.com" ];
    parent = "master";
}
object Endpoint "hostname.hostdomain.com" {
    host = "10.20.20.1"
}

And this is my script:

#!/bin/bash

cd /etc/icinga2/zones.d/master/hosts/new

while read f; do
   cp -v "$f" /etc/icinga2/zones.d/master/hosts/new/"$f.conf"
   cp windows-template.conf "$f.conf"
   chown icinga:icinga "$f.conf"
   sed -i 's/hostname.hostdomain.com/$f/g' "$f.conf"
#   git add "$f.conf"
#   git commit -m "Add $f"
done < windows-list.txt

Thank you

Upvotes: 1

Views: 311

Answers (2)

Matias Barrios
Matias Barrios

Reputation: 5056

Does this work for you?

#!/bin/bash

cd /etc/icinga2/zones.d/master/hosts/new

while read f; do
   cp -v "$f" /etc/icinga2/zones.d/master/hosts/new/"$f.conf"
   cp windows-template.conf "$f.conf"
   chown icinga:icinga "$f.conf"
   sed -i "s/hostname.hostdomain.com/$f/g" "$f.conf"
   hostname=$( ssh -o StrictHostKeyChecking=no  "username@$f" -n "hostname" )
   mv "$f.conf" "${hostname}.conf"
#   git add "$f.conf"
#   git commit -m "Add $f"
done < windows-list.txt

Where username is your username, and I assume you copy your pub key to the hosts.

Upvotes: 0

Sebastian Freitag
Sebastian Freitag

Reputation: 143

You need double quotes for the shell to expand your variable. Try

sed -i "s/hostname.hostdomain.com/$f/g" "$f.conf"

Upvotes: 2

Related Questions