Laravelからazure mysqlに接続する

.env.production

APP_ENV=production
APP_DEBUG=true
APP_KEY

DB_CONNECTION=mysql
DB_HOST=namysql.database.windows.net
DB_DATABASE=sampledb
DB_USERNAME=adminuser@namysql
DB_PASSWORD=hoge
MYSQL_SSL=true

vagrant config/database.php
追加

'sslmode' => env('DB_SSLMODE', 'prefer'),
    'options' => (env('MYSQL_SSL')) ? [
        PDO::MYSQL_ATTR_SSL_KEY    => '/ssl/BaltimoreCyberTrustRoot.crt.pem', 
    ] : []

migrateします。あら、いいですね!?

php artisan migrate --env=production --force
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2015_10_27_141258_create_tasks_table
Migrated:  2015_10_27_141258_create_tasks_table

applicationkeyを作成

php artisan key:generate --env=production --force

vagrantでサーバーを起動する。
php artisan serve –env=production –host 0.0.0.0

!?
RuntimeException in Encrypter.php line 43:
The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.

うまくいかないので、別の方法を探します。

Azure Mysqlにfirewallを設定して、接続する

ここで、idアドレスを指定します。

az mysql server firewall-rule create --name allIPs --server namysql --resource-group myResourceGroup --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255

{
  "additionalProperties": {},
  "endIpAddress": "255.255.255.255",
  "id": "/subscriptions/hogehoge/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/namysql/firewallRules/allIPs",
  "name": "allIPs",
  "resourceGroup": "myResourceGroup",
  "startIpAddress": "0.0.0.0",
  "type": "Microsoft.DBforMySQL/servers/firewallRules"
}

vagrantから接続する

[vagrant@localhost ~]$ mysql -u adminuser@namysql -h namysql.database.windows.net -P 3306 -p

Azureにcloud shellでMySQLサーバーを作成する

cloud shellを開き、mysql serverをcreateします。

az mysql server create --name mysql --resource-group myResourceGroup --location "North Europe" --admin-user adminuser --admin-password hogehoge

エラー

az mysql server create: error: the following arguments are required: --sku-name

–sku-name
The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8.

なに?

クイックスタートをみて、–sku-name GP_Gen4_2 –version 5.7を追加します。

az mysql server create --name mysql --resource-group myResourceGroup --location "North Europe" --admin-user adminuser --admin-password hogehoge --sku-name GP_Gen4_2 --version 5.7

GP_Gen4_2は仮想コア2つのようです。2つもいらないな。と思ったら、こちらにスペック一覧があります。
https://docs.microsoft.com/ja-jp/azure////sql-database/sql-database-vcore-resource-limits

最大データ サイズ (GB) 1024 って記載がありますね。
いつも、mysqlにどれ位のデータサイズが入るのか気になっていましたが、1024Gですか。。
varchar255で1bit、1億レコードで10GBくらいでしょうから、これ相当入りますね。相当凄い!

と思ったら、またエラー

Deployment failed. Correlation ID: xxxx-xxxx. Specified server name is already used.

さすがに、グローバルな名前で–name mysql はなかったですね(笑) ひどい。

やり直します。cloud shellにパスワードが表示されるのはだめですね。
来た!MySQL5.7 これ、どういうことなんだろう?locationが選択できる(今回はnortheurope)ってことは、仮想マシンVMの中にmysqlをインストールしているわけではなくて、指定したlocationにつくっているってこと?VMの中に入れた方がrequest responseの通信距離が短くて効率的な気がするのですが。。よくわからないです。

t@Azure:~$ az mysql server create --name namysql --resource-group myResourceGroup --location "North Europe" --admin-user adminuser --admin-password hogehoge --sku-name GP_Gen4_2 --version 5.7
{
  "additionalProperties": {},
  "administratorLogin": "adminuser",
  "earliestRestoreDate": "2018-04-21T00:34:32.223000+00:00",
  "fullyQualifiedDomainName": "namysql.mysql.database.azure.com",
  "id": "/subscriptions/hoge/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/namysql",
  "location": "northeurope",
  "name": "namysql",
  "resourceGroup": "myResourceGroup",
  "sku": {
    "additionalProperties": {},
    "capacity": 2,
    "family": "Gen4",
    "name": "GP_Gen4_2",
    "size": null,
    "tier": "GeneralPurpose"
  },
  "sslEnforcement": "Enabled",
  "storageProfile": {
    "additionalProperties": {},
    "backupRetentionDays": 7,
    "geoRedundantBackup": "Disabled",
    "storageMb": 5120
  },
  "tags": null,
  "type": "Microsoft.DBforMySQL/servers",
  "userVisibleState": "Ready",
  "version": "5.7"
}

azure mysql tutorial

まず、vagrant mysqlにcreate table

CREATE DATABASE sampledb;

tutorial用のファイル群をgit clone

git clone https://github.com/Azure-Samples/laravel-tasks
cd laravel-tasks
composer install

laravelのルートに.env ファイルをつくる

APP_ENV=local
APP_DEBUG=true
APP_KEY=

DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=sampledb
DB_USERNAME=root
DB_PASSWORD=hoge

あれ、.envファイルって何でしょう?
.envファイル:.env ファイルを使用して、ユーザーは個人の作業環境変数をカスタマイズすることができる
>envファイルは、アプリケーションのソースコントロールに含めるべきでありません。各ユーザー/サーバは異なった環境設定が必要だからです。さらに、侵入者がソースコントロールリポジトリへアクセスすることが起きれば、機密性の高い情報が漏れてしまうセキュリティリスクになります。

なるほど、gitでpushしないようにってことですね。
migrationします。

[vagrant@localhost laravel-tasks]$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrating: 2015_10_27_141258_create_tasks_table
Migrated: 2015_10_27_141258_create_tasks_table

ほー

php artisan key:generate
php artisan serve


あれ、ipが127.0.0.1になってる。。192.168.33.10:8000にしないといけないのに。

なにーーーー

再度git push

まず、azure用のdirectoryを作成し、git initします。

mkdir azure
cd azure
git init
git add *
git commit -m "initial commit"

azureにpushするファイルを作成します。
index.php

hello world

リモートリポジトリの設定をします。

[vagrant@localhost azure]$ git remote add azure https://hoge@nanalytics.scm.azurewebsites.net/nanalytics.git
[vagrant@localhost azure]$ git push azure master

vagrantでphpサーバーを立てます。

azureにトラッキングコードタグの入ったphpファイルをpushします。

</style>
<body>
    <div class="box"></div>
</body>
<script type="text/javascript">
    var a = [['acount','007'],["ip","<?php echo $_SERVER&#91;'REMOTE_ADDR'&#93;; ?>"]];
    var b =['https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js', 'http://192.168.33.10:8000/na.js'];
    var i = 0;
    (function appendScript(){
        var script = document.createElement('script');
        script.src = b[i];
        document.body.appendChild(script);
        if(i++ < 2){
            script.onload = appendScript;
        }
    })();
</script>

commit、pushします。

[vagrant@localhost azure]$ git commit -am "second"
[master a1cf4be] second
 1 file changed, 23 insertions(+), 1 deletion(-)
 rewrite index.php (100%)
[vagrant@localhost azure]$ git push azure master

あああああああああああああ
azureからvagrant環境(192.168.33.10:8000)のjsには接続できない。。
しまったーーー 渾身のミス

VPSにmongoDB入れるか?
でもazureでのdb接続の方が先ですね。

azureにgit push

[vagrant@localhost php-docs-hello-world]$ git remote add azure https://name@hpscript.scm.azurewebsites.net/hpscript.git
[vagrant@localhost php-docs-hello-world]$ git push azure master
Password for ‘https://name@hpscript.scm.azurewebsites.net’:
Counting objects: 13, done.
Compressing objects: 100% (11/11), done.
Writing objects: 100% (13/13), 2.07 KiB | 0 bytes/s, done.
Total 13 (delta 2), reused 0 (delta 0)
remote: Updating branch ‘master’.
remote: Updating submodules.
remote: Preparing deployment for commit id ‘cc39b1e4cb’.
remote: Generating deployment script.
remote: Generating deployment script for Web Site
remote: Generated deployment script files
remote: Running deployment command…
remote: Handling Basic Web Site deployment.
remote: KuduSync.NET from: ‘D:\home\site\repository’ to: ‘D:\home\site\wwwroot’
remote: Deleting file: ‘hostingstart.html’
remote: Copying file: ‘.gitignore’
remote: Copying file: ‘index.php’
remote: Copying file: ‘LICENSE’
remote: Copying file: ‘README.md’
remote: Finished successfully.
remote: Running post deployment command(s)…
remote: Deployment successful.
To https://name@hpscript.scm.azurewebsites.net/hpscript.git
* [new branch] master -> master

なんじゃこりゃー
昇天しそうだ。頭で必死に計算してるけど、追い付かない。

とりあえず優先的な重要事項は
1.今後はVPS・共有サーバーは使わずに、auzreかawsに構築していく
2.azurewebsites.netではなく、独自ドメインの場合の設定方法

1、2共に重要!

ほう

なるほど、では、復讐を兼ねて、vagrant側でphp server, mongoDBに接続して、azure(hoge.azurewebsites.net)にトラッキングコードを入力したhtmlファイルをデプロイ・アクセスして、しっかりトラッキングがviewに反映されるか作ってみたいと思います。

azureにweb appを作成する

already existsって、そんなアホな。。phpはversionは指定するそうです。
そりゃそうだよね。

t@Azure:~$ az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name analytics --runtime "PHP|7.0" --deployment-local-git
Website with given name analytics already exists.
t@Azure:~$ az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name hpscript --runtime "PHP|7.0" --deployment-local-git

json
host nameができてます。しかも、これSSLですね。あ、これは凄い!
json読むと、webrootがファイルディレクトのパスっぽいです。

Local git is configured with url of ‘https://hoge.scm.azurewebsites.net/hpscript.git’
{
“additionalProperties”: {},
“availabilityState”: “Normal”,
“clientAffinityEnabled”: true,
“clientCertEnabled”: false,
“cloningInfo”: null,
“containerSize”: 0,
“dailyMemoryTimeQuota”: 0,
“defaultHostName”: “hpscript.azurewebsites.net”,
“deploymentLocalGitUrl”: “https://hoge.scm.azurewebsites.net/hpscript.git”,
“enabled”: true,
“enabledHostNames”: [
“hpscript.azurewebsites.net”,
“hpscript.scm.azurewebsites.net”
],
“ftpPublishingUrl”: “ftp://waws-prod-am2-187.ftp.azurewebsites.windows.net/site/wwwroot”,
“hostNameSslStates”: [
{
“additionalProperties”: {
“ipBasedSslResult”: null,
“ipBasedSslState”: “NotConfigured”,
“toUpdateIpBasedSsl”: null
},
“hostType”: “Standard”,
“name”: “hpscript.azurewebsites.net”,
“sslState”: “Disabled”,
“thumbprint”: null,
“toUpdate”: null,
“virtualIp”: null
},
{
“additionalProperties”: {
“ipBasedSslResult”: null,
“ipBasedSslState”: “NotConfigured”,
“toUpdateIpBasedSsl”: null
},
“hostType”: “Repository”,
“name”: “hpscript.scm.azurewebsites.net”,
“sslState”: “Disabled”,
“thumbprint”: null,
“toUpdate”: null,
“virtualIp”: null
}
],
“hostNames”: [
“hpscript.azurewebsites.net”
],
“hostNamesDisabled”: false,
“hostingEnvironmentProfile”: null,
“httpsOnly”: false,
“id”: “/subscriptions/hogehoge/resourceGroups/myResourceGroup/providers/Microsoft.Web/sites/hpscript”,
“identity”: null,
“isDefaultContainer”: null,
“kind”: “app”,
“lastModifiedTimeUtc”: “2018-04-20T13:04:30.993333”,
“location”: “West Europe”,
“maxNumberOfWorkers”: null,
“name”: “hpscript”,
“outboundIpAddresses”: “hoge”,
“possibleOutboundIpAddresses”: “hoge”,
“repositorySiteName”: “hpscript”,
“reserved”: false,
“resourceGroup”: “myResourceGroup”,
“scmSiteAlsoStopped”: false,
“serverFarmId”: “/subscriptions/hogehogehoge/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan”,
“siteConfig”: null,
“slotSwapStatus”: null,
“snapshotInfo”: null,
“state”: “Running”,
“suspendedTill”: null,
“tags”: null,
“targetSwapSlot”: null,
“trafficManagerHostNames”: null,
“type”: “Microsoft.Web/sites”,
“usageState”: “Normal”
}

azure tutrial

まずvagrant

git clone https://github.com/Azure-Samples/php-docs-hello-world
cd php-docs-hello-world
echo "Hello World!";

Azure Cloud Shellを起動

user nameをset

az webapp deployment user set --user-name  --password 

なに!?

{
  "additionalProperties": {},
  "id": null,
  "kind": null,
  "name": "web",
  "publishingPassword": null,
  "publishingPasswordHash": null,
  "publishingPasswordHashSalt": null,
  "publishingUserName": "hoge",
  "type": "Microsoft.Web/publishingUsers/web",
  "userName": null
}

freeレベル
なんでchinaないんだ?なぞだ。

t@Azure:~$ az appservice list-locations --sku FREE
[
  {
    "name": "Central US"
  },
  {
    "name": "North Europe"
  },
  {
    "name": "West Europe"
  },
  {
    "name": "Southeast Asia"
  },
  {
    "name": "East Asia"
  },
  {
    "name": "West US"
  },
  {
    "name": "East US"
  },
  {
    "name": "Japan West"
  },
  {
    "name": "Japan East"
  },
  {
    "name": "East US 2"
  },
  {
    "name": "North Central US"
  },
  {
    "name": "South Central US"
  },
  {
    "name": "Brazil South"
  },
  {
    "name": "Australia East"
  },
  {
    "name": "Australia Southeast"
  },
  {
    "name": "Central India"
  },
  {
    "name": "West India"
  },
  {
    "name": "South India"
  },
  {
    "name": "Canada Central"
  },
  {
    "name": "Canada East"
  },
  {
    "name": "West Central US"
  },
  {
    "name": "West US 2"
  },
  {
    "name": "UK West"
  },
  {
    "name": "UK South"
  },
  {
    "name": "Korea South"
  },
  {
    "name": "Korea Central"
  },
  {
    "name": "France South"
  },
  {
    "name": "France Central"
  }
]

リソースグループを作成
az group create –name myResourceGroup –location “West Europe”
appservice planを作成
az appservice plan create –name myAppServicePlan –resource-group myResourceGroup –sku FREE

{
  "additionalProperties": {},
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/hoge/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "isSpot": false,
  "kind": "app",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  "numberOfSites": 0,
  "perSiteScaling": false,
  "provisioningState": "Succeeded",
  "reserved": false,
  "resourceGroup": "myResourceGroup",
  "sku": {
    "additionalProperties": {},
    "capabilities": null,
    "capacity": 0,
    "family": "F",
    "locations": null,
    "name": "F1",
    "size": "F1",
    "skuCapacity": null,
    "tier": "Free"
  },
  "spotExpirationTime": null,
  "status": "Ready",
  "subscription": "ほげ",
  "tags": null,
  "targetWorkerCount": 0,
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
}

リソース グループ:Web アプリ、データベース、ストレージ アカウントなどの Azure リソースのデプロイと管理に使用する論理コンテナー
デプロイ:主にネットワークを通じて提供されるWebアプリケーションなどのシステム開発工程において、システムを利用可能な状態にする
(1)myresourcegroupをWest Europeに作成
(2)Azure App Service プランの作成 myAppServicePlanというプラン名

app service:
“.NET、.NET Core、Java、Ruby、Node.js、PHP、Python を使用して、強力な Web アプリ、モバイル アプリ、API アプリをすばやく構築できます。Azure App Service を既存のフレームワークに統合して、継続的インテグレーション、ライブサイト デバッグ、および業界最高レベルの Microsoft Visual Studio IDE などの最先端の機能を活用することで、比類ない開発者生産性を実現できます。また、Azure Marketplace から、事前構築済みのアプリ、API、コネクタのエコシステムも活用できます。Visual Studio Team Services、Bitbucket、Docker Hub、および GitHub と統合された CI/CD 機能を使用することで、更新プログラムを簡単にデプロイできます。”
“Azure Web Apps を使用すると、インフラストラクチャを管理することなく、お好きなプログラミング言語で Web アプリケーションを構築してホストすることができます。”

OSがどうなっているかブラックボックスでよくわからんな。
要するに.NET、.NET Core、Java、Ruby、Node.js、PHP、Pythonやそれにつくライブラリーは既にインストールされているってこと?
まずOSのファイル構成が見たいです。