Cloud Function から IAM認証で CloudSQL(PostgreSQL) へ接続する

はじめに クラウド環境でのデータベース管理において、セキュリティは日々進化する脅威への対応が求められる重要課題です。特に、以下の課題が顕在化しています: 従来の認証情報(パスワード)の漏洩リスク 認証情報のローテーション管理の煩雑さ アプリケーション展開時の認証情報受け渡しの安全性確保 これらの課題に対し、IAM認証を活用することで、より強固でかつ運用負荷の少ないセキュリティ体制を実現できます。IAM認証のメリットは以下の通りです: 一時的な認証トークンの利用による漏洩リスクの低減 クラウドプロバイダーの統合認証基盤との連携による管理の一元化 きめ細かなアクセス制御とアクセスログの監査対応 本ガイドでは、Cloud FunctionsからCloudSQL(PostgreSQL)へIAM認証で接続する実践的な手順を解説します。この設定により、セキュアかつスケーラブルなデータベースアクセス環境を構築できます。 Cloud Function から CloudSQL(PostgreSQL) へ IAM 認証で接続するために必要な手順 Cloud Function 用 Service Account に必要な権限を付与 PGUSER の作成(IAM認証用) データベースへの権限付与 Cloud Function の実装 Service Account での Cloud Function のデプロイ 具体的な設定手順 1. Cloud Function 用 Service Account に必要な権限を付与 以下の権限が必要: Cloud SQL インスタンス ユーザー Cloud SQL クライアント 今回はコンソールから設定したが、以下のコマンドで設定も可能: gcloud projects add-iam-policy-binding example-project \ --member="serviceAccount:example-function@example-project.iam.gserviceaccount.com" \ --role="roles/cloudsql.instanceUser" gcloud projects add-iam-policy-binding example-project \ --member="serviceAccount:example-function@example-project.iam.gserviceaccount.com" \ --role="roles/cloudsql.client" 2. PGUSER の作成 IAM認証用のユーザーを作成する。 gcloud sql users create example-function@example-project.iam \ --instance=example-project-fdc \ --type=cloud_iam_service_account PostgreSQLの場合、以下の点に注意が必要: ユーザー名から .gserviceaccount.com を除いた形で作成 タイプは cloud_iam_service_account を指定 MySQL の場合は @project-id.iam.gserviceaccount.com を除いた形で作成する模様 Refs: GoogleCloudPlatform/cloud-sql-nodejs-connector: A JavaScript library for connecting securely to your Cloud SQL instances Postgres: For an IAM user account, this is the user’s email address. For a service account, it is the service account’s email without the .gserviceaccount.com domain suffix. MySQL: For an IAM user account, this is the user’s email address, without the @ or domain name. For example, for test-user@gmail.com , set the user field to test-user. For a service account, this is the service account’s email address without the @project-id.iam.gserviceaccount.com suffix. ...

2025-01-29 ·  2025-01-30 · 3 分 · 515 文字

Ubuntu 14.04 postgresql install

postgresql install sudo apt-get install postgresql sudo apt-get install libpq-dev postgresql settings sudo su postgres -c psql postgres=# CREATE ROLE [user] SUPERUSER LOGIN; postgres=# \password [user] [userpassword] [userpassword] check or list database, tables, indexes, and so on. postgres=# create database [user]; postgres=# select * from pg_user; /* ユーザ一覧 */ postgres=# \d /* 表、インデックスの一覧 */ postgres=# \dt /* 表の一覧 */ postgres=# \d [表名] /* 表の項目一覧 */ postgres=# \l /* データベース一覧、文字コード表示 */ postgres=# \q /* 終了 */ psql -l # データベース 一覧 psql [データベース名] # psql へ切り替え

2014-10-23 ·  2014-10-23 · 1 分 · 85 文字

Ubuntu 14.04 ruby2.1.2 で ActiveRecord4.1.6 を使用し、postgresql4.1.6 へアクセス

まずはdatabase 確認 sudo su postgres -c psql install activerecord,pg mkdir -p ~/works/99_sample/02_activerecord cd ~/works/99_sample/02_activerecord gem install activerecord gem install pg gem list DBユーザtest_nameを作成しておく sudo su postgres -c psql create role test_name superuser login; \password test_name Enter new password: test_name Enter it again: test_name create database test_name; config/database.yml mkdir -p config && vim config/database.yml db: production: adapter: postgresql host: localhost username: test_name password: test_name database: test_name development: adapter: postgresql host: localhost username: test_name password: test_name database: test_name db/migrate配下に、3ファイルを配置(rails環境からコピー) mkdir -p db/migrate ...

2014-10-03 ·  2014-10-03 · 1 分 · 130 文字

Ubuntu 14.04 で websocket, zeroMQ

rails 、postgresql、zeroMQ、websocketを使って通信するサンプル環境を作成中 create rails project cd 任意のディレクトリ rails new test_rails_postgres -d postgresql cd test_rails_postgres bundle install --path vendor/bundle bundle exec rake db:create db:migrate テスト起動確認 cd test_rails_postgres rails server http://[サーバアドレス]:3000へアクセス git 管理開始 cd test_rails_postgres git init vim .gitignore 以下を追加 doc/ *.swp *~ .project .DS_Store .idea .secret git add . git commit -m "initial commit." テスト設定 bundle exec rails generate scaffold book title:string author:string outline:text bundle exec rake db:migrate bundle exec rails server db確認 -- database list \l -- user list select * from pg_user; -- table list \d routes の確認 http://localhost:3000/rails/info/routes rails へwebsocket実装 websocket-rails install cd test_rails_postgres vim Gemfile # 以下を追加 gem 'websocket-rails' bundle install rails g websocket_rails:install # コントローラ作成 vim app/controllers/websocket_chat_controller.rb # WebsocketRails::BaseControllerを継承 class WebsocketChatController < WebsocketRails::BaseController def message_recieve # クライアントからのメッセージを取得 recieve_message = message() # websocket_chatイベントで接続しているクライアントにブロードキャスト broadcast_message(:websocket_chat, recieve_message) end end vim config/events.rb WebsocketRails::EventMap.describe do # websocket_chatイベントのマッピング subscribe :websocket_chat, to: WebsocketChatController, with_method: :message_recieve end # クライアント rails g controller chat index vim app/views/chat/index.html.erb 以下追加 <!-- チャット表示部分 --> <ul id="chat_area"> </ul> <!-- コメントフォーム --> <input id="comment" type="text"> <input id="send" type="button" value="send"> <script> var ws_rails = new WebSocketRails("[url]:3000/websocket"); // メッセージ受信時の処理 ws_rails.bind("websocket_chat", function(message){ var message_li = document.createElement("li"); message_li.textContent = message; document.getElementById("chat_area").appendChild(message_li); }) // メッセージ送信時の処理 document.getElementById("send").onclick = function(){ var comment = document.getElementById("comment").value; ws_rails.trigger("websocket_chat", comment); } </script> vim config/environments/development.rb # 以下を追加 config.middleware.delete Rack::Lock test websocket client作成 gem install gem install websocket-client-simple client program(動かない) vim websocket_client.rb require 'rubygems' require 'websocket-client-simple' ws = WebSocket::Client::Simple.connect '[url]:3000/websocket' ws.on :message do |msg| puts msg.data end ws.on :open do ws.send 'hello!!!' end ws.on :close do |e| p e exit 1 end loop do ws.send STDIN.gets.strip end execjs install(不要) gem install execjs zeromq install cd 任意のディレクトリ git clone https://github.com/zeromq/zeromq4-x.git cd zeromq4-x # git checkout origin/v4.0.1 sudo aptitude install libtool autoconf uuid-dev ./autogen.sh #./configure --prefix=/usr/local/zmq ./configure make sudo make install ZeroMQ導入 vim Gemfile -------------------- # Use zeroMq gem 'rbzmq' #gem 'ffi-rzmq' #gem 'zqm' ffi-rzmqのバージョンが合っている2.0.1が要る? rails コントローラにZMQスレッドを立ち上げる vim websocket_chat_controller.rb --------------------------------------------------- require 'rbzmq' # WebsocketRails::BaseControllerを継承 class WebsocketChatController < WebsocketRails::BaseController context = ZMQ::Context.new publisher = context.socket ZMQ::PUB publisher.bind "tcp://*:5563" begin t = Thread.new do Thread.pass # メインスレッドが確実にjoinするように puts "[rails] Tread loop start." loop do publisher.send_string 'A', ZMQ::SNDMORE publisher.send_string "We don't want to see this." publisher.send_string 'B', ZMQ::SNDMORE publisher.send_string "We would like to see this." sleep 1 end publisher.close raise "unhandled exception" end t.join rescue p $! # => "unhandled exception" end puts "[rails] WebsocketChatController is started!!!!!" def message_recieve # クライアントからのメッセージを取得 recieve_message = message() puts "[rails] server message receive and broadcast => #{recieve_message}" # websocket_chatイベントで接続しているクライアントにブロードキャスト broadcast_message(:websocket_chat, recieve_message) end end rails server立ち上げ bundle exec rails server em-websocket in rails vim websocket_chat_controller.rb require “em-websocket” # 省略 puts “rails emwebsocket server start” # 配列ではなくEventMachineオブジェクトを生成 connections = EM::Channel.new EM::WebSocket.start(host: “172.19.1.94”, port: 3001) do |ws_conn| ws_conn.onopen do puts “connected” # EventMachine#subscribeを用い、コネクションオブジェクトと処理を登録 connections.subscribe{|message| ws_conn.send(message) } end ws_conn.onmessage do |message| # onopen内で登録した処理を呼び出し puts “received:” + message connections.push(message) end end

2014-10-03 ·  2014-10-03 · 3 分 · 454 文字