通过Automation批量更新密码
原创
©著作权归作者所有:来自51CTO博客作者mxy00000的原创作品,请联系作者获取转载授权,否则将追究法律责任
Azure Automation 算是个比较老的产品了,也属于Azure上做自动化运维的一种工具,虽然没有Ansible或者类似产品那么强,但是执行一些基础的操作,解决常见的运维问题还是很容易的,比如说如何批量维护环境内的账号密码,这个就属于比较典型的问题,一种方案是通过编写各种shell或者ps脚本来做,但其实用Azure Automation也非常方便
我们可以用Automation来批量执行runcommand或者custom extension,这些都可以批量执行一些脚本或者命令,password我们也可以存储在key vault里,这样相对安全些,不过我还没查过run command的log在平台上或者虚机内部是不是可以看到具体的执行命令记录,如果是的话,那是可以直接看到password的,所以还是不要在生产环境直接用比较好
大概的思路有了,具体到执行其实就比较简单了
先把Azure Automation Account准备好,现在的automation account用的都是managed identity了,注意在需要的范围内给automation account对应的identity assign好权限,在identity这里是可以清楚看到的
之后把key vault准备好,在key vault里要添加access policy来允许automation account读取secret,这里就要用到之前查到的identity的信息了,在添加权限的时候要知道automation account的名字或者id
之后在automation account里创建一个runbook即可
workflow password
{
Disable-AzContextAutosave -Scope Process
# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity -Environment AzureChinaCloud).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
Select-AzSubscription -SubscriptionId "xxxx";
$rgname ="xxxxx"
$VMS=get-azvm -ResourceGroupName $rgname
$secret = Get-AzKeyVaultSecret -VaultName "vaulttemp" -Name "nonprod" -AsPlainText
foreach ($vm in $vms) {
<# $currentItemName is the current item #>
write-output "setting password for $($vm.Name)"
Invoke-AzVMRunCommand -ResourceGroupName $rgname -Name $vm.Name -CommandId 'RunShellScript' -ScriptString "echo 'username:$secret' |chpasswd"
}
}
脚本的用途其实很简单,就是把某个resource group里的linux虚机密码都重置掉,可以看到log里的输出内容
大概内容就是这样,可以看出来整体步骤其实很简单,通过类似的思路其实还可以执行别的操作,还是比较方便的