I'm new to JavaScript and stuck.
I'm writing my first "real" Electron App and want to connect via sftp. (ssh2-sftp-client to be more specific)
When I set up the connection like the example:
sftp.connect({
host: '192.168.76.173',
port: '22',
username: 'Backup',
password: 'PasswordInPlainText'
}).then(() => {
return sftp.list('/Backups/Server');
}).then(data => {
console.log(data, 'the data info');
}).catch(err => {
console.log(err, 'catch error');
});
everything works like a charm. But when I try to "hide" my credentials in an .env file:
sftp.connect({
host: process.env.HOST,
port: process.env.PORT,
username: process.env.USERNAME,
password: process.env.PASSWORD
}).then(() => {
return sftp.list('/Backups/Server');
}).then(data => {
console.log(data, 'the data info');
}).catch(err => {
console.log(err, 'catch error');
});
I get the error message:
Error: connect: getConnection: All configured authentication methods failed
I checked via
console.log("Host to connect: "+ process.env.HOST)
and the correct output is:
Host to connect: 192.168.76.173
The content of the .env File is
HOST='192.168.76.173'
PORT='22'
USERNAME='Backup'
PASSWORD='PasswordInPlainText'
So this my first time working with environment Variables at all, so I'm guessing I misunderstood something, or a JavaScript property can't be defined by a string this way.
Your problem is that the .env files are not supported in NodeJS by default and you might have some env variables already with the same names and different values (defined in the system probably).
You could either use a NPM package like dotenv or parse the contents of the file by yourself.
You could also test it like that:
// Place this code before you use the ENV variables.
// Replace the `<variables>` with the real data
// and test if your code works with the ENV variables.
process.env.HOST = '<your host ip>';
process.env.PORT = '<your port>';
process.env.USERNAME = '<username>';
process.env.PASSWORD = '<password>';
Related
I was originally on mysql 8.0 which gave me the error
ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
when trying to run my server. I saw on multiple sources that downgrading to mysql#5.7 would solve the problem because 5.7 uses native password authentication, but the same error is still present after downgrading to the earlier version. Are there any other known reasons as to why the error still persists?
Here is my config file:
config.js
// import dependencies
const util = require("util");
const mysql = require("mysql");
// import environment variables
const env = {
env: process.env.NODE_ENV,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
}
const database = mysql.createConnection({
host: env.host,
database: env.database,
user: env.user,
password: env.password
});
database.connect(err => {
if (err) {
console.log("Connection " + err);
} else {
console.log(`Connection Success: You are now connected to the ${env.env} database`);
}
});
// promisify all database queries
database.query = util.promisify(database.query);
// export database
module.exports = database;
MySQL 8.0 introduced a default SHA256 encryption that many clients do not understand. You have many options, the easiest being using the older MySQL native password (see https://mysqlserverteam.com/upgrading-to-mysql-8-0-default-authentication-plugin-considerations/) authentication. Change the account to use the older authentication and your client connector will be happy.
I'm using Elasticsearch in a Rails app via the elasticsearch-model and elasticsearch-rails gems.
Everything was previously working fine, but after some updates I am now getting a Connection Failed error whenever I attempt to interact with the remote cluster (AWS Elasticsearch).
> MyModel.__elasticsearch__.create_index! force: true
=> Faraday::ConnectionFailed (execution expired)
I'm struggling to work out what is causing this connection error. After searching for similar issues, I've adjusted timeouts and tried various combinations of http, https and naked urls, but no success.
What is a sensible way to debug this connection error?
My Elasticsearch is initialized like this.
#initializers/elasticsearch.rb
require 'faraday_middleware'
require 'faraday_middleware/aws_sigv4'
credentials = Aws::Credentials.new(
ENV.fetch('AWS_ACCESS_KEY_ID'),
ENV.fetch('AWS_SECRET_ACCESS_KEY')
)
config = {
url: ENV.fetch('AWS_ELASTICSEARCH_URL'),
retry_on_failure: true,
transport_options: {
request: { timeout: 10 }
}
}
client = Elasticsearch::Client.new( config ) do |f|
f.request :aws_sigv4, credentials: credentials, service: 'es', region: ENV.fetch('AWS_ELASTICSEARCH_REGION')
end
Elasticsearch::Model.client = client
It turns out that there were two parts to this issue.
First, the Elasticsearch::Client, as configured above, was using the default ES port 9200. My ES is hosted on AWS, which appears to not expose this port.
After fixing this, I ran into the second issue (which I suspect is more specific to this app). I started getting a Faraday::ConnectionFailed (end of file) error. I don't know what caused this, but configuring the client with host and scheme fixed it.
My final config is as follows:
#initializers/elasticsearch.rb
# ...
config = {
host: ENV.fetch('AWS_ELASTICSEARCH_URL'),
port: 443,
scheme: "https",
retry_on_failure: true,
transport_options: {
request: { timeout: 10 }
}
}
client = Elasticsearch::Client.new( config ) do |f|
# ...
N.B. AWS_ELASTICSEARCH_URL must return a URL without protocol.
This is because of version issue.
Use this gem 'elasticsearch-model', '~> 5'
I am running few docker container on aws ecs, All running on php Yii application.
the apps needs to connect to AWS RDS database. currently the databasename, host,username and password is hardcoded in the file "main-local.php"
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=dbinstancename.xxxxx.region.rds.amazonaws.com;dbname=xxxxxxx',
'username' => 'xxxxxxxx',
'password' => 'xxxxxxxx',
'charset' => 'utf8',
],
I know its not best practice to hardcode the database details in the docker container. I can pass environment variables into the docker at run time such that "DB_HOST","DB_NAME", "DB_USER","DB_PASSWORD" with the corresponding values. I can see the same details inside the docker container typing the command "env"
How can this be used in the main-local.php? can we directly substitute the db details in the code with the env variables? Is this something to be done from the developers end?
To add env support you may use this extension https://github.com/vlucas/phpdotenv
Simply install it
composer.phar require vlucas/phpdotenv
Create .env file. It should be in .gitignore and not accessed from web. If you are using basic or advanced templates put it with yii.bat into the project root. Also you may create .env.example with empty variables.
YII_DEBUG=1
YII_TRACE_LEVEL=3
YII_ENV=dev
Then add it to your index.php like this
require_once __DIR__ . '/protected/vendor/autoload.php';
$factory = new Dotenv\Environment\DotenvFactory([
new Dotenv\Environment\Adapter\EnvConstAdapter(),
]);
// Specify path to directory with .env file here (for advanced you should up twice)
\Dotenv\Dotenv::create(__DIR__ . DIRECTORY_SEPARATOR . '/../', null, $factory)->load();
defined('YII_DEBUG') or define('YII_DEBUG', (bool) $_ENV['YII_DEBUG']);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', $_ENV['YII_TRACE_LEVEL']);
defined('YII_ENV') or define('YII_ENV', $_ENV['YII_ENV']);
I recommend to use only EnvConstAdapter. Cause $_SERVER variable get logged and getenv() some time has empty values on concurrency requests.
Small improvement for bool, null and empty strings. Add this before $factory instantiation and use env() instead $_ENV.
if (!function_exists('env')) {
/**
* Gets the value of an environment variable.
* #param string $key
* #param mixed $default
* #return mixed
*/
function env($key, $default = null)
{
if (!isset($_ENV[$key])) {
return $default;
}
$value = $_ENV[$key];
switch ($value) {
case 'true':
case '(true)':
return true;
case 'false':
case '(false)':
return false;
case 'empty':
case '(empty)':
return '';
case 'null':
case '(null)':
return null;
default:
return $value;
}
}
}
I was trying to connect to MySQL database in Flutter application using sqljocky5 using the below code using dart language
void getInfo () async {
var pool = new ConnectionPool(
host: 'localhost',
port: 3305,
user: 'root',
password: 'mysql',
db: 'smartlender',
max :5
);
print('test');
var results = await pool.query('SELECT employee.firstName FROM smartlender.employee;'); // exception is thrown here
results.forEach((row){ // for each loop to add data to the list created above
names.add(row[0].toString());
});
Then I received this exception:
I have working connection to MySQL database and the query is exiting without an error .
I appreciate a lot if someone could resolve this issue .
Isn't it default Mysql port number 3306?
I am trying to create a sub-domain using Route53 with aws-php-sdk.
but I am getting this error again and again:
[2017-06-16 12:17:00] local.ERROR: Aws\Exception\CredentialsException: Error retrieving credentials from the instance profile metadata server.
(cURL error 7: Failed to connect to 169.254.169.254 port 80: No route to host (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)) in /var/www/html/test/vendor/aws/aws-sdk-php/src/Credentials/InstanceProfileProvider.php:79
I am using aws-sdk-php version: 3.29
"aws/aws-sdk-php": "^3.29"
Here is my written code
use Aws\Route53\Route53Client;
$client = Route53Client::factory(array(
'region' => 'us-east-1',
'version' => '2013-04-01',
'credentials ' => array('key'=>'AWS_KEY',
'secret'=>'AWS_SECRET_KEY')
));
$result = $client->changeResourceRecordSets(array(
// HostedZoneId is required
'HostedZoneId' => 'ROUTER_53_HOSTED_ZONE_ID',
// ChangeBatch is required
'ChangeBatch' => array(
// Changes is required
'Changes' => array(
array(
// Action is required
'Action' => 'CREATE',
// ResourceRecordSet is required
'ResourceRecordSet' => array(
// Name is required
'Name' => 'test2.xyz.co.in.',
// Type is required
'Type' => 'A',
'TTL' => 600,
"AliasTarget"=> array(
"HostedZoneId"=> "LOAD_BALANCER_ZONE_ID",
"DNSName"=> "LOAD_BALANCER_DOMAIN_NAME",
"EvaluateTargetHealth"=> false
),
),
),
),
),
));
Help will be appreciable. Thanks in advance.
This question is very old but I want to drop an answer in case someone has a similar issue.
The AWS PHP SDK needs credentials to communicate with AWS. the credentials are known as access key ID and secret access key.
As highlighted in AWS documentation
If you do not provide credentials to a client object at the time of its instantiation, the SDK will attempt to find credentials in your environment.
According to your logs it seems that the SDK is still pulling credentials from your environment which are stored in ~/.aws/credentials, and not using the provided keys.
Either make sure you have the access key and the secret key in your environment variable.
$ less ~/.aws/credentials
[default]
aws_access_key_id = key
aws_secret_access_key = secret
Or
Clear the configuration cache to force using the explicit credentials declared in the instantiation of your client. in case they were cached.
php artisan config:cache
Also refer to this documentation on how to properly setup a client.
https://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/credentials.html
If you use
php artisan config:cache
make sure you don't use env() helper for accessing env variables from anywhere except the config files (config/*). Avoid using env() helper in your blade templates. This is because, calling env() helper after the above command is run, will return null.
Instead use a config file for accessing env values. If a separate config file under the config folder is not available for that vendor package / service, The config/services.php is a good place to point to env values.
Thephp artisan config:cache command will speed up your app as the the env variables are cached and so is recommended in a production environment.
Refer Laravel Configuration Caching for more details.