Skip to content

Commit

Permalink
Merge pull request #1515 from OctopusDeploy/update-postgres
Browse files Browse the repository at this point in the history
Updating postgres template
  • Loading branch information
twerthi authored May 28, 2024
2 parents 68101d2 + ab56372 commit 7f74cb9
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions step-templates/postgres-create-database.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
"Name": "Postgres - Create Database If Not Exists",
"Description": "Creates a Postgres database if it doesn't already exist.\n\nNote:\n- AWS EC2 IAM Role authentication requires the AWS CLI be installed.",
"ActionType": "Octopus.Script",
"Version": 9,
"Version": 10,
"Author": "twerthi",
"Packages": [],
"Properties": {
"Octopus.Action.Script.ScriptSource": "Inline",
"Octopus.Action.Script.Syntax": "PowerShell",
"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"
"Octopus.Action.Script.ScriptBody": "# Define variables\n$connectionName = \"OctopusDeploy\"\n\n# 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 -ConnectionName $connectionName\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 -ConnectionName $connectionName\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 -ConnectionName $connectionName\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\t# Close connection if open\n if ((Test-SqlConnection -ConnectionName $connectionName) -eq $true)\n {\n \tClose-SqlConnection -ConnectionName $connectionName\n }\n}\n\n\n"
},
"Parameters": [
{
Expand All @@ -32,7 +32,7 @@
"Octopus.ControlType": "Select",
"Octopus.SelectOptions": "awsiam|AWS EC2 IAM Role\nazuremanagedidentity|Azure Managed Identity\ngcpserviceaccount|GCP Service Account\nusernamepassword|Username\\Password\nwindowsauthentication|Windows Authentication"
}
},
},
{
"Id": "df993ccf-71ab-48de-9a67-e2af6653d35e",
"Name": "createUsername",
Expand Down Expand Up @@ -96,8 +96,8 @@
],
"LastModifiedBy": "twerthi",
"$Meta": {
"ExportedAt": "2022-06-14T15:09:44.806Z",
"OctopusVersion": "2022.2.5111",
"ExportedAt": "2024-05-23T15:30:50.319Z",
"OctopusVersion": "2024.3.164",
"Type": "ActionTemplate"
},
"Category": "postgresql"
Expand Down

0 comments on commit 7f74cb9

Please sign in to comment.