Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change cloudbase-init script runner user #159

Open
PrashantRaj18198 opened this issue Nov 6, 2024 · 3 comments
Open

Change cloudbase-init script runner user #159

PrashantRaj18198 opened this issue Nov 6, 2024 · 3 comments

Comments

@PrashantRaj18198
Copy link

Hi,

I'm trying to setup cloudbase init with windows 2022 using packer for azure. I was able to do so, but I need to change the cloudbase init executor user. From my understanding, this is the user that runs the userdata script that I add. Also, can I setup a password for this user?

Additional context for what I'm trying to do:
I want to configure a windows service to be run via this user. I'm not able to configure the service to be run via a local user. It says 'log on as service' is required (which is setup using the same cloudbase init script).

@ader1990
Copy link
Member

ader1990 commented Nov 6, 2024

Hello,

Can you give more details on what you are trying to achieve by sharing maybe the cloudbase-init config files and how you did install the MSI?

If you have userdata that creates a service and a user to run that service, you can do it via powershell, including the user right 'Log on as a service'.

Thanks.

@ader1990
Copy link
Member

ader1990 commented Nov 6, 2024

@PrashantRaj18198
Copy link
Author

I'm installing cloudbase init using the github release msi files.

function Install-CloudbaseInit {
    Param(
        [Parameter(Mandatory=$false)]
        [string]$Version="1.1.4",
        [Parameter(Mandatory=$false)]
        [string]$Arch="x64"
    )
    Write-Output "Downloading cloudbase-init"

    $cbslInitInstallerPath = Join-Path $env:TEMP "CloudbaseInitSetup_x64.msi"
    Start-FileDownload `
        -URL "https://github.com/cloudbase/cloudbase-init/releases/download/${Version}/CloudbaseInitSetup_$($Version -replace '\.', '_')_${Arch}.msi" `
        -Destination $cbslInitInstallerPath

    Write-Output "Installing cloudbase-init"
    $p = Start-Process -Wait -PassThru -FilePath "msiexec.exe" -ArgumentList @("/i", $cbslInitInstallerPath, "/qn")
    if ($p.ExitCode -ne 0) {
        Throw "Failed to install cloudbase-init"
    }
}

function Invoke-CloudbaseInitSetupComplete {
    Write-Output "Running cloudbase-init SetSetupComplete.cmd"
    $setupCompleteScript = Join-Path $env:windir "Setup\Scripts\SetupComplete.cmd"
    if(Test-Path $setupCompleteScript) {
        Remove-Item -Force $setupCompleteScript
    }
    & "$env:ProgramFiles\Cloudbase Solutions\Cloudbase-Init\bin\SetSetupComplete.cmd"
    if ($LASTEXITCODE) {
        Throw "Failed to run Cloudbase-Init\bin\SetSetupComplete.cmd"
    }
}

I call the Install-CloudbaseInit and then copy the cloudbase-init conf files
filename -> cloudbase-init-unattended.conf

[DEFAULT]
username=Admin
groups=Administrators
inject_user_password=true
first_logon_behaviour=no
config_drive_raw_hhd=true
config_drive_cdrom=true
config_drive_vfat=true
bsdtar_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\bsdtar.exe
mtools_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\
verbose=true
debug=true
logdir=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\log\
logfile=cloudbase-init-unattend.log
default_log_levels=comtypes=INFO,suds=INFO,iso8601=WARN,requests=WARN
logging_serial_port_settings=COM1,115200,N,8
mtu_use_dhcp_config=true
ntp_use_dhcp_config=true
local_scripts_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\LocalScripts\
metadata_services=cloudbaseinit.metadata.services.azureservice.AzureService
plugins=cloudbaseinit.plugins.windows.createuser.CreateUserPlugin,cloudbaseinit.plugins.common.setuserpassword.SetUserPasswordPlugin,cloudbaseinit.plugins.common.sethostname.SetHostNamePlugin,cloudbaseinit.plugins.common.userdata.UserDataPlugin
allow_reboot=true
stop_service_on_exit=false
check_latest_version=false

filename = cloudbase-init.conf

[DEFAULT]
username=Admin
groups=Administrators
inject_user_password=true
config_drive_raw_hhd=true
config_drive_cdrom=true
config_drive_vfat=true

bsdtar_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\bsdtar.exe
mtools_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\
verbose=true
debug=true
logdir=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\log\
logfile=cloudbase-init.log
default_log_levels=comtypes=INFO,suds=INFO,iso8601=WARN,requests=WARN
logging_serial_port_settings=COM2,115200,N,8
mtu_use_dhcp_config=true
ntp_use_dhcp_config=true
local_scripts_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\LocalScripts\

first_logon_behaviour=no
san_policy=OnlineAll
trim_enabled=True

metadata_report_provisioning_started=True
metadata_report_provisioning_completed=True
ephemeral_disk_volume_label="Temporary Storage"
netbios_host_name_compatibility=True

metadata_services=cloudbaseinit.metadata.services.azureservice.AzureService
plugins=cloudbaseinit.plugins.windows.rdp.RDPPostCertificateThumbprintPlugin,
        cloudbaseinit.plugins.windows.azureguestagent.AzureGuestAgentPlugin,
        cloudbaseinit.plugins.common.ephemeraldisk.EphemeralDiskPlugin,
        cloudbaseinit.plugins.common.trim.TrimConfigPlugin,
        cloudbaseinit.plugins.windows.sanpolicy.SANPolicyPlugin,
        cloudbaseinit.plugins.common.mtu.MTUPlugin,
        cloudbaseinit.plugins.windows.ntpclient.NTPClientPlugin,
        cloudbaseinit.plugins.common.sethostname.SetHostNamePlugin,
        cloudbaseinit.plugins.windows.createuser.CreateUserPlugin,
        cloudbaseinit.plugins.common.networkconfig.NetworkConfigPlugin,
        cloudbaseinit.plugins.windows.licensing.WindowsLicensingPlugin,
        cloudbaseinit.plugins.common.sshpublickeys.SetUserSSHPublicKeysPlugin,
        cloudbaseinit.plugins.windows.extendvolumes.ExtendVolumesPlugin,
        cloudbaseinit.plugins.common.userdata.UserDataPlugin,
        cloudbaseinit.plugins.common.setuserpassword.SetUserPasswordPlugin,
        cloudbaseinit.plugins.windows.winrmlistener.ConfigWinRMListenerPlugin,
        cloudbaseinit.plugins.windows.winrmcertificateauth.ConfigWinRMCertificateAuthPlugin,
        cloudbaseinit.plugins.common.localscripts.LocalScriptsPlugin

The user is configured (created and given the logon as service) during the image creation flow itself via the following script.

# Create runneradmin user and add the user to relevant groups
Write-Host 'Create runneradmin user'
$MACHINE_USER = "runneradmin"
$MACHINE_PASSWORD = "<redacted>"
$Password = ConvertTo-SecureString $MACHINE_PASSWORD -AsPlainText -Force
New-LocalUser -Name $MACHINE_USER -Password $Password -FullName "Runner Admin" -Description "Runner admin user for CI/CD"
Add-LocalGroupMember -Group "Administrators" -Member $MACHINE_USER
Add-LocalGroupMember -Group "Users" -Member $MACHINE_USER

# Set runneradmin user to not require password change at next logon
Set-LocalUser -Name $MACHINE_USER -PasswordNeverExpires $true

# Enable auto-login for runneradmin user
Write-Host 'Enable auto-login for runneradmin user'
$RegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
Set-ItemProperty -Path $RegistryPath -Name "AutoAdminLogon" -Value "1"
Set-ItemProperty -Path $RegistryPath -Name "DefaultUsername" -Value $MACHINE_USER
Set-ItemProperty -Path $RegistryPath -Name "DefaultPassword" -Value $MACHINE_PASSWORD

# Disable UAC
Write-Host 'Disable UAC'
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value 0

# Enable PowerShell remoting
Write-Host 'Enable PowerShell remoting'
Enable-PSRemoting -Force

$UserName = $MACHINE_USER

Write-Host "UserName for service elevate access: $UserName"

# Define the path for the temporary policy file
$policyPath = "C:\temp\secpol.cfg"

# Ensure the temporary directory exists
if (-not (Test-Path -Path "C:\temp")) {
    New-Item -ItemType Directory -Path "C:\temp" | Out-Null
}

# Export the current security policy to a temporary file
secedit /export /cfg $policyPath

# Read the exported policy content
$content = Get-Content $policyPath

# Check if warpbuild is already in the SeServiceLogonRight policy
if ($content -match "SeServiceLogonRight = .*?($UserName)") {
    Write-Host "User $UserName already has 'Log on as a Service' permission."
} else {
    # Add the username to the "Log on as a service" policy (SeServiceLogonRight)
    $updatedContent = $content -replace "(SeServiceLogonRight = .*)", "`$1,$UserName"

    # Save the modified policy file
    $updatedContent | Set-Content $policyPath

    # Apply the modified policy non-interactively
    echo y | secedit /configure /db secedit.sdb /cfg $policyPath /overwrite

    # Force policy update
    gpupdate /force

    Write-Host "User $UserName has been granted the 'Log on as a Service' permission."
}

In the userdata section when I'm creating a vm from this image, the service bootup is failing saying the logon service is not avaiable. But logging into the machine using user ('prashant') and then trying to start the service works (service is configured with 'runneradmin').

This image setup is done via packer using azure-arm source.
filename -> packer.hcl

  provisioner "powershell" {
    elevated_password = "${var.install_password}"
    elevated_user     = "${var.install_user}"
    scripts = [
      "${path.root}/../scripts/build/Cloudbase-Init.Install.ps1"
    ]
  }

  provisioner "file" {
    source      = "${path.root}/../assets/cloudbase-init/conf/cloudbase-init-unattend.conf"
    destination = "C:\\Program Files\\Cloudbase Solutions\\Cloudbase-Init\\conf\\cloudbase-init-unattend.conf"
  }

  provisioner "file" {
    source      = "${path.root}/../assets/cloudbase-init/conf/cloudbase-init.conf"
    destination = "C:\\Program Files\\Cloudbase Solutions\\Cloudbase-Init\\conf\\cloudbase-init.conf"
  }

  provisioner "powershell" {
    elevated_password = "${var.install_password}"
    elevated_user     = "${var.install_user}"
    scripts = [
      "${path.root}/../scripts/build/Cloudbase-Init.Run-SetupComplete.ps1"
    ]
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants