Issue
I am trying to add Linux machines to ansible host file with automation script. Automation process is;
1- Ansible machine gets Linux vm list which named LinuxVms.txt from one of Vmware server.
2- I developed sh file below. It adds servers into the "[all_linux_host]" tag ,from LinuxVms.txt file. And sh works. (One time operation)
after this process, what I want to do is;
Vmteam will automatically send the LinuxVm.txt list to the ansible server and If the LinuxVm.txt file has new IP address I need to add this IP address to the ansible hosts file, under the "[all_linux_host]" tag.
I am thinking that the,for loop should be work for this. For loop has to control new arrived LinuxVm.txt file and only [all_linux_host] tag (not all tags in ansible host file) if there is a differences between file and tag it has to find that differences and add to the "[all_linux_host]" tag.
For example LinuxVms.txt
1.1.1.1
2.2.2.2
3.3.3.3
12.12.12.12
current, ansible host file
/etc/ansible/hosts.
[test]
8.8.8.8
12.12.12.12
13.13.13.13
[all_linux_hosts] ## this is the last tag in ansible host file..
1.1.1.1
2.2.2.2
after for loop, ansible host file has to be like this
[test]
8.8.8.8
12.12.12.12
13.13.13.13
[all_linux_hosts] ## IP address order is not import.
1.1.1.1
2.2.2.2
3.3.3.3
12.12.12.12
Can you help me to develop for loop?
One time operation
sudo cp /home/vmteam/LinuxVMs.txt /home/xxx
sudo chown xxx: /home/vmteam/LinuxVMs.txt
sudo dos2unix /home/xxx/LinuxVMs.txt
awk '{print $1}' /home/xxx/LinuxVMs.txt >> ansible_host_file ##file correction
awk '{print $2}' /home/xxx/LinuxVMs.txt >> ansible_host_file ##file correction
sed -i 's/PublicIp//g' /home/xxx/ansible_host_file
sed -i 's/-//g' /home/xxx/ansible_host_file
sed -i '/^\s*$/d' /home/xxx/ansible_host_file
sed -i 's/IpAddress1/ /g' /home/xxx/ansible_host_file
sed -i '/^\s*$/d' /home/xxx/ansible_host_file```
Solution
One way with awk is as given here.
awk '
NR==FNR {a[$1];next}
$1=="[all_linux_hosts]" {f=1}
f && ( $1 in a ) { delete a[$1] }
{print}
END {
for (host in a) print host
}
' LinuxVms.txt /etc/ansible/hosts
[test]
8.8.8.8
12.12.12.12
13.13.13.13
[all_linux_hosts]
1.1.1.1
2.2.2.2
12.12.12.12
3.3.3.3
Answered By - guest_7