在我的gatsby网站根目录的buildspec.yml文件中有以下命令。
version: 0.2
phases:
install:
commands:
- npm i npm@latest -g
- npm install --global gatsby-cli
- npm install
- pip install --upgrade pip
- pip install --upgrade awscli
build:
commands:
- gatsby build
post_build:
commands:
- aws s3 sync public/ s3://stagging
我有2个环境,即停滞和生产。有没有一种方法可以使我的同步命令自动化,以便在执行代码构建时使用某种变量来更改环境。也许我可以通过命令行传递环境名称。
答案 0 :(得分:5)
创建代码构建时,您可以传递环境变量。
{
"name": "sample-docker-project",
"source": {
"type": "S3",
"location": "codebuild-region-ID-account-ID-input-bucket/DockerSample.zip"
},
"artifacts": {
"type": "NO_ARTIFACTS"
},
"environment": {
"type": "LINUX_CONTAINER",
"image": "aws/codebuild/docker:17.09.0",
"computeType": "BUILD_GENERAL1_SMALL",
"environmentVariables": [
{
"name": "AWS_DEFAULT_REGION",
"value": "region-ID"
},
{
"name": "AWS_ACCOUNT_ID",
"value": "account-ID"
},
{
"name": "IMAGE_REPO_NAME",
"value": "Amazon-ECR-repo-name"
},
{
"name": "IMAGE_TAG",
"value": "latest"
}
]
},
"serviceRole": "arn:aws:iam::account-ID:role/role-name",
"encryptionKey": "arn:aws:kms:region-ID:account-ID:key/key-ID"
}
您可以在buildspec.yml中使用 $ IMAGE_REPO_NAME 像常规环境变量一样引用它们。
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to Amazon ECR...
- $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION)
build:
commands:
- echo Build started on `date`
- echo Building the Docker image...
- docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
- docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
post_build:
commands:
- echo Build completed on `date`
- echo Pushing the Docker image...
- docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
您不能做的就是仅创建1个代码构建并将变量像脚本一样传递给它,因此您需要创建2个代码构建,但要创建1个buildspec.yml。
更多信息在这里:https://docs.aws.amazon.com/codebuild/latest/userguide/sample-docker.html
答案 1 :(得分:4)
基于documentation,您可以使用以下格式:
env:
variables:
key: "value"
key: "value"
答案 2 :(得分:0)
另一种方法是使用所需的所有配置变量准备脚本和YAML。
脚本文件 yaml_to_envvars.sh (在此处https://stackoverflow.com/a/21189044/2275126进行了修改):
#!/bin/bash
prefix=$2
s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -ne "s|^\($s\):|\1|" \
-e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 |
awk -F$fs '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
printf("conf_%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
}
}'
YAML文件 settings.yml :
common:
key1: value1
dev:
key2: value2
test:
key3: value3
在您的 pre_build 部分 commands 中运行以下命令:
- chmod u+x yaml_to_envvars.sh
- ./yaml_to_envvars.sh settings.yml > variables.env
- |-
for NEWVAR in $(cat variables.env); do
export $NEWVAR
done
然后,您的buildspec中将具有以下可用变量:
$ echo $conf_common_key1
value1
$ echo $conf_dev_key2
value2
$ echo $conf_test_key3
value3