Search code examples
linuxawksedcut

Manipulate AWK field variables ($1,$2,..) and add that to the end of line


I am trying to create /etc/host file from ansible inventory file.

Ansible inventory file looks like this:

[masters]
k8s-master-a.example.com ansible_ssh_host=10.15.90.2
k8s-master-b.example.com ansible_ssh_host=10.15.90.3
k8s-master-c.example.com ansible_ssh_host=10.15.90.4
[etcd]
k8s-etcd-a.example.com ansible_ssh_host=10.15.91.2
k8s-etcd-b.example.com ansible_ssh_host=10.15.91.3
k8s-etcd-c.example.com ansible_ssh_host=10.15.91.4

The following script will help to create it with fqdn entry.

$cat inventory.yaml | grep -v '^\[' | sed 's/ansible_ssh_host=//g' | awk '{ print $2 " " $1}' > /etc/hosts
10.15.90.2 k8s-master-a.example.com  
10.15.90.3 k8s-master-b.example.com  
10.15.90.4 k8s-master-c.example.com  
10.15.91.2 k8s-etcd-a.example.com 
10.15.91.3 k8s-etcd-b.example.com 
10.15.91.4 k8s-etcd-c.example.com 

But I want to have k8s-master-* and k8s-etcd-* aslo in the /etc/hosts file. The final result should look like this.

10.15.90.2 k8s-master-a.example.com k8s-master-a
10.15.90.3 k8s-master-b.example.com k8s-master-b
10.15.90.4 k8s-master-c.example.com k8s-master-c
10.15.91.2 k8s-etcd-a.example.com k8s-etcd-a
10.15.91.3 k8s-etcd-b.example.com k8s-etcd-b
10.15.91.4 k8s-etcd-c.example.com k8s-etcd-c


Solution

  • AWK solution:

    awk -F'[ =]' '/^[^\[]/ { if (match($1,/\./)) print($NF " " $1 " " substr($1,0,RSTART-1)); }'
    

    Test:

    $ awk -F'[ =]' '/^[^\[]/ { if (match($1,/\./)) print($NF " " $1 " " substr($1,0,RSTART-1)); }' inventory.yaml
    10.15.90.2 k8s-master-a.example.com k8s-master-a
    10.15.90.3 k8s-master-b.example.com k8s-master-b
    10.15.90.4 k8s-master-c.example.com k8s-master-c
    10.15.91.2 k8s-etcd-a.example.com k8s-etcd-a
    10.15.91.3 k8s-etcd-b.example.com k8s-etcd-b
    10.15.91.4 k8s-etcd-c.example.com k8s-etcd-c