Score:0

How to change SQL Server sa password as part of ec2 userdata

cn flag

I'm provisioning some development EC2 instances running Windows Server, with SQL Server installed. I use a custom Amazon Machine Image with the configuration we need, but as part of the provisioning process, I run a userData script on each machine that sets some values specific to that user, including a random password for certain applications. Part of the script does this for SQL Server, following this example:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" localhost
$user = $srv.Logins | where Name -eq "sa"
$user.ChangePassword("<injected by provisioning process>");
$user.PasswordPolicyEnforced = 1;
$user.Alter();
$user.Refresh();

The weird thing is that when I run this manually on the box after it's spun up, it works. However, when I have it as part of the user data, it doesn't appear to have any effect -- you can't authenticate to the database with the new password. I know for certain that the full user data script is running without error. Other components before and after this code block are working as expected. Furthermore, I can see the DateLastModified attribute of the sa user reflects when the script ran.

Why would this behave any differently running in the user data script vs. me doing it manually in powershell?

(Yes, I'm aware this is not good practice, so to speak. These machines are not used for production: they're spun up temporarily, firewalled, and only used to test specific workflows)

Score:1
cn flag

Well, turns out this was not the right approach, possibly because my userData script was not being run as Administrator. Instead, I found this to be successful:

net stop mssqlserver
net start mssqlserver /m
SQLCMD -E -Q "ALTER LOGIN [sa] WITH DEFAULT_DATABASE=[master]; USE [master]; ALTER LOGIN [sa] WITH PASSWORD=N'<injected by provisioning process>'"
net stop mssqlserver
net start mssqlserver
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.