使用AWS自动化terraform进行环境设置(docker)
想做的事情 zuò de
-
- AWSに立てたCIサーバ(EC2・jenkins)でterraformを叩いてインフラのコード化
-
- terraformはVMの環境に左右されないようコンテナ上で実行
- imageはECRに保存しておく
设计
关于1
先登录AWS,然后进行推送。
#!groovy
pipeline {
agent any
triggers {
pollSCM('H/3 * * * 1-5')
}
//environment {}
stages {
stage('Master Branch <pushing>') {
when {
branch 'master'
}
steps {
ansiColor('xterm') {
echo '<<< start pushing >>>'
sh 'aws ecr get-login --no-include-email --region ap-northeast-1 > temp.sh'
sh '''
echo "***@***.co.jp" | sudo sh temp.sh
sudo docker build -t ***** .
sudo docker tag *****:latest *****.ap-northeast-1.amazonaws.com/*****:latest
sudo docker push *****.ap-northeast-1.amazonaws.com/*****:latest
'''
}
}
}
}
}
FROM python:3.6
ARG TERRAFORM_VERSION=0.10.0
RUN apt-get clean && \
rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/* && \
apt-get update && \
apt-get -y upgrade && \
apt-get install -y --no-install-recommends unzip zip jq ca-certificates curl lsb-release gawk
# install python modules
COPY requirements.txt .
RUN pip install -r requirements.txt
# install Terraform
RUN mkdir /tmp/terraform && \
cd /tmp/terraform && \
curl -O -sS -L https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip && \
unzip terraform_${TERRAFORM_VERSION}_linux_amd64.zip && \
rm terraform_${TERRAFORM_VERSION}_linux_amd64.zip && \
mv terraform* /usr/local/bin && \
rm -rf /tmp/terraform
RUN apt-get clean && \
rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/*
关于2
尝试在Jenkinsfile的agent中指定容器,但失败了
– 在从ECR拉取之前,需要先登录
– 即使尝试使用本地镜像,仍会执行docker pull(alwaysPull false也无效)
愚直地启动容器,然后在内部执行terraform命令。
#!groovy
pipeline {
agent any
triggers {
pollSCM('H/3 * * * 1-5')
}
stages {
stage('Pull Request <Plan>') {
when {
branch 'PR-*'
}
steps {
ansiColor('xterm') {
echo '<<< start planning >>>'
sh "docker run --name tmp-jenkins -id ***** | echo 'ignore failure'"
sh "docker start tmp-jenkins | echo 'ignore failure'"
sh "docker exec tmp-jenkins mkdir /tmp/terraform | echo 'ignore failure'"
sh "docker exec tmp-jenkins rm -rf /tmp/terraform/*"
sh "docker cp ./ tmp-jenkins:/tmp/terraform/"
sh "docker exec tmp-jenkins ls /tmp/terraform/"
sh "docker exec tmp-jenkins sh -c 'cd /tmp/terraform/ && terraform init -backend-config \"bucket=*****\"'"
sh "docker exec tmp-jenkins sh -c 'cd /tmp/terraform/ && terraform env select dev'"
sh "docker exec tmp-jenkins sh -c 'cd /tmp/terraform/ && terraform plan'"
sh "docker exec tmp-jenkins sh -c 'cd /tmp/terraform/ && terraform apply'"
sh "docker stop tmp-jenkins"
}
}
}
}
}
结果 – Jié guǒ
Alternate options:
– 成果 – guǒ
– 后果 – guǒ
– 效果 – guǒ
– 所以 – Suǒ yǐ
-
- ひとまずterraformを動かすことができた
-
- ただ何かを作ろうとするとエラーが出る…
-
- * provider.aws: dial unix /tmp/plugin392670482|netrpc: connect: no such file or directory
あとこれを解決すれば完成… =>terraformを 0.10.0 -> 0.10.8にすることで解決