2017-04-04 66 views
0

想寫AWS雲的形成腳本安全組內更換,這個過程太很重複我嘗試了一些黑客將其自動化搜索和從輸出到匹配模式的文件

我有CSV輸出從下面的調用awksed

awk -F, 'NR > 1 { OFS=",";print $2, $3, $4, $5 }' para.csv | sed -n 1p 

輸出:

10.0.0.0/8,tcp,53,53 

我需要這個輸出映射到FIL Ë其具有以下

"ingress5": { 
     "Type": "AWS::EC2::SecurityGroupIngress", 
     "Properties": { 
     "GroupId": { 
      "Ref": "sginformatica" 
     }, 
     "IpProtocol": "", 
     "FromPort": "", 
     "ToPort": "", 
     "CidrIp": "" 
     } 
}, 

即,從命令IpProtocol的輸出應該被映射到tcp

FromPort應映射53(第3列,或在輸出字段3)

ToPort應映射53(第4列,或在輸出字段4)

CidrIp應該被映射到10.0.0.0/8(場輸出的1)

回答

1
#!/bin/bash 

while IFS="," read -r CidrIp IpProtocol FromPort ToPort; do 
cat << EOF 
"ingress5": { 
     "Type": "AWS::EC2::SecurityGroupIngress", 
     "Properties": { 
     "GroupId": { 
      "Ref": "sginformatica" 
     }, 
     "IpProtocol": "$IpProtocol", 
     "FromPort": "$FromPort", 
     "ToPort": "$ToPort", 
     "CidrIp": "$CidrIp" 
     } 
}, 
EOF 
done < file 

利用該文件:

 
10.0.0.0/8,tcp,53,53 

輸出:

 
"ingress5": { 
     "Type": "AWS::EC2::SecurityGroupIngress", 
     "Properties": { 
     "GroupId": { 
      "Ref": "sginformatica" 
     }, 
     "IpProtocol": "tcp", 
     "FromPort": "53", 
     "ToPort": "53", 
     "CidrIp": "10.0.0.0/8" 
     } 
}, 

或沒有文件:

awk -F, 'NR > 1 { OFS=",";print $2, $3, $4, $5 }' para.csv | sed -n 1p | while ...; do ...; done 
1

安裝和使用靈活的命令行JSON處理器 - jq

比方說,我們有ingress.json文件內容:

{ 
    "ingress5": { 
     "Type": "AWS::EC2::SecurityGroupIngress", 
     "Properties": { 
     "GroupId": { 
      "Ref": "sginformatica" 
     }, 
     "IpProtocol": "", 
     "FromPort": "", 
     "ToPort": "", 
     "CidrIp": "" 
     } 
    } 
} 

起初,我們會調整的關鍵輸入字符串看作是一個有效的JSON字符串:

v="["$(awk -F, '{ OFS=",";print "\042"$2"\042", "\042"$3"\042", $4, $5 }' para.csv | sed -n 1p)"]" 
echo $v 
["10.0.0.0/8","tcp",53,53] 

下一步是修改使用JQ命令所需的屬性值:

jq --argjson v "$v" '.ingress5.Properties.IpProtocol = $v[1] | .ingress5.Properties.FromPort = $v[2] 
    | .ingress5.Properties.ToPort = $v[3] | .ingress5.Properties.CidrIp = $v[0]' ingress.json 

輸出:

{ 
    "ingress5": { 
    "Type": "AWS::EC2::SecurityGroupIngress", 
    "Properties": { 
     "GroupId": { 
     "Ref": "sginformatica" 
     }, 
     "IpProtocol": "tcp", 
     "FromPort": 53, 
     "ToPort": 53, 
     "CidrIp": "10.0.0.0/8" 
    } 
    } 
} 
+0

會試一下jq one –

+0

@SaravananD,所以試試 – RomanPerekhrest

相關問題