package test import ( "fmt" "github.com/gruntwork-io/terratest/modules/gcp" "github.com/gruntwork-io/terratest/modules/terraform" "github.com/gruntwork-io/terratest/modules/test-structure" "github.com/stretchr/testify/assert" "path/filepath" "strings" "testing" ) const NAME_PREFIX_POSTGRES_PRIVATE = "postgres-private" const EXAMPLE_NAME_POSTGRES_PRIVATE = "postgres-private-ip" func TestPostgresPrivateIP(t *testing.T) { t.Parallel() //os.Setenv("SKIP_bootstrap", "true") //os.Setenv("SKIP_deploy", "true") //os.Setenv("SKIP_validate_outputs", "true") //os.Setenv("SKIP_teardown", "true") _examplesDir := test_structure.CopyTerraformFolderToTemp(t, "../", "examples") exampleDir := filepath.Join(_examplesDir, EXAMPLE_NAME_POSTGRES_PRIVATE) test_structure.RunTestStage(t, "bootstrap", func() { projectId := gcp.GetGoogleProjectIDFromEnvVar(t) region := getRandomRegion(t, projectId) test_structure.SaveString(t, exampleDir, KEY_REGION, region) test_structure.SaveString(t, exampleDir, KEY_PROJECT, projectId) }) // At the end of the test, run `terraform destroy` to clean up any resources that were created defer test_structure.RunTestStage(t, "teardown", func() { terraformOptions := test_structure.LoadTerraformOptions(t, exampleDir) terraform.Destroy(t, terraformOptions) }) test_structure.RunTestStage(t, "deploy", func() { region := test_structure.LoadString(t, exampleDir, KEY_REGION) projectId := test_structure.LoadString(t, exampleDir, KEY_PROJECT) terraformOptions := createTerratestOptionsForCloudSql(projectId, region, exampleDir, NAME_PREFIX_POSTGRES_PRIVATE, "", "", 0, "") test_structure.SaveTerraformOptions(t, exampleDir, terraformOptions) terraform.InitAndApply(t, terraformOptions) }) test_structure.RunTestStage(t, "validate_outputs", func() { terraformOptions := test_structure.LoadTerraformOptions(t, exampleDir) region := test_structure.LoadString(t, exampleDir, KEY_REGION) projectId := test_structure.LoadString(t, exampleDir, KEY_PROJECT) instanceNameFromOutput := terraform.Output(t, terraformOptions, OUTPUT_MASTER_INSTANCE_NAME) ipAddressesFromOutput := terraform.Output(t, terraformOptions, OUTPUT_MASTER_IP_ADDRESSES) privateIPFromOutput := terraform.Output(t, terraformOptions, OUTPUT_MASTER_PRIVATE_IP) assert.Contains(t, ipAddressesFromOutput, "PRIVATE", "IP Addresses output has to contain 'PRIVATE'") assert.Contains(t, ipAddressesFromOutput, privateIPFromOutput, "IP Addresses output has to contain 'private_ip' from output") dbNameFromOutput := terraform.Output(t, terraformOptions, OUTPUT_DB_NAME) proxyConnectionFromOutput := terraform.Output(t, terraformOptions, OUTPUT_MASTER_PROXY_CONNECTION) expectedDBConn := fmt.Sprintf("%s:%s:%s", projectId, region, instanceNameFromOutput) assert.True(t, strings.HasPrefix(instanceNameFromOutput, NAME_PREFIX_POSTGRES_PRIVATE)) assert.Equal(t, DB_NAME, dbNameFromOutput) assert.Equal(t, expectedDBConn, proxyConnectionFromOutput) }) }