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

Cloudbase-init localscript exitcode 1003 won't restart when converting Windows Server 2019 to a DomainController #100

Open
Ks89 opened this issue Aug 29, 2022 · 11 comments

Comments

@Ks89
Copy link

Ks89 commented Aug 29, 2022

I'm stucked with this error since May 2022 and I didn't find any solution.
I also opened a discussion here ask.cloudbase.

It happens only with Windows Server 2019

I tried these configurations:

  • windows server 2019 from official trial iso without any updates + Cloudbase-init 1.1.3dev16
  • windows server 2019 from official trial iso without any updates + Cloudbase-init 1.1.2
  • windows server 2019 from official trial iso WITH ALL updates + Cloudbase-init 1.1.3dev16

I sysprepped all of these configurations and used a Powershell script (via local scripts) to convert the OS into a DomainController.

In my powershell script I install required features:

Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
Install-WindowsFeature RSAT-AD-Tools -IncludeManagementTools
exit 1003

This part of the script works as expected!

Then I create the forest and reboot again with exit 1003:

 $secureSafeModePassword=(ConvertTo-SecureString "SafePass1!" -AsPlainText -Force)
 Import-Module ADDSDeployment
 Install-ADDSForest `
  -CreateDnsDelegation:$false `
  -DatabasePath "C:\Windows\NTDS" `
  -DomainMode "Win2012R2" `
  -DomainName "testdomain.corp" `
  -DomainNetbiosName "TESTDOMAIN" `
  -ForestMode "Win2012R2" `
  -InstallDns:$true `
  -LogPath "C:\Windows\NTDS" `
  -NoRebootOnCompletion:$true `
  -SysvolPath "C:\Windows\SYSVOL" `
  -SafeModeAdministratorPassword $secureSafeModePassword `
  -Force:$true

  Restart-Computer -Force
  exit 1003

But this time, cloudbase-init returns an error as shown in log file:

INFO cloudbaseinit.init [-] Rebooting
ERROR cloudbaseinit.init [-] reboot failed with error 'Reboot failed: ''Arresto del sistema già pianificato.'': cloudbaseinit.exception.WindowsCloudbaseInitException: Reboot failed: 'Arresto del sistema già pianificato.'
INFO cloudbaseinit.init [-] Process execution ended with exit code: 0

The Italian message says "System shutdown already planned".

Do you have any suggestion? Feel free to ask for more information, because I can reproduce this problem very easily.
The problem is that I cannot convert Windows Server 2019 into a domain controller with Cloudbase-Init. This error happens EVERY TIME. I think that this is a big problem, because it makes cloudbase-init broken on Windows Server 2019 to create a Domain controller.

Is there a workaround? Thank you.

@Ks89
Copy link
Author

Ks89 commented Sep 1, 2022

I made many experiments and these are the results:

I created all windows-server images installing dependencies with:

Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
Install-WindowsFeature RSAT-AD-Tools -IncludeManagementTools

and Cloudbase-init 1.1.2 64 bit.
Then I sysprepped the images.

What I want to do is converting my windows-server into a domain controller.
Since cloudbase-init can run a powershell script, I'm doing this process via "localscripts" with a "ps1" file.

The idea is this one (not the real script, but a simplified version):

# Step 1) convert into a domain controller
   
Import-Module ADDSDeployment
Install-ADDSForest `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-DomainMode "$domainMode" `
-DomainName "$fullDomainName" `
-DomainNetbiosName "$shortDomainName" `
-ForestMode "$forestMode" `
-InstallDns:$true `
-LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$true `                            # <- to block the shutdown
-SysvolPath "C:\Windows\SYSVOL" `
-SafeModeAdministratorPassword $secureSafeModePassword `
-Force:$true

exit 1003
  
# Step 2) add users

New-ADUser `
-Name "$name" `
-GivenName "$givenName" `
-Surname "$surname" `
-SamAccountName "$samName" `
-UserPrincipalName "$userPrincipalname" `
-AccountPassword $secureUserPassword `
-Enabled $true

exit 1003

# Step 4)
    # done, localscript should end here, because I'm not exiting with 1003

I tested this script on these versions:

  • windows server 2012 R2 with Cloudbase-init 1.1.2 stable 64 bit
  • windows server 2016 with Cloudbase-init 1.1.2 stable 64 bit
  • windows server 2019 with Cloudbase-init 1.1.2 stable 64 bit
  • windows server 2022 with Cloudbase-init 1.1.2 stable 64 bit

What I expect is that after every step, windows will reboot, because there is exit 1003 as return code. This should terminate the script and trigger Cloudbase-init to reboot the system,

However the behaviour is not consistent across windows-server versions.
These are the results:

  • windows server 2012 R2 with Cloudbase-init 1.1.2 => IT WORKS PERFECTLY
  • windows server 2016 with Cloudbase-init 1.1.2 => IT WORKS PERFECTLY
  • windows server 2019 with Cloudbase-init 1.1.2 => WON'T REBOOT AT exit 1003 at the end of Step 1)
  • windows server 2022 with Cloudbase-init 1.1.2 => IT WORKS PERFECTLY

So, to understand why Cloudbase-init is not rebooting the system I added some logs into Cloudbase-init python source code.
Specifically I added some LOGS to these files:

  • plugins/common/execcmd.py
def get_plugin_return_value(ret_val):
    LOG.warning("get_plugin_return_value called with ret_val = %r", ret_val)

    plugin_status = base.PLUGIN_EXECUTION_DONE
    reboot = False
    LOG.warning("get_plugin_return_value plugin_status = %r", plugin_status)

    try:
        ret_val = int(ret_val)
        LOG.warning("get_plugin_return_value converted ret_val into an integer = %r", ret_val)
    except (ValueError, TypeError):
        ret_val = 0
        LOG.warning("get_plugin_return_value cannot convert ret_val into an integer, forced to 0")

    LOG.warning("get_plugin_return_value RET_START = %r", RET_START)
    LOG.warning("get_plugin_return_value RET_END = %r", RET_END)
    LOG.warning("get_plugin_return_value ret_val = %r", ret_val)

    if ret_val and RET_START <= ret_val <= RET_END:
        LOG.warning("get_plugin_return_value inside if to check for reboot with ret_val = %r", ret_val)
        reboot = bool(ret_val & 1)
        LOG.warning("get_plugin_return_value reboot = %r", reboot)
        if ret_val & 2:
            plugin_status = base.PLUGIN_EXECUTE_ON_NEXT_BOOT
            LOG.warning("get_plugin_return_value plugin_status forced to PLUGIN_EXECUTE_ON_NEXT_BOOT, so plugin_status = %r", plugin_status)

    LOG.warning("get_plugin_return_value returning plugin_status = %r, and reboot = %r", plugin_status, reboot)
    return plugin_status, reboot
  • osutils/windows.py
    def reboot(self):
        with privilege.acquire_privilege(win32security.SE_SHUTDOWN_NAME):
            ret_val = advapi32.InitiateSystemShutdownExW(
                0, "Cloudbase-Init reboot",
                0, True, True, 0)
            errno1 = ctypes.GetLastError()
            LOG.warning("1) InitiateSystemShutdownExW returned ret_val = %r", ret_val)
            LOG.warning("1) InitiateSystemShutdownExW result errno1 = %r", errno1)
            if not ret_val:
                raise exception.WindowsCloudbaseInitException(
                    "Reboot failed: %r")
  • init.py
    def configure_host(self):
        LOG.warning("configure_host called")

        service = None
        osutils = osutils_factory.get_os_utils()

        if CONF.reset_service_password and sys.platform == 'win32':
            self._reset_service_password_and_respawn(osutils)

        LOG.info('Cloudbase-Init version: %s', version.get_version())
        osutils.wait_for_boot_completion()

        stage_success, reboot_required = self._handle_plugins_stage(
            osutils, None, None,
            plugins_base.PLUGIN_STAGE_PRE_NETWORKING)

        LOG.warning("configure_host stage_success = %r", stage_success)
        LOG.warning("configure_host reboot_required = %r", reboot_required)
        LOG.warning("configure_host CONF.allow_reboot = %r", CONF.allow_reboot)

        self._check_latest_version()

        # (... source code omitted, but unchanged)

        if reboot_required and CONF.allow_reboot:
            LOG.warning("configure_host rebooting check in true")
            try:
                LOG.info("Rebooting")
                osutils.reboot()
                LOG.info("osutils.reboot() called without errors")
            except Exception as ex:
                LOG.error('reboot failed with error \'%s\'' % ex)
        else:
            LOG.info("Plugins execution done")

            if (service and CONF.metadata_report_provisioning_completed and
                    stage_success):
                try:
                    LOG.info("Reporting provisioning completed")
                    service.provisioning_completed()
                except Exception as ex:
                    LOG.exception(ex)

            if CONF.stop_service_on_exit:
                LOG.info("Stopping Cloudbase-Init service")
                osutils.terminate()

I didn't change any logic! I simply added some logs to print data in cloudbase-init.log.

The result for the broken version (windows server 2019) is:

2022-08-31 14:14:54.021 2120 INFO cloudbaseinit.plugins.common.fileexecutils [-] Script "D:\localscripts\powershell.ps1" ended with exit code: 1003
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value called with ret_val = 1003
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value plugin_status = 1
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value converted ret_val into an integer = 1003
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value RET_START = 1001
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value RET_END = 1003
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value ret_val = 1003
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value inside if to check for reboot with ret_val = 1003
2022-08-31 14:14:54.021 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value reboot = True
2022-08-31 14:14:54.036 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value plugin_status forced to PLUGIN_EXECUTE_ON_NEXT_BOOT, so plugin_status = 2
2022-08-31 14:14:54.036 2120 WARNING cloudbaseinit.plugins.common.execcmd [-] get_plugin_return_value returning plugin_status = 2, and reboot = True
2022-08-31 14:14:54.036 2120 DEBUG cloudbaseinit.metadata.services.baseconfigdrive [-] Deleting metadata folder: 'C:\\Users\\CLOUDB~1\\AppData\\Local\\Temp\\tmppcc5_xw8' cleanup C:\Program Files\Cloudbase Solutions\Cloudbase-Init\Python\lib\site-packages\cloudbaseinit\metadata\services\baseconfigdrive.py:91
2022-08-31 14:14:54.036 2120 WARNING cloudbaseinit.init [-] configure_host rebooting check in true
2022-08-31 14:14:54.036 2120 INFO cloudbaseinit.init [-] Rebooting
2022-08-31 14:14:54.036 2120 WARNING cloudbaseinit.osutils.windows [-] 1) InitiateSystemShutdownExW returned ret_val = 1
2022-08-31 14:14:54.036 2120 WARNING cloudbaseinit.osutils.windows [-] 1) InitiateSystemShutdownExW result errno1 = 0
2022-08-31 14:14:54.036 2120 INFO cloudbaseinit.init [-] osutils.reboot() called without errors
2022-08-31 14:14:54.083 3688 INFO cloudbaseinit.init [-] Process execution ended with exit code: 0

As you can see, Cloudbase-init do everything as expected without errors and it calls InitiateSystemShutdownExW with return code != 0 (so it's not and error) and its error cause is 0 (a success).
What I expect is that Windows-server should reboot, because Win32 API succeeded, but this isn't happening. Why?

This is the main reason of all issues, because every other attempt with workarounds to try to reboot the system in a forced way caused different errors (like the one described HERE about pending shutdown).

In fact, if I modify localscript adding a Restart-Computer -Force before every exit 1003 in this way:

Restart-Computer -Force
exit 1003  

It causes the errore described in the first post of this issue, because you are trying to restart the system, but also Cloudbase-init is trying to do the same thing. You can easily modify the reboot function of Cloudbase-init to cancel the shutdown and do another shutdown, however this doesn't solve the problem, because the issue is with InitiateSystemShutdownExW that for some reason is not able to reboot the system on windows-server 2019, after the Install-ADDSForest command.

Do you have suggestions/workarounds to fix this?

@Ks89
Copy link
Author

Ks89 commented Sep 1, 2022

The question is: "why running InitiateSystemShutdownExW after Install-ADDSForest won't work even if the result is a success?"
If I access to the VM, when blocked at the end of step 1, I can easily reboot the system manually, but not via InitiateSystemShutdownExW in cloudbase-init.

So

  • is it something about the user that is running the script/cloudbase?
  • is it something about timing? What happens with a delay before InitiateSystemShutdownExW (this doesn't make sense in my opinion, because InitiateSystemShutdownExW is a shutdown request, not a synchronous command)
  • ???? I'm really confused, please help :)

@Ks89
Copy link
Author

Ks89 commented Sep 1, 2022

Unbelievable, I fixed this problem installing Clodubase-Init 1.1.2 as LocalSystem (the checkbox available in the installer). Now it's working on windows-server-2019

@ader1990
Copy link
Member

ader1990 commented Sep 5, 2022

Unbelievable, I fixed this problem installing Clodubase-Init 1.1.2 as LocalSystem (the checkbox available in the installer). Now it's working on windows-server-2019

Hello,

We have not seen this error so far with the initial testing of the feature a while back: https://github.com/openstack/heat-templates/blob/master/hot/Windows/ActiveDirectoryController/AD.psm1#L20

I am going to try to reproduce this error on a 2019 with latest updates and will try to raise the issue upstream, I think it s the flag that s not respected in the implementation.

Thank you,
Adrian.

@Ks89
Copy link
Author

Ks89 commented Sep 6, 2022

Hi!

I think it s the flag that s not respected in the implementation

Which flag? I'm curious :)

What does it means "LocalSystem"? Is it the "Admin/Administrator" account?

Thanks

@ader1990
Copy link
Member

ader1990 commented Sep 8, 2022

Hello,

We have tried to reproduce the issue, but seems that it works fine on Windows Server 2k19 Standard, latest updates, Build 17763.

Here is the exact script to install AD (example script with dummy passwords, please do not use in production):

#ps1
$ErrorActionPreference = "STOP"

$SafeModePwd = "Passw0rd"
$DomainName = "cbsl1.local"
$DomainNetbiosName = "cbsl1"

$defaultLocalAdministrator = "Administrator"

## Install tools
$adDSInstall = Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
$mgtmToolInstall = Install-WindowsFeature RSAT-AD-Tools -IncludeManagementTools

if (!($adDSInstall.Success -and $mgtmToolInstall.Success)) {
    throw "Failed to install AD-Domain-Services or RSAT-AD-Tools"
}

if ($adDSInstall.RestartNeeded -eq "Yes" -or $mgtmToolInstall.RestartNeeded -eq "Yes") {
    exit 1003
}


## Install AD
try {
    $adUser = Get-ADUser "Administrator" -ErrorAction SilentlyContinue
    if ($adUser) {
        exit 0
    }
} catch {
    Write-Host $_
}

$localAdministratorPath = "WinNT://./$defaultLocalAdministrator"
$user = [ADSI]$localAdministratorPath
$user.SetPassword($SafeModePwd)
Import-Module ADDSDeployment
$secureSafeModePwd = ConvertTo-SecureString $SafeModePwd -AsPlainText -Force
Install-ADDSForest -DomainName $DomainName `
    -DomainNetbiosName $DomainNetbiosName `
    -SafeModeAdministratorPassword $secureSafeModePwd `
    -InstallDns -NoRebootOnCompletion -Force

exit 1003

Note that the script has to be idempotent and to have finality in the sense of an exit 0 when all has been completed.

Thank you,
Adrian.

@Ks89
Copy link
Author

Ks89 commented Sep 8, 2022

Weird!

Yes, also my script is idempotent to do these steps sequentially across different reboots.

It's very similar to my script. The only difference is that I specify more parameters in ADDSForest:

Install-ADDSForest `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-DomainMode "$domainMode" `
-DomainName "$fullDomainName" `
-DomainNetbiosName "$shortDomainName" `
-ForestMode "$forestMode" `
-InstallDns:$true `
-LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$true `
-SysvolPath "C:\Windows\SYSVOL" `
-SafeModeAdministratorPassword $secureSafeModePassword `
-Force:$true

Also, I'm using your same version of Windows Server 2019 (connected to the internet) with Cloudbase 1.1.2 64bit with NoCloudConfigDriveService and these plugins:

  • SetHostNamePlugin
  • NetworkConfigPlugin
  • UserDataPlugin
  • LocalScriptsPlugin

I sysprepped the image with sysprep.exe /generalize /oobe /shutdown /unattend:Unattend.xml using the default Unattend.xml.

My config file contains:

username=Administrator
groups=Administrators
inject_user_password=true
first_logon_behaviour=no
...
allow_reboot=true
stop_service_on_exit=false
check_latest_version=false

But I don't think that this issue is related to the config of cloudbase-init.

What is the purpose of the flag "LocalSystem" in cloudbase-init? Is it a way to run it as Administrator instead of its specific user?
If I run InitiateSystemShutdownExW as Administrator when the system is blocked (after the previous error, when cloudbase is not able to reboot) I can easely reboot the system without issues. Is there a way to try to manually run InitiateSystemShutdownExW as cloudbaseinit user, instead of Administrator, to check if the problem is about permissions? Because, I saw this problem only when cloudbase executes InitiateSystemShutdownExW (without "LocalSystem" flag).

Or, is it possible that there is a problem about timing?
Cloudbase-init cannot reboot the system, but after some second, when the system is ready and I can login, I can reboot it as Administrator (invoking the same InitiateSystemShutdownExW function) without problems.

@ader1990
Copy link
Member

ader1990 commented Sep 8, 2022

Weird!

Yes, also my script is idempotent to do these steps sequentially across different reboots.

It's very similar to my script. The only difference is that I specify more parameters in ADDSForest:

Install-ADDSForest `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-DomainMode "$domainMode" `
-DomainName "$fullDomainName" `
-DomainNetbiosName "$shortDomainName" `
-ForestMode "$forestMode" `
-InstallDns:$true `
-LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$true `
-SysvolPath "C:\Windows\SYSVOL" `
-SafeModeAdministratorPassword $secureSafeModePassword `
-Force:$true

Also, I'm using your same version of Windows Server 2019 (connected to the internet) with Cloudbase 1.1.2 64bit with NoCloudConfigDriveService and these plugins:

  • SetHostNamePlugin
  • NetworkConfigPlugin
  • UserDataPlugin
  • LocalScriptsPlugin

I sysprepped the image with sysprep.exe /generalize /oobe /shutdown /unattend:Unattend.xml using the default Unattend.xml.

My config file contains:

username=Administrator
groups=Administrators
inject_user_password=true
first_logon_behaviour=no
...
allow_reboot=true
stop_service_on_exit=false
check_latest_version=false

But I don't think that this issue is related to the config of cloudbase-init.

What is the purpose of the flag "LocalSystem" in cloudbase-init? Is it a way to run it as Administrator instead of its specific user? If I run InitiateSystemShutdownExW as Administrator when the system is blocked (after the previous error, when cloudbase is not able to reboot) I can easely reboot the system without issues. Is there a way to try to manually run InitiateSystemShutdownExW as cloudbaseinit user, instead of Administrator, to check if the problem is about permissions? Because, I saw this problem only when cloudbase executes InitiateSystemShutdownExW (without "LocalSystem" flag).

Or, is it possible that there is a problem about timing? Cloudbase-init cannot reboot the system, but after some second, when the system is ready and I can login, I can reboot it as Administrator (invoking the same InitiateSystemShutdownExW function) without problems.

Hello,

LocalSystem is a builtin Windows account and it does not get transformed from hostname/username into domainname/username when you create the AD and subsequently you transform the Windows installation into the first AD Domain Controller.

What you can do in your script to try to cancel the reboot is to run: shutdown -a (abort). But the AD Forest install should not trigger the reboot. Also, can you provide the exact userdata to give it a try on my environment to check if I can repro the issue?

Thank you.

@Ks89
Copy link
Author

Ks89 commented Sep 9, 2022

What you can do in your script to try to cancel the reboot is to run: shutdown -a (abort)

I tried to do this via python without success. It won't reboot.

can you provide the exact userdata to give it a try on my environment to check if I can repro the issue?

These are my files in cidata:

meta-data:

instance-id: 314e503b67bf

network-config:

version: 1
config:
- type: physical
    mac_address: '02:CE:34:AA:E0:FA'
    name: eth0
    subnets:
      - type: dhcp

user-data:

#cloud-config

hostname: win-server-2019

users:
  - name: Administrator
    passwd: Passw0rdX1!
    primary_group: Administrators
  - name: Manager
    passwd: Passw0rdX1!
    primary_group: Administrators
  - name: Domainadmin
    passwd: Password1!
    primary_group: Administrators

These are my cloudbase-init configs:

cloudbase-init.conf:

[DEFAULT]
username=Administrator
groups=Administrators
# Use password from the metadata (not random).
inject_user_password=true
# first_logon_behaviour controls what happens with the password at the next logon:
# "always": user is forced to change the password at the next logon
# "clear_text_injected_only": user is forced to change the password only if it's a clear text password coming from the metadata
# "no": user is never forced to change the password
# Which devices to inspect for a possible configuration drive (metadata).
first_logon_behaviour=no
config_drive_raw_hhd=true
config_drive_cdrom=true
config_drive_vfat=true
# Path to tar implementation from Ubuntu.
bsdtar_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\bsdtar.exe
mtools_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\
# Logging debugging level.
verbose=true
debug=true
# Where to store logs.
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=
# Enable MTU and NTP plugins.
mtu_use_dhcp_config=false
ntp_use_dhcp_config=false
# Where are located the user supplied scripts for execution.
local_scripts_path=D:\localscripts\
# Services that will be tested for loading until one of them succeeds.
metadata_services=cloudbaseinit.metadata.services.nocloudservice.NoCloudConfigDriveService
# What plugins to execute.
plugins=cloudbaseinit.plugins.common.sethostname.SetHostNamePlugin,
        cloudbaseinit.plugins.common.networkconfig.NetworkConfigPlugin,
        cloudbaseinit.plugins.common.userdata.UserDataPlugin,
        cloudbaseinit.plugins.common.localscripts.LocalScriptsPlugin
# Allow the service to reboot the system
allow_reboot=true
stop_service_on_exit=false
check_latest_version=false

cloudbase-init-unattend.conf:

[DEFAULT]
# Use password from the metadata (not random).
inject_user_password=false
# first_logon_behaviour controls what happens with the password at the next logon:
# "always": user is forced to change the password at the next logon
# "clear_text_injected_only": user is forced to change the password only if it's a clear text password coming from the metadata
# "no": user is never forced to change the password
# Which devices to inspect for a possible configuration drive (metadata).
first_logon_behaviour=no
config_drive_raw_hhd=true
config_drive_cdrom=true
config_drive_vfat=true
# Path to tar implementation from Ubuntu.
bsdtar_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\bsdtar.exe
mtools_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\
# Logging debugging level.
verbose=true
debug=true
# Where to store logs.
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=
# Enable MTU and NTP plugins.
mtu_use_dhcp_config=false
ntp_use_dhcp_config=false
# Where are located the user supplied scripts for execution.
local_scripts_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\LocalScripts\
# Services that will be tested for loading until one of them succeeds.
metadata_services=
# What plugins to execute.
plugins=
# Allow the service to reboot the system
allow_reboot=true
stop_service_on_exit=false
check_latest_version=false

And the default Unattend.xml preinstalled with Cloudbase-init 1.1.2.

Note that I'm using a localscript local_scripts_path=D:\localscripts\, only because I'm passing localscript file inside cidata iso, instead of a fixed file in the default local path. (this makes my tests easier to set-up).

Thanks

@ader1990
Copy link
Member

ader1990 commented Dec 5, 2022

Hello again,

I would need the exact localscript you are using in order to reproduce, as I have tried with the one I shared above and works as expected. I think there might be a way to fix it in cloudbase-init code directly -- perform a shutdown abort if need be, but I need to reproduce the issue first.

Thank you,
Adrian Vladu

@Ks89
Copy link
Author

Ks89 commented Dec 19, 2022

Hi @ader1990 I'm sorry for the delay.

This is my full localscript file executed from a virtual cd-rom with path D:\localscripts defined as local_scripts_path in cloudbase-init.conf:

#ps1_sysnative

$regPath = "HKLM:\Software\ExampleValues"

if (-Not (Test-Path $regPath))
{
  New-Item -Path $regPath -ItemType Directory
}

Try
{
  Get-ItemProperty -Path $regPath -Name Init -ErrorAction Stop
  echo "Init property found!"
}
Catch [System.Exception]
{
  echo "Cannot find Init property in System Registry, creating it..."
  New-ItemProperty -Path $regPath -Name Init -PropertyType DWord -Value 0
}

  # in case of domain controller
  switch ( (Get-ItemProperty -Path $regPath -Name Init).Init )
  {
    0 {
      echo "SystemRegistry ItemProperty $regPath at value = 0"
      $fullDomainName = "example.corp"
      $shortDomainName = "EXAMPLE"
      $domainMode = "Win2012R2"
      $forestMode = "Win2012R2"
      $safeModePassword = "Password1!"
      $secureSafeModePassword = ConvertTo-SecureString "$safeModePassword" -AsPlainText -Force

      Import-Module ADDSDeployment
      Install-ADDSForest `
      -CreateDnsDelegation:$false `
      -DatabasePath "C:\Windows\NTDS" `
      -DomainMode "$domainMode" `
      -DomainName "$fullDomainName" `
      -DomainNetbiosName "$shortDomainName" `
      -ForestMode "$forestMode" `
      -InstallDns:$true `
      -LogPath "C:\Windows\NTDS" `
      -NoRebootOnCompletion:$true `
      -SysvolPath "C:\Windows\SYSVOL" `
      -SafeModeAdministratorPassword $secureSafeModePassword `
      -Force:$true

      echo "Forest added successfully. Setting ItemProperty $regPath to 2"
      Set-ItemProperty -Path $regPath -Name Init -Value 2

      echo "ItemProperty $regPath set to 2. Restarting..."
      exit 1003
    }
    2 {
      Try
      {
        Get-ItemProperty -Path $regPath -Name Tries -ErrorAction Stop
        echo "Tries property found!"
      }
      Catch [System.Exception]
      {
        echo "Cannot find Tries property in System Registry, creating it..."
        New-ItemProperty -Path $regPath -Name Tries -PropertyType DWord -Value 0
      }

      $Stoploop = $false
      [int]$Retrycount = "0"
      do {
        try {
          echo "Try to add domain users..."
            echo "Adding domain user = j.robinson"

            $userPassword = "Password3!"
            $secureUserPassword = ConvertTo-SecureString "$userPassword" -AsPlainText -Force
            New-ADUser `
            -Name "Jack Robinson" `
            -GivenName "Jack" `
            -Surname "Robinson" `
            -SamAccountName "J.Robinson" `
            -UserPrincipalName "j.robinson" `
            -AccountPassword $secureUserPassword `
            -Enabled $true

            echo "Domain users added."

          echo "Exiting from do-while loop"
          $Stoploop = $true
        } catch {
          if ($Retrycount -gt 40) {
            echo "Could not send Information after 40 retrys."
            $Stoploop = $true
          } else {
            echo "Could not send Information at retry=$Retrycount. Retrying in 30 seconds..."
            Start-Sleep -Seconds 30
            $Retrycount = $Retrycount + 1
            Set-ItemProperty -Path $regPath -Name Tries -Value $Retrycount
          }
        }
      } While ($Stoploop -eq $false)

      echo "Adding domainadmin to 'Domain admins' groups"
      Add-ADGroupMember -Identity "Domain Admins" -Members domainadmin

      # TODO is this really required?
      Start-Sleep -Seconds 20

        echo "Adding ADGroupMember for user = j.robinson"

        echo "ADGroupMember skipped for user = j.robinson, because not required"

      echo "Setting ItemProperty $regPath to 3"
      Set-ItemProperty -Path $regPath -Name Init -Value 3

      echo "ItemProperty $regPath set to 3. Restarting..."

      exit 1003
    }
    3 {
      echo "Value of ItemProperty $regPath is 2, so windowDomain has been created."
    }
    default {
      echo "ERROR - UNKNOWN INIT VALUE!!!"
      exit 1002
    }
  }


# clean-up System Registry
echo "Cleaning-up System Registry key"
Remove-ItemProperty -Path $regPath -Name Init -Force

Write-Output "Shutting down..."

Stop-Computer -Force

Write-Output "Shutdown called"

The config files used are those #100 (comment)

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