Accessing existing cloud SQL instance from another project ID - google-app-engine

I have created a cloud sql instance in a PHP project and have made the billing procedure successfully. The project works.
Now, I want to access my database from another project but this time in Java SDK project with servlets.
Using the example in https://developers.google.com/appengine/
docs/java/cloud-sql/
In Java project I have:
project id: javaProjectID
In php project id I have:
project id: phptestID
instance name: phpinstanceName
database: dbname
In my code in Servlet i do the below connection:
String url = "jdbc:google:mysql://phptestID:phpinstanceName/dbname?user=root";
Connection conn = (Connection) DriverManager.getConnection(url);
(...>> The connection fails in this point and doesn't access the database to make the below query )
String sqlStmt = "SELECT * FROM sometable";
PreparedStatement stmt = conn.prepareStatement(sqlStmt);
ResultSetres = stmt.executeQuery(sqlStmt);
How can I access my database in another project?? Is there any other way except
your-project-id:your-instance-name???

You will need to give the new app engine app access to your CloudSQL instance. To do this go to the Cloud SQL instance in the console, edit it, go down to Authorized App Engine Applications and then add the app id of the new App Engine app.
UPDATE:
The most recent steps look like in the attached screenshot below

Related

Connect to a Microsoft SQL Server database to which is normally connected to via GlobalProtect using .NET 6 application

I'm using .NET 6, Azure Function version 4 and SqlClient in my Azure Function application.
I have a connection string like this
Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;
Normally, I access this database using GlobalProtect by providing it portal, username and password.
Now, I'm developing an Azure Function app which will access this database, but I'm getting this error
System.Private.CoreLib: Exception while executing function:
MyAzurefunction. Core .Net SqlClient Data Provider: Cannot open
server 'serverName' requested by the login. Client with IP address
'MyIpAddress' is not allowed to access the server. To enable
access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule
for this IP address or address range. It may take up to five minutes
for this change to take effect.
I know I'm getting this error because my IP Address doesn't have access to the server but how can I connect to it via my Connection String?
I create azure SQL database. connection string of database:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Image for reference:
I created function app with .net 6 in visual studio.
Image for reference:
I published it to Azure.
Image for reference:
Selected the ellipse(...) on the published page and selected Manage Azure App Service settings.
Image for reference:
Click on Add Setting in Application page and add the name of setting.
Image for reference:
In sql_connection enter the connection string of sql db in Local section for remote section click on Insert Value from Local.
Image for reference:
Install System.Data.SqlClient package in Manage Nuget packages of project. I added below code that connects to SQL Database :
using System.Data.SqlClient;
using System.Threading.Tasks;
[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
// Get the connection string from app settings and use it to create a connection.
var str = Environment.GetEnvironmentVariable("sqldb_connection");
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "UPDATE SalesLT.SalesOrderHeader " +
"SET [Status] = 5 WHERE ShipDate < GetDate();";
using (SqlCommand cmd = new SqlCommand(text, conn))
{
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
Above function runs every 15 seconds to update the Status column based on the ship date.
I added my IP address in database firewall settings.
Image for reference:
At 15 seconds after startup, the function runs.
Output of number of rows updated in the SalesOrderHeader table:
In this way I connected to my SQL database to my function app.

Create a SQL Server database while deploying an RDS instance using Terraform

I'm using Terraform with the AWS provider (v3.37.0) to create an RDS instance:
resource "aws_db_instance" "rds" {
identifier = "my_db"
engine = "sqlserver-se"
engine_version = "14.00.3401.7.v1"
name = null
username = "${somewhere/in/ssm}"
password = "${somewhere/in/ssm}"
}
I wish to create a database alongside this RDS instance, so the documentation (https://registry.terraform.io/providers/hashicorp/aws/3.37.0/docs/resources/db_instance) states that I need to assign a value to the variable name, which I cannot, since the engine that I'm using (SQL Server) doesn't support that.
Is there another way to create that database inside this instance within Terraform?
I was thinking of using the local-exec provisioner or a community provider, but:
For the local-exec provider, I don't know what I would put in the command. Would the following work, for example?
resource "aws_db_instance" "rds" {
identifier = "my_db"
engine = "sqlserver-se"
engine_version = "14.00.3401.7.v1"
name = null
username = "${somewhere/in/ssm}"
password = "${somewhere/in/ssm}"
provisioner "local-exec" {
command = "USE master; CREATE DATABASE db-name"
}
}
For the community providers, I'm not really that trusting, but I could make leeway if they end up being my only option.
I don't know what I would put in the command
You need to use full mssql-cli command (or any other programming interface to mssql) which will execute on your computer and create your database. This means you have to have it installed first. For example, you can develop a python script which will connect and create your database. Then you invoke the python script from your local-exec.

Terraform InvalidParameterCombination with AWS Microsoft SQL

Having issues when trying to create an AWS RDS instance with terraform, I have gone through the documentation in AWS and Terraform and I just cannot see why this would be an invalid combination, I'm trying to create a free tier DB for testing:
resource "aws_db_instance" "rds-mssql" {
allocated_storage = 20
engine = "sqlserver-ee"
engine_version = "14.00.3356.20.v1"
instance_class = "db.t2.micro"
name = "mydbtest"
username = "usernameGoesHere"
password = "passwordGoesHere"
license_model = "license-included"
}
Getting the following error:
Error: Error creating DB Instance: InvalidParameterCombination: RDS does not support creating a DB instance with the following combination: DBInstanceClass=db.t2.micro, Engine=sqlserver-ee, EngineVersion=14.00.3356.20.v1, LicenseModel=license-included. For supported combinations of instance class and database engine version, see the documentation
I have followed documentation from here: https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html
Also I have created manually from the AWS console a DB with those specs with no problem
Thanks in advance
sqlserver-ee is for Enterprise Edition which does not support t2.micro. I guess you want sqlserver-ex (express edition).

Missing socket for connection to Cloud SQL from Google App Engine standard environment

I am trying to connect a Python 3.7 GAE app in standard environment to a Cloud SQL Postgres 9.6 database.
The procedure is described in this doc.
Unfortunately, the UNIX socket /cloudsql/<DB_CONNECTION_NAME> that is normally used to connect to the database does not exist on the GAE instance (folder /cloudsql is empty).
More information on what I tried:
the GAE app and the cloud SQL instance are in the same project and region (I tried in europe-west1 and europe-west3)
I have added and removed a beta_settings -> cloud_sql_instances key in the app.yaml config file, to no avail. From what I understood, this should only be needed in the flexible environment anyway
I have activated the Cloud SQL Admin UI
Has anyone encountered and solved this problem?
The SO questions about this problem are either old, unanswered, or do not solve the problem in my environment.
I am able to get the connection working with the following configuration:
PROJECT=[[YOUR-PROJECT-ID]]
REGION=europe-west3
INSTANCE=instance-01
and:
import os
from flask import Flask
import psycopg2
db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_pass = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE')
db_conn = os.environ.get('CLOUD_SQL_INSTANCE')
app = Flask(__name__)
#app.route('/')
def main():
host = '/cloudsql/{}'.format(db_conn)
cnx = psycopg2.connect(
dbname=db_name,
user=db_user,
password=db_pass,
host=host
)
with cnx.cursor() as cursor:
cursor.execute('SELECT NOW() as now;')
result = cursor.fetchall()
current_time = result[0][0]
cnx.commit()
cnx.close()
return str(current_time)
and:
flask==1.0.2
psycopg2==2.8
and, with ${VARIABLE} replaced with value:
runtime: python37
env_variables:
CLOUD_SQL_INSTANCE: "${PROJECT}:${REGION}:${INSTANCE}"
CLOUD_SQL_USERNAME: ${USERNAME}
CLOUD_SQL_PASSWORD: ${PASSWORD}
CLOUD_SQL_DATABASE: ${DATABASE}
Based on a similar issue, the most probable root cause is detailed here:
https://issuetracker.google.com/117804657#comment16
Other possible causes, per the discussion, could be:
A lack of public IP on the SQL instance
Specification of the port in the configuration settings
Here are some recommendations:
Run the application locally to make sure it works before deploying to App Engine.
Double check the Cloud SQL configuration (e.g. username, password, instance connection name) on the app.yaml file.
Make sure the Google Cloud SQL API is enabled.
Try recreating the Cloud SQL instance.
Simply recreating the Cloud SQL instance or database has worked in other cases, as modifications to the quickstart’s default setup might be difficult to track.
Cheers
I fixed this by enabling the Cloud SQL Admin API.
See https://cloud.google.com/sql/docs/postgres/debugging-connectivity

Bluemix connecting to external SQL Server Database

I have an application built using the ASP.NET 5 runtime - I would like to connect it to an on-premise SQL Server Database.
After some research I've already created the user-provided service with the relevant credentials, however I am unsure what to do next (i.e. writing the necessary code connecting it in ASP.NET).
Some further googling suggests to use Secure Gateway? but is this the only way? the cloud I am working on is dedicated and does not have the Secure Gateway service. Is there a workaround for this?
(Note: The application I'm working on is based on the ASP.NET-Cloudant example on IBM Github, if that helps).
https://github.com/IBM-Bluemix/asp.net5-cloudant
The Secure Gateway service isn't required as long as the Bluemix environment can connect to the server running SQL Server. This might require your firewall rules to be a little more relaxed on the SQL Server, or you can contact IBM to create a secure tunnel as Hobert suggested in his answer.
Aside from that issue, if you're planning to use Entity Framework to connect to your SQL Server, it should work similar to the existing tutorials on the asp.net site. The only difference will be in how you access the environment variables to create your connection string.
Assuming that you created your user-provided service with a command similar to this:
cf cups my-sql-server -p '{"server":"127.0.0.1","database":"MyDB","user":"sa","password":"my-password"}'
Your connection string in your Startup.cs file's ConfigureServices method would then look something like this:
string vcapServices = Environment.GetEnvironmentVariable("VCAP_SERVICES");
string connection = "";
if (vcapServices != null)
{
string myServiceName = "my-sql-server";
JArray userServices = (JArray)JObject.Parse(vcapServices)?["user-provided"];
dynamic creds = ((dynamic)userServices
.FirstOrDefault(m => ((dynamic)m).name == myServiceName))?.credentials;
connection = string.Format(#"Server={0};Database={1};User Id={2}; Password={3};",
creds.server, creds.database, creds.user, creds.password);
}
Update
The cloudant boilerplate that you're modifying doesn't use Entity Framework because cloudant is a NoSQL database, so it's a bit different than connecting to SQL Server. The reason that the boilerplate calls .Configure to register the creds class is that it needs to use that class from another location, but when using Entity Framework you simply need to use the credentials when adding EF to the services in the Startup.cs file so you don't need to use .Configure<creds>.
If you follow the guide here, the only part you'll need to change is the line var connection = #"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNet5.NewDb;Trusted_Connection=True;"; replacing it with the code above to create the connection string instead of hard-coding it like they did in the example tutorial.
Eventually, your ConfigureServices method should look something like this, assuming your DbContext class is named BloggingContext like in the example:
public void ConfigureServices(IServiceCollection services)
{
string vcapServices = Environment.GetEnvironmentVariable("VCAP_SERVICES");
string connection = "";
if (vcapServices != null)
{
string myServiceName = "my-sql-server";
JArray userServices = (JArray)JObject.Parse(vcapServices)?["user-provided"];
dynamic creds = ((dynamic)userServices
.FirstOrDefault(m => ((dynamic)m).name == myServiceName))?.credentials;
connection = string.Format(#"Server={0};Database={1};User Id={2}; Password={3};",
creds.server, creds.database, creds.user, creds.password);
}
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
services.AddMvc();
}
And then your Startup method would be simplified to:
public Startup(IHostingEnvironment env)
{
var configBuilder = new ConfigurationBuilder()
.AddJsonFile("config.json", optional: true);
Configuration = configBuilder.Build();
}
Excellent!
In Public Bluemix Regions, you would create and use the Secure Gateway Service to access the On-Premise MS SQL Server DB.
In your case, as a Bluemix Dedicated client, you should engage your IBM Bluemix Administration Team so they can work with your Network Team to create a tunnel between the Dedicated Bluemix Region and your On-Premise MS SQL DB Server.
If you want to connect directly from your Asp.Net Core application to a SQL Server you actually don't need a Secure Gateway.
For example, if you want to use a SQL Azure as your Database you can simply add the given connection string in your application.
But, for pratical and security reasons, you should create a User-Provided Service to store your credentials (and not use statically in your code), and pull your credentials from you VCAP_SERVICES simply adding SteelToe to your Cconfiguration Builder. (Instead of use parse the configuration manually with JObjects and JArrays)
Step-by-step:
In your CloudFoundry console create a User-Provided Service using a Json:
cf cups MySqlServerCredentials -p '{"server":"tcp:example.database.windows.net,1433", "database":"MyExampleDatabase", "user":"admin", "password":"password"}'
Obs.: If you use Windows console/Powershell you should escape you double quotes in Json like:
'{\"server\":\"myserver\",\"database\":\"mydatabase\",\"user\":\"admin\",\"password\":\"password\"}'
After you have created your User-Provided Service you should Connect this Service with your application in Bluemix Console.
Then, In your application add the reference to SteelToe CloudFoundry Steeltoe.Extensions.Configuration.CloudFoundry
In your Startup class add:
using Steeltoe.Extensions.Configuration;
...
var builder = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.AddCloudFoundry();
var config = builder.Build();
Finally, to access your configurations just use:
var mySqlName = config["vcap:services:user-provided:0:name"];
var database = config["vcap:services:user-provided:0:credentials:database"];
var server = config["vcap:services:user-provided:0:credentials:server"];
var password = config["vcap:services:user-provided:0:credentials:password"];
var user = config["vcap:services:user-provided:0:credentials:user"];
OBS.: If you're using Azure, remember to configure your Database firewall to accept the IP of your Bluemis application, but as default Bluemix don't give a static IP address you have some options:
Buy a Bluemix Statica service to you application (expensive)
Update firewall rules with REST put with the current IP of application (workaroud)
Open your Azure Database Firewall to a broad range of IPs. (Just DON'T)
More info about SteelToe CloudFoundry in :
https://github.com/SteeltoeOSS/Configuration/tree/master/src/Steeltoe.Extensions.Configuration.CloudFoundry

Resources