使用CircleCI处理Terraform
请参考
目录结构
yuta add-subnet ~ aws-terraform tree -a -L 2
.
├── .circleci
│ └── config.yml
├── .git
│ ├── COMMIT_EDITMSG
│ ├── FETCH_HEAD
│ ├── HEAD
│ ├── ORIG_HEAD
│ ├── branches
│ ├── config
│ ├── description
│ ├── hooks
│ ├── index
│ ├── info
│ ├── logs
│ ├── objects
│ ├── packed-refs
│ └── refs
├── .gitignore
├── .terraform
│ └── providers
├── .terraform.lock.hcl
├── README.md
└── main.tf
-
- terraformはVPCを作るだけのもの
- s3にremote stateをセットできるようにしておく
provider "aws" {
region = "ap-northeast-1"
profile = "yuta"
}
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 3.36.0"
}
}
backend "s3" {
bucket = "vamdemic-circleci"
region = "ap-northeast-1"
profile = "yuta"
key = "terraform.tfstate"
encrypt = true
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
tags = {
Name = "circleci-test-vpc"
}
}
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
tags = {
Name = "Main"
}
}
准备好
创建适用于CircleCI的配置文件。
version: 2.1
orbs:
terraform: "circleci/terraform@2.1.0"
workflows:
deploy_infrastructure:
jobs:
- terraform/fmt:
checkout: true
context: terraform
- terraform/validate:
checkout: true
context: terraform
requires:
- terraform/fmt
- terraform/plan:
checkout: true
context: terraform
persist-workspace: true
requires:
- terraform/validate
- terraform/apply:
attach-workspace: true
context: terraform
filters:
branches:
only: main
requires:
- terraform/plan
将AWSCredencial配置到CircleCI的环境变量中。
-
- CircleCI上で作成したプロジェクトでProject Settingsを選び入力する
-
- それぞれ次の通りそのまま入力する
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
今回の場合、指定した資格情報がterraform plan,applyのときに利用される
预先设置上下文
尝试
在 main.tf 中添加
resource "aws_subnet" "private" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.2.0/24"
tags = {
Name = "private"
}
}
将更改推送到远程分支
git checkout -b add-subnet
git commit -m "init"
git push
执行结果
将其合并到主分支
在中文中重新运行CircleCI
-
- といのは、以下の記述があるから
ブランチがmainのときのみterraform applyが実行されるということ
- terraform/apply:
attach-workspace: true
context: terraform
filters:
branches:
only: main