所以,我試圖編寫腳本在Rackspace Cloud上創建服務器。我已經能夠讓腳本成功創建一個服務器。雖然在創建服務器之後,我需要從輸出中獲取幾條數據,並將它們存儲在一個變量中,以便以後在同一個腳本中使用(在創建後將在新服務器上執行一些操作)。Bash存儲輸出變量,解析並存儲一些值供以後使用
這裏是我使用創建服務器腳本:
#!/bin/bash
# Ask user to continue or not
read -p "You are about to setup a new Rackspace cloud server. Would you like to continue (y/n)? " cont
if [ "$cont" == "y" ]; then
echo "Starting server setup script..."
# Ask questions to get login creds
read -p "Rackspace Username? " username
read -p "Rackspace API Key? " apikey
# Get Rackspace token
echo "Getting token..."
token=$(curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens \
-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"'"$username"'", "apiKey":"'"$apikey"'" } } }' \
-H "Content-type: application/json" \
| python -m json.tool \
| python -c 'import sys, json; print json.load(sys.stdin)["access"]["token"]["id"]')
echo "...done!"
# Get Rackspace account id
echo "Getting account id..."
account=$(curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens \
-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"'"$username"'", "apiKey":"'"$apikey"'" } } }' \
-H "Content-type: application/json" \
| python -m json.tool \
| python -c 'import sys, json; print json.load(sys.stdin)["access"]["token"]["tenant"]["id"]')
echo "...done!"
# Create a new Rackspace cloud server
echo "Creating a new Rackspace cloud server..."
serverpassword=$(curl -s -X POST https://dfw.servers.api.rackspacecloud.com/v2/$account/servers \
-H "Content-Type: application/json" \
-H "X-Auth-Token: $token" \
-H "X-Auth-Project-Id: test-project" \
-T server_build.json \
| python -m json.tool \
| python -c 'import sys, json; print json.load(sys.stdin)["server"]["adminPass"]')
echo "...done!"
echo "Your new server has been created!"
read -p "Would you like to continue on to setting up your new server (y/n)? " cont2
if [ "$cont2" == "y" ]; then
exit
else
echo "Here is your root password for this server (you must write this down now): $serverpassword"
exit
fi
else
echo "You have chosen not to setup a new Rackspace server."
exit
fi
你可以看到,權杖和帳戶變量被設置,並在創建curl命令使用。最後curl命令的輸出是這樣的:(去掉實際值)
{
"server": {
"OS-DCF:diskConfig": "AUTO",
"adminPass": "************",
"id": "************",
"links": [
{
"href": "https://dfw.servers.api.rackspacecloud.com/v2/...",
"rel": "self"
},
{
"href": "https://dfw.servers.api.rackspacecloud.com/...",
"rel": "bookmark"
}
]
}
}
我希望能夠既adminPass
和id
存儲在兩個不同的變量。我怎樣才能做到這一點?我也知道通過解決這個問題,我將能夠通過使用一個curl命令而不是兩個不同的值來獲得token
和account
值時重構腳本。
感謝您的幫助!
從提示讀取'adminpass'和'id'嗎? – MLSC
我的問題可能是措辭錯誤。 'adminPass'和'id'是curl命令輸出中的值。我只是在描述他們,因爲我不想在這裏發佈信息。我想要做的就是獲取該輸出並將這兩個值存儲在兩個單獨的變量中。類似於'python -c'import sys,json;打印json.load(sys.stdin)[「access」] [「token」] [「id」]''獲得上述'token'的行。那有意義嗎? – ryanpitts1
是的,謝謝你... – MLSC