当前位置: 首页 > 工具软件 > Terraform 2 > 使用案例 >

阿里云Terraform实践

陈增
2023-12-01

Terraform环境准备与安装

Golang环境准备

下载Golang安装包

https://golang.org/dl/

清除旧的版本

brew info go
brew uninstall go

安装Golang

  1. 下载pkg,双击确认
  2. 编辑~/.bash_profile
export GOPATH=/Users/sjl/Projects/golang
export PATH=$PATH:$GOPATH/bin

Terraform安装

参考Terraform官方文档:https://learn.hashicorp.com/terraform/getting-started/install.html

On mac OSX

brew install terraform
terraform -help
terraform -install-autocomplete
mkdir -p Projects/terraforms; cd $_
mkdir terraform-docker-demo && cd $_

vi main.tf

resource "docker_image" "nginx" {
  name         = "nginx:latest"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.latest
  name  = "tutorial"
  ports {
    internal = 80
    external = 8000
  }
}
terraform init
terraform plan
terraform apply

访问如下地址,验证运行结果

docker ps
http://localhost:8000/
terraform destroy

Alibaba Terraform Provider

mkdir -p $GOPATH/src/github.com/terraform-providers; cd $_
git clone git@github.com:terraform-providers/terraform-provider-alicloud
cd terraform-provider-alicloud
make build

设置环境变量

设置环境变量,省去每次测试时输入AK的要求


运行

Terraform阿里云

创建RAM用户并授权

为提高权限管理的灵活性和安全性,建议您创建RAM用户,并为其授权。
登录 RAM控制台。
创建名为Terraform的RAM用户,并为该用户创建AccessKey。具体步骤请参见创建RAM用户。
为RAM用户授权。具体步骤请参见为RAM用户授权。

export ALICLOUD_ACCESS_KEY=xxx
export ALICLOUD_SECRET_KEY=xxx
export ALICLOUD_REGION=xxx
export ALICLOUD_ACCOUNT_ID=xxx
export ALICLOUD_RESOURCE_GROUP_ID=xxx
export outfile=gotest.out
TF_ACC=1 TF_LOG=INFO go test ./alicloud -v -run=TestAccAlicloud -timeout=1440m | tee $outfile
go2xunit -input $outfile -output $GOPATH/tests.xml

# If your account belongs to domestic site
export ALICLOUD_ACCOUNT_SITE=Domestic

# If your account belongs to international site
export ALICLOUD_ACCOUNT_SITE=International

vi setenv.sh

export ALICLOUD_ACCESS_KEY="LTAIUrZCw3********"
export ALICLOUD_SECRET_KEY="zfwwWAMWIAiooj14GQ2*************"
export ALICLOUD_REGION="cn-beijing"

vi unsetenv.sh

unset ALICLOUD_ACCESS_KEY
unset ALICLOUD_SECRET_KEY
unset ALICLOUD_REGION
chmod 600 setenv.sh
chmod 600 unsetenv.sh
source setenv.sh
terraform apply
terraform show
terraform destroy

参考资料

[1] https://github.com/terraform-providers/terraform-provider-alicloud
[2] https://help.aliyun.com/document_detail/95825.html?spm=a2c4g.11186623.2.14.123240f2MaAtuZ#task-bts-tlz-dfb
[3] https://www.terraform.io/docs/configuration/index.html
[4] https://www.jianshu.com/p/1745e64f07e9

 类似资料: