oracle / terraform-provider-oci

Terraform Oracle Cloud Infrastructure provider
https://www.terraform.io/docs/providers/oci/
Mozilla Public License 2.0
760 stars 683 forks source link

Unable to run user data on Windows service 2022(OCI Instance) #2106

Open Madhurya98 opened 6 months ago

Madhurya98 commented 6 months ago

Community Note Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request If you are interested in working on this issue or have submitted a pull request, please leave a comment Terraform Version and Provider Version Terraform v1.6.2 Provider Version 5.27.0

Affected Resource(s) affected_resources = oci_core_instance , oci_core_instances

Terraform Configuration Files resource "oci_core_instance" "windows-test1" {

Required

availability_domain = var.availability_domain compartment_id = var.compartment_id shape = var.instance_shape defined_tags = merge(var.tags, var.env_tag) shape_config { ocpus = var.cpus memory_in_gbs = var.memory_in_gbs } source_details { source_id = var.source_id source_type = "image" }

Optional

display_name = "test-windows" create_vnic_details { assign_public_ip = false subnet_id = var.subnet_id } metadata = { ssh_authorized_keys = file(var.ssh_public_key_path) user_data = "${base64encode(data.template_file.cloud-config.rendered)}" } instance_options { are_legacy_imds_endpoints_disabled = var.legacy_imds_endpoints_disabled } is_pv_encryption_in_transit_enabled = var.intransit_encryption_enabled preserve_boot_volume = var.preserve_boot_volume }

also passing data.tf

data "template_file" "cloud-config" { template = file("./testinit.ps1.tpl") }

data "template_cloudinit_config" "config" { gzip = false base64_encode = true

part { content_type = "text/cloud-config"

content_type = "text/x-shellscript" ---> tried this content type as well

content      = data.template_file.cloud-config.rendered

} }

testinit.ps1.tpl

ps1_sysnative

function Get-TimeStamp { return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date) }

function checkPathExists($path) { <# .Description Check if the path exists else create path .Parameters $path: Check if $path exists .Return Path which was created if not exists

>

try
{
    $temp_path_copy = $path
    $file_extensions = @('.zip', '.exe', '.txt', '.xml', '.msi', '.pem', '.sql', '.py', '.config', '.json', '.ps1', '.psm1', '.cer', '.log')    
    $file_extensionsRegex = [string]::Join('|', $file_extensions) # create the regex
    If($path -match $file_extensionsRegex)
    {
        $remove_zip_path_ref = $path.split("\")
        $path = $remove_zip_path_ref[0..($remove_zip_path_ref.length-2)] -join "\"
    }
    If(!(test-path -PathType container $path))
    {
        New-Item -ItemType Directory -Path $path 
        Write-Host "$(Get-TimeStamp) Created path $path successfully" 
    }
    else
    {
        Write-Host "$(Get-TimeStamp) Path $path exists"
    }
    $path = $temp_path_copy
    return $path
}
catch
{
    Write-Error "$(Get-TimeStamp) Error in checkPathExists `nError - $_" -ErrorAction Stop
}

}

function CreateEnvVariable($variableName,$value) <# .Description Update Environment variable .Parameters $variableName: Name of the variable which needs to be added to env variable $value: Value of the variable

>

{ try{ [Environment]::SetEnvironmentVariable($variableName, $value, "Machine") Write-Host "$(Get-TimeStamp) $variableName with value "$value" is added to environment variables" } catch{ Write-Host "$(Get-TimeStamp) Failed to add $variableName with value "$value" to environment variables" -ErrorAction Stop } }

function updatePathSystemVariable($variableName,$value,$scope) <# .Description Update path system variable .Parameters $variableName: Name of the variable which needs to be added to PATH $value: Value of the variable

>

{ try{ if (!$scope){$scope="Machine"} $Prepath=[Environment]::GetEnvironmentVariable("$variableName",$scope) $newPath=";$Prepath;$value" [Environment]::SetEnvironmentVariable("$variableName", $newPath,$scope) Write-Host "$(Get-TimeStamp) $value path is updated in environment variables" } catch{ Write-Error "$(Get-TimeStamp) Failed to add $value to environment variables`nError - $_" -ErrorAction Stop } }

function downloadFile($web_path,$destination_path) {<# .Description Download a file from a web url .Parameters $web_path: Url to download the file $destination_path: Path where the file needs to be downloaded

>

try{
    checkPathExists -path $destination_path
    Invoke-RestMethod -Uri $web_path -OutFile $destination_path
    Write-Host "$(Get-TimeStamp) File downloaded successfully"
    waitFileDownload -filepath $destination_path
    }
catch{
    Write-Error "$(Get-TimeStamp) Downloading the file failed`nError - $_" -ErrorAction Stop
    }

} function waitFileDownload($filepath) {<# .Description Wait for specified time for the file to download .Parameters $filepath: File download path

>

$timeoutSec = 10
$intervalSec = 5
$startTime = Get-Date
while (-not (Test-Path -Path $filepath) -and ((Get-Date) -lt ($startTime.AddSeconds($timeoutSec)))) 
{
    Write-Host "$(Get-TimeStamp) Waiting $intervalSec for the file to download"
    Start-Sleep -Seconds $intervalSec
}
if (Test-Path -Path $filePath)
{
    Write-Host "$(Get-TimeStamp) $filepath exists"
}
else
{
    Write-Error "$(Get-TimeStamp) File download timeout reached" #-ErrorAction Stop 
}

}

function Install-TennableAgent($path,$NessusServer,$NessusKey,$NessusGroups) <# .Description Install Tennable Agent .Parameters $path: Path where file needs to be downloaded and installed $NessusServer: Server URL of Nesus $NessusKey: Key of the Nessus $NessusGroups: group of Nessus

>

{ $TennableURL="https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents/downloads/22992/download?i_agree_to_tenable_license_agreement=true"

try{
    Write-Host "$(Get-TimeStamp) Initiating TennableAgent download"
    $tennable_setup = [IO.Path]::Combine($path,"NessusAgent-10.6.2-x64.msi")
    downloadFile -web_path $TennableURL -destination_path $tennable_setup
    Write-Host "$(Get-TimeStamp) Initiating Tennable Agent installation"
    Start-Process msiexec.exe -ArgumentList "/i `"$tennable_setup`" NESSUS_SERVER=$NessusServer NESSUS_KEY=$NessusKey NESSUS_GROUPS=$NessusGroups  /qn" -Wait
    updatePathSystemVariable -variableName "PATH" -value "$tennable_setup"
    Write-Host "$(Get-TimeStamp) Tennable Agent installed successfully"

    }
catch{
Write-Host "Error: $_"
}
}

Install-TennableAgent -path "C:\Tennable" -NessusServer ":" -NessusKey "" -NessusGroups ""

Debug Output NA

Panic Output NA

Expected Behavior The powershell script must be executed as part of the user data on the windows server 2022 and get the tenable agent installed on top of the oci instance.

Actual Behavior

  1. The User data script is not executed as expected, hence the tenable agent is not downloaded and installed.
  2. The same user data installation works fine in the oci instance from the console when it is done manually.

Steps to Reproduce

  1. terraform apply Important Factoids NA

References None

tf-oci-pub commented 6 months ago

Thank you for reporting the issue. We observed the affected resources are not provided in the description or it's incorrect. We request you to add it in issue description as mentioned in below format. Example: affected_resources = oci_core_instance , oci_core_instances

If it's not related to any particular resource then mention affected resource as terraform. Example: affected_resources = terraform

As this works through automation, request you to follow exact syntax.

Madhurya98 commented 6 months ago

Updated

ViniciusBastosTR commented 5 months ago

Some updates here?

rcsvenlimbach commented 5 months ago

@tf-oci-pub We can confirm that we have the same behavior with a user_data script to change and unexpire the opc Password on an windows instance image. The TF Code is unchanged and worked before without any issues. It would be great if someone can find out if that is a BUG.

rcsvenlimbach commented 5 months ago

@Madhurya98 Please can you check on your instance which API Endpoints are enabled:

Instance metadata service: Versions 1 and 2 OR Instance metadata service: Version 2 only

The user_data / Cloudinit needs the legacy Endpoints be enabled. So the Instance should have:

Instance metadata service: Versions 1 and 2

instance_options { are_legacy_imds_endpoints_disabled = false }

asaber80 commented 3 months ago

@tf-oci-pub We can confirm that we have the same behavior with a user_data. The User data script is not executed via terraform for windows and linux instances, while the same TF Code worked with resource manager oci service.

rcsvenlimbach commented 3 months ago

@asaber80 Did you check your Instance Metadata Versions? You need 1 and 2 available

asaber80 commented 3 months ago

@rcsvenlimbach Yes both versions are available