我正在尝试从ansible库存文件创建/ etc / host文件。
可用库存文件如下:
[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
以下脚本将帮助使用fqdn条目创建它。
$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
但是我想在/ etc / hosts文件中包含k8s-master- *和k8s-etcd- * aslo。最终结果应如下所示。
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
答案 0 :(得分:2)
您只需要awk
。这样就可以了:
cat inventory.yaml
[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
awk -F'[[:space:]=]' '/^[^[]/ {split($1, tokens, /[.]/); print $3, $1, tokens[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
答案 1 :(得分:1)
AWK解决方案:
awk -F'[ =]' '/^[^\[]/ { if (match($1,/\./)) print($NF " " $1 " " substr($1,0,RSTART-1)); }'
测试:
$ 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
答案 2 :(得分:0)
如果“ d”文件中的数据,请在gnu awk上尝试:
def setDistinctElements(self, result):
elements = []
for chunk in getattr(result, 'chunks'):
for pr in getattr(chunk, 'prs'):
for seg in getattr(pRaid, 'segs'):
elements.append(getattr(seg, 'node_id'))
答案 3 :(得分:0)
$ awk -F'[=[:space:]]+' 'split($1,f,/[.]/)>1{print $NF, $1, f[1]}' file
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