- "Octopus.Action.Script.ScriptBody": "# Define functions\nfunction Get-ModuleInstalled\n{\n # Define parameters\n param(\n $PowerShellModuleName\n )\n\n # Check to see if the module is installed\n if ($null -ne (Get-Module -ListAvailable -Name $PowerShellModuleName))\n {\n # It is installed\n return $true\n }\n else\n {\n # Module not installed\n return $false\n }\n}\n\nfunction Install-PowerShellModule\n{\n # Define parameters\n param(\n $PowerShellModuleName,\n $LocalModulesPath\n )\n\n\t# Check to see if the package provider has been installed\n if ((Get-NugetPackageProviderNotInstalled) -ne $false)\n {\n \t# Display that we need the nuget package provider\n Write-Host \"Nuget package provider not found, installing ...\"\n \n # Install Nuget package provider\n Install-PackageProvider -Name Nuget -Force\n }\n\n\t# Save the module in the temporary location\n Save-Module -Name $PowerShellModuleName -Path $LocalModulesPath -Force\n}\n\nfunction Get-NugetPackageProviderNotInstalled\n{\n\t# See if the nuget package provider has been installed\n return ($null -eq (Get-PackageProvider -ListAvailable -Name Nuget -ErrorAction SilentlyContinue))\n}\n\nfunction Get-DatabaseExists\n{\n\t# Define parameters\n param ($DatabaseName)\n \n\t# Execute query\n return Invoke-SqlQuery -Query \"SELECT datname FROM pg_catalog.pg_database where datname = '$DatabaseName';\" -CommandTimeout $postgresCommandTimeout\n}\n\n# Define PowerShell Modules path\n$LocalModules = (New-Item \"$PSScriptRoot\\Modules\" -ItemType Directory -Force).FullName\n$env:PSModulePath = \"$LocalModules$([System.IO.Path]::PathSeparator)$env:PSModulePath\"\n$PowerShellModuleName = \"SimplySql\"\n\n# Set secure protocols\n[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12\n\n# Check to see if SimplySql module is installed\nif ((Get-ModuleInstalled -PowerShellModuleName $PowerShellModuleName) -ne $true)\n{\n # Tell user what we're doing\n Write-Output \"PowerShell module $PowerShellModuleName is not installed, downloading temporary copy ...\"\n\n # Install temporary copy\n Install-PowerShellModule -PowerShellModuleName $PowerShellModuleName -LocalModulesPath $LocalModules\n}\n\n# Display\nWrite-Output \"Importing module $PowerShellModuleName ...\"\n\n# Check to see if it was downloaded\nif ((Test-Path -Path \"$LocalModules\\$PowerShellModuleName\") -eq $true)\n{\n\t# Use specific version\n $PowerShellModuleName = \"$LocalModules\\$PowerShellModuleName\"\n}\n\n# Import the module\nImport-Module -Name $PowerShellModuleName\n\n# Get whether trust certificate is necessary\n$createTrustSSL = [System.Convert]::ToBoolean(\"$createTrustSSL\")\n\ntry\n{\n\t# Declare initial connection string\n $connectionString = \"Server=$createPosgreSQLServerName;Port=$createPort;Database=postgres;\"\n \n\t# Check to see if we need to trust the ssl cert\n\tif ($createTrustSSL -eq $true)\n\t{\n # Append SSL connection string components\n $connectionString += \"SSL Mode=Require;Trust Server Certificate=true;\"\n\t}\n\n # Update the connection string based on authentication method\n switch ($postgreSqlAuthenticationMethod)\n {\n \"azuremanagedidentity\"\n {\n \t# Get login token\n Write-Host \"Generating Azure Managed Identity token ...\"\n $token = Invoke-RestMethod -Method GET -Uri \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://ossrdbms-aad.database.windows.net\" -Headers @{\"MetaData\" = \"true\"}\n \n # Append remaining portion of connection string\n $connectionString += \";User Id=$createUsername;Password=`\"$($token.access_token)`\";\"\n \n break\n }\n \"awsiam\"\n {\n # Region is part of the RDS endpoint, extract\n $region = ($createPosgreSQLServerName.Split(\".\"))[2]\n\n Write-Host \"Generating AWS IAM token ...\"\n $createUserPassword = (aws rds generate-db-auth-token --hostname $createPosgreSQLServerName --region $region --port $createPort --username $createUsername)\n\n # Append remaining portion of connection string\n $connectionString += \";User Id=$createUsername;Password=`\"$createUserPassword`\";\"\n\n break\n }\n \"gcpserviceaccount\"\n {\n # Define header\n $header = @{ \"Metadata-Flavor\" = \"Google\"}\n\n # Retrieve service accounts\n $serviceAccounts = Invoke-RestMethod -Method Get -Uri \"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/\" -Headers $header\n\n # Results returned in plain text format, get into array and remove empty entries\n $serviceAccounts = $serviceAccounts.Split([Environment]::NewLine, [StringSplitOptions]::RemoveEmptyEntries)\n\n # Retreive the specific service account assigned to the VM\n $serviceAccount = $serviceAccounts | Where-Object {$_.Contains(\"iam.gserviceaccount.com\") }\n\n Write-Host \"Generating GCP IAM token ...\"\n # Retrieve token for account\n $token = Invoke-RestMethod -Method Get -Uri \"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/$serviceAccount/token\" -Headers $header\n \n # Check to see if there was a username provided\n if ([string]::IsNullOrWhitespace($createUsername))\n {\n \t# Use the service account name, but strip off the .gserviceaccount.com part\n $createUsername = $serviceAccount.SubString(0, $serviceAccount.IndexOf(\".gserviceaccount.com\"))\n }\n \n # Append remaining portion of connection string\n $connectionString += \";User Id=$createUsername;Password=`\"$($token.access_token)`\";\"\n \n break\n }\n \"usernamepassword\"\n {\n # Append remaining portion of connection string\n $connectionString += \";User Id=$createUsername;Password=`\"$createUserPassword`\";\"\n\n break \n }\n\n \"windowsauthentication\"\n {\n # Append remaining portion of connection string\n $connectionString += \";Integrated Security=True;\"\n }\n }\n\n\t# Open connection\n Open-PostGreConnection -ConnectionString $connectionString\n\n # See if database exists\n $databaseExists = Get-DatabaseExists -DatabaseName $createDatabaseName\n\n if ($databaseExists.ItemArray.Count -eq 0)\n {\n # Create database\n Write-Output \"Creating database $createDatabaseName ...\"\n $executionResult = Invoke-SqlUpdate -Query \"CREATE DATABASE `\"$createDatabaseName`\";\" -CommandTimeout $postgresCommandTimeout\n\n # Check result\n if ($executionResult -ne -1)\n {\n # Commit transaction\n Write-Error \"Create schema failed.\"\n }\n else\n {\n \t# See if it was created\n $databaseExists = Get-DatabaseExists -DatabaseName $createDatabaseName\n \n # Check array\n if ($databaseExists.ItemArray.Count -eq 1)\n {\n \t# Success\n Write-Output \"$createDatabaseName created successfully!\"\n }\n else\n {\n \t# Failed\n Write-Error \"$createDatabaseName was not created!\"\n }\n }\n }\n else\n {\n \t# Display message\n Write-Output \"Database $createDatabaseName already exists.\"\n }\n}\nfinally\n{\n Close-SqlConnection\n}\n\n\n"
0 commit comments