天天看點

真正跨平台!在Linux上跑Azure PowerShell腳本

    前段時間寫了個PowerShell腳本給同僚,換來的卻是同僚的白眼,意思是說我這都是linux,你給我寫個powershell的腳本我去哪跑去,我真想回個白眼,馬上都0202年了,還以為powershell隻能在windows上跑呢,PowerShell開源,PowerShell Core出世都已經很長時間了,但是仍然有人天真的以為PowerShell隻适用Windows平台,事實上,從PowerShell Core開始,PowerShell腳本已經可以直接跑在各大Linux平台上了!!而且體驗基本真的是無縫移植!!很多腳本一個字母都不需要改!

    拿Azure的腳本來說,我們就來看下怎麼在Linux上把PowerShell玩起來

    首先,我們需要把PowerShell裝上,首先把repo的資訊準備好

    curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo

真正跨平台!在Linux上跑Azure PowerShell腳本

    之後直接yum install安裝,linux下安裝确實是友善,而且速度很快

    sudo yum install -y powershell

真正跨平台!在Linux上跑Azure PowerShell腳本

    直接輸入Pwsh進入PowerShell

真正跨平台!在Linux上跑Azure PowerShell腳本

    接下來就可以安裝Azure的module了,注意linux下我們要安裝最新的az module,也可以試下其他指令,文法和windows下的powershell基本沒有差別

真正跨平台!在Linux上跑Azure PowerShell腳本
真正跨平台!在Linux上跑Azure PowerShell腳本

    接下來我們來看下怎麼登陸Azure,和windows一樣,直接用login-azaccount就能登陸了,但是差別在于,因為沒有圖形化界面,是以需要用code登陸,和CLI感覺差不多

真正跨平台!在Linux上跑Azure PowerShell腳本

    在浏覽器裡輸入對應的code

真正跨平台!在Linux上跑Azure PowerShell腳本

    可以看到已經能夠get到賬戶裡的資訊了!

真正跨平台!在Linux上跑Azure PowerShell腳本

    另外有個問題需要說下,如果想運作一些定時的腳本,身份認證這塊,PowerShell core并不支援直接用使用者名密碼登陸,是以這裡我們要不就用剛才看到的code的方式來實作互動式登入,要不就用service principal進行登入

真正跨平台!在Linux上跑Azure PowerShell腳本

    service principal的介紹之前已經講過了,這裡不再贅述,建立service principal的方法也比較簡單,用PowerShell就可以建立了,如果想給service principal加個密碼,可以在Portal上找到Service Principal,點選添加secret

真正跨平台!在Linux上跑Azure PowerShell腳本

    secret可以設定過期的時間

真正跨平台!在Linux上跑Azure PowerShell腳本

    把value儲存下來,注意不儲存的話以後就找不到了,是以注意一定要儲存

真正跨平台!在Linux上跑Azure PowerShell腳本

接下來就可以用這個secret進行登入了!

登入成功!可以愉快地跑腳本了

真正跨平台!在Linux上跑Azure PowerShell腳本

不得不說,真的是挺友善的,微軟這個操作必須得贊一個

繼續閱讀