[Spike] cdktf
契機はこちら↓の記事の発見
気にはなってたのと、ちょうど昨日今日から小規模構築案件やるのでこれでいってみようかなと。
(手段は全面的におまかせになっている。「これだけは」が少々あるものの。)
これもありがたい。
周辺?整備
anyenv-update
~/Temp
❯ mkdir -p $(anyenv root)/plugins
~/Temp
❯ git clone https://github.com/znz/anyenv-update.git $(anyenv root)/plugins/anyenv-update
Cloning into '/Users/sogaoh/.anyenv/plugins/anyenv-update'...
remote: Enumerating objects: 87, done.
remote: Total 87 (delta 0), reused 0 (delta 0), pack-reused 87
Receiving objects: 100% (87/87), 13.33 KiB | 100.00 KiB/s, done.
Resolving deltas: 100% (33/33), done.
~/Temp
❯ anyenv update
Skipping 'anyenv'; not git repo
Updating 'anyenv/anyenv-update'...
Updating 'goenv'...
| From https://github.com/syndbg/goenv
| 0fb2fb4..f2acd3c master -> origin/master
Skipping 'goenv/go-build'; not git repo
Updating 'nodenv'...
| From https://github.com/nodenv/nodenv
| 631d0b6..acf64b3 master -> origin/master
Updating 'nodenv/node-build'...
| From https://github.com/nodenv/node-build
| 5e126125..8eb08bb0 master -> origin/master
| * [new tag] v4.9.89 -> v4.9.89
| * [new tag] v4.9.82 -> v4.9.82
| * [new tag] v4.9.83 -> v4.9.83
| * [new tag] v4.9.84 -> v4.9.84
| * [new tag] v4.9.85 -> v4.9.85
| * [new tag] v4.9.86 -> v4.9.86
| * [new tag] v4.9.87 -> v4.9.87
| * [new tag] v4.9.88 -> v4.9.88
Updating 'nodenv/nodenv-vars'...
Updating 'rbenv'...
| From https://github.com/rbenv/rbenv
| c6cc0a1..c4395e5 master -> origin/master
Updating 'rbenv/ruby-build'...
| From https://github.com/rbenv/ruby-build
| 58cda90..a9ed743 master -> origin/master
| * [new tag] v20220710 -> v20220710
| * [new tag] v20220713 -> v20220713
| * [new tag] v20220721 -> v20220721
| * [new tag] v20220725 -> v20220725
| * [new tag] v20220726 -> v20220726
| * [new tag] v20220825 -> v20220825
Updating 'anyenv manifest directory'...
~/Temp 9s
node 16.17.0 を入れられるようになった
bun
❯ curl https://bun.sh/install | bash
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 5649 0 5649 0 0 16817 0 --:--:-- --:--:-- --:--:-- 17275
######################################################################## 100.0%
bun was installed successfully to ~/.bun/bin/bun
Added "~/.bun/bin" to $PATH in "~/.zshrc"
To get started, run:
exec /bin/zsh
bun --help
~
❯
~/.zshrc リロードを意図してターミナル切り替えてインストール確認
❯ bun --help
--use <STR> Choose a framework, e.g. "--use next". It checks first for a package named "bun-framework-packagename" and then "packagename".
--bunfile <STR> Use a .bun file (default: node_modules.bun)
--server-bunfile <STR> Use a .server.bun file (default: node_modules.server.bun)
--cwd <STR> Absolute path to resolve files & entry points from. This just changes the process' cwd.
-c, --config <PATH>? Config file to load bun from (e.g. -c bunfig.toml
--disable-react-fast-refresh Disable React Fast Refresh
--disable-hmr Disable Hot Module Reloading (disables fast refresh too)
--extension-order <STR>... defaults to: .tsx,.ts,.jsx,.js,.json
--jsx-factory <STR> Changes the function called when compiling JSX elements using the classic JSX runtime
--jsx-fragment <STR> Changes the function called when compiling JSX fragments
--jsx-import-source <STR> Declares the module specifier to be used for importing the jsx and jsxs factory functions. Default: "react"
--jsx-production Use jsx instead of jsxDEV (default) for the automatic runtime
--jsx-runtime <STR> "automatic" (default) or "classic"
--main-fields <STR>... Main fields to lookup in package.json. Defaults to --platform dependent
--no-summary Don't print a summary (when generating .bun
-v, --version Print version and exit
--platform <STR> "browser" or "node". Defaults to "browser"
--public-dir <STR> Top-level directory for .html files, fonts or anything external. Defaults to "<cwd>/public", to match create-react-app and Next.js
--tsconfig-override <STR> Load tsconfig from path instead of cwd/tsconfig.json
-d, --define <STR>... Substitute K:V while parsing, e.g. --define process.env.NODE_ENV:"development". Values are parsed as JSON.
-e, --external <STR>... Exclude module from transpilation (can use * wildcards). ex: -e react
-h, --help Display this help and exit.
-i, --inject <STR>... Inject module at the top of every file
-l, --loader <STR>... Parse files with .ext:loader, e.g. --loader .js:jsx. Valid loaders: jsx, js, json, tsx, ts, css
-u, --origin <STR> Rewrite import URLs to start with --origin. Default: ""
-p, --port <STR> Port to serve bun's dev server on. Default: "3000"
--silent Don't repeat the command for bun run
-------
bun: a fast bundler, transpiler, JavaScript Runtime and package manager for web software.
dev ./a.ts ./b.jsx Start a bun Dev Server
bun ./a.ts ./b.jsx Bundle dependencies of input files into a .bun
init Start an empty Bun project from a blank template
create next ./app Create a new project from a template (bun c)
run test Run JavaScript with bun, a package.json script, or a bin
install Install dependencies for a package.json (bun i)
add wrangler Add a dependency to package.json (bun a)
link Link an npm package globally
remove browserify Remove a dependency from package.json (bun rm)
unlink Globally unlink an npm package
upgrade Get the latest version of bun
completions Install shell completions for tab-completion
discord Open bun's Discord server
help Print this help menu
~
❯
❯ bun --version
0.1.10
yarn
❯ yarn
yarn install v1.22.19
info No lockfile found.
warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.
[1/5] 🔍 Validating package.json...
[2/5] 🔍 Resolving packages...
[3/5] 🚚 Fetching packages...
[4/5] 🔗 Linking dependencies...
[5/5] 🔨 Building fresh packages...
success Saved lockfile.
✨ Done in 32.48s.
前提確認
❯ cat .node-version
v16.17.0
❯ node -v
v16.17.0
❯ cat .terraform-version
v1.2.8
❯ terraform --version
Terraform v1.2.8
on darwin_arm64
cdktf cli インストール
実は3回目
❯ npm install --global cdktf-cli@latest
changed 282 packages, and audited 335 packages in 21s
26 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
23s
cdktf init
❯ cdktf init --template=typescript --local
Note: By supplying '--local' option you have chosen local storage mode for storing the state of your stack.
This means that your Terraform state file will be stored locally on disk in a file 'terraform.<STACK NAME>.tfstate' in the root of your project.
? Project Name ts-cdktf
? Project Description A simple getting started project for cdktf.
? Do you want to start from an existing Terraform project? No
? Do you want to send crash reports to the CDKTF team? See https://www.terraform.io/cdktf/create-and-deploy/configuration-file#enable-crash-reporting-for-the-cli for more information Yes
added 2 packages, and audited 57 packages in 758ms
5 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
added 376 packages, and audited 433 packages in 22s
35 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
========================================================================================================
Your cdktf typescript project is ready!
cat help Print this message
Compile:
npm run get Import/update Terraform providers and modules (you should check-in this directory)
npm run compile Compile typescript code to javascript (or "npm run watch")
npm run watch Watch for changes and compile typescript in the background
npm run build Compile typescript
Synthesize:
cdktf synth [stack] Synthesize Terraform resources from stacks to cdktf.out/ (ready for 'terraform apply')
Diff:
cdktf diff [stack] Perform a diff (terraform plan) for the given stack
Deploy:
cdktf deploy [stack] Deploy the given stack
Destroy:
cdktf destroy [stack] Destroy the stack
Test:
npm run test Runs unit tests (edit __tests__/main-test.ts to add your own tests)
npm run test:watch Watches the tests and reruns them on change
Upgrades:
npm run upgrade Upgrade cdktf modules to latest version
npm run upgrade:next Upgrade cdktf modules to latest "@next" version (last commit)
Use Providers:
You can add prebuilt providers (if available) or locally generated ones using the add command:
cdktf provider add "aws@~>3.0" null kreuzwerker/docker
You can find all prebuilt providers on npm: https://www.npmjs.com/search?q=keywords:cdktf
You can also install these providers directly through npm:
npm install @cdktf/provider-aws
npm install @cdktf/provider-google
npm install @cdktf/provider-azurerm
npm install @cdktf/provider-docker
npm install @cdktf/provider-github
npm install @cdktf/provider-null
You can also build any module or provider locally. Learn more https://cdk.tf/modules-and-providers
========================================================================================================
1m 0s
cdktf provider add "aws@~>4.0"
❯ cdktf provider add "aws@~>4.0"
Checking whether pre-built provider exists for the following constraints:
provider: aws
version : ~>4.0
language: typescript
cdktf : 0.12.2
Found pre-built provider.
Adding package @cdktf/provider-aws @ 9.0.21
Installing package @cdktf/provider-aws @ 9.0.21 using npm.
Package installed.
11s
npm install @cdktf/provider-aws
❯ npm install @cdktf/provider-aws
added 376 packages, and audited 434 packages in 2s
35 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
backend に s3 を
はじめての cdktf diff
たぶんダメだろうと思ってたがやっぱり(expireしてた)
❯ cdktf diff
[2022-09-03T21:12:04.122] [INFO] default - Error reporting disabled: SENTRY_DSN not set
ts-cdktf Initializing the backend...
⠋ Processing
[2022-09-03T21:12:12.656] [ERROR] default - ╷
│ Error: error configuring S3 Backend: no valid credential sources for S3 Backend found.
│
│ Please see https://www.terraform.io/docs/language/settings/backends/s3.html
│ for more information about providing credentials.
│
│ Error: ExpiredToken: The security token included in the request is expired
│ status code: 403, request id: ff1b0afb-24be-42d3-9f1d-af9d50070f7c
│
│
│
╵
ts-cdktf ╷
│ Error: error configuring S3 Backend: no valid credential sources for S3 Backend found.
│
│ Please see https://www.terraform.io/docs/language/settings/backends/s3.html
│ for more information about providing credentials.
│
│ Error: ExpiredToken: The security token included in the request is expired
│ status code: 403, request id: ff1b0afb-24be-42d3-9f1d-af9d50070f7c
│
│
│
╵
⠋ Processing
External Error: Stack failed to plan: ts-cdktf. Please check the logs for more information.
やりなおし (妥当そうな結果)
❯ cdktf diff
[2022-09-03T21:26:55.464] [INFO] default - Error reporting disabled: SENTRY_DSN not set
ts-cdktf Initializing the backend...
ts-cdktf
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
ts-cdktf Initializing provider plugins...
ts-cdktf - Finding hashicorp/aws versions matching "4.29.0"...
ts-cdktf - Installing hashicorp/aws v4.29.0...
ts-cdktf - Installed hashicorp/aws v4.29.0 (signed by HashiCorp)
ts-cdktf Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
ts-cdktf Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
ts-cdktf No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration
and found no differences, so no changes are needed.
``` 22s
module の init は cdktf get
とおぼえた
( package.json に get script が用意されてるので yarn get
or bun run get
も可)
module 追加記述
"terraformModules": [
{
"name": "s3",
"source": "terraform-aws-modules/s3-bucket/aws"
},
{
"name": "cloudfront",
"source": "terraform-aws-modules/cloudfront/aws"
}
],
後継や運用者へのガイド、とりあえずこんな感じかな、と思っている
手順 (cdktf 使用)
cd /path/to/ts-cdktf
node,yarn バージョン設定
nodenv local 16.17.0
node -v
yarn
yarn -v
依存関係インストール
yarn install # or bun install
yarn get # or bun run get
plan
cdktf diff
apply
cdktf deploy
test
yarn test
はじめての cdktf deploy 成功したんだけど・・・
これの結果のS3リソースとなんというかいったりきたりして設定値確認してたら、us-east-1 リージョンにできちゃった(のではじめての destroy も経験した)のと、 S3 class のコンストラクタで名前指定したらそれがバケット名になってくれると思い込んでいて、できたらテキトーな terraform-YYYYMMDDHHMMSS00000000001 みたいな名前になってたので明示的に bucket を指定した。。
という、早くも2回 destroy をやりました w
us-east-1 リージョンにできちゃったのは SSO がらみで手順を雑にやっていたのがあるとは思うが diff の段階でどこのリージョンにできるかを確認したいところ、とは思った。(known after apply
だけじゃわからん・・・)
Memo