温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-06 20:17:54 来源:网络 阅读:1870 作者:mxy00000 栏目:云计算

    前段时间写了个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进行登录了!

$ApplicationID="a67aa2ff-f009-4ec9-93fa-c773aa1442ec"
$Password="******"
$TenantID="b7283bff-0d3d-4728-9189-8513ee70744a"
$Password=ConvertTo-SecureString $Password -AsPlainText -Force
$Credential=New-Object System.Management.Automation.PSCredential($ApplicationID,$Password)
Add-AzAccount -Credential $Credential -ServicePrincipal -TenantId $TenantID -EnvironmentName azurechinacloud


登录成功!可以愉快地跑脚本了

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



不得不说,真的是挺方便的,微软这个操作必须得赞一个


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI