2017-01-24 5 views
0

Google에서는 terraform을 Google 조직에서 광범위하게 사용하고 있으며 다른 사람들이 VPC 피어링을 수행하는 방법에 대해 몇 가지 질문을했습니다. 초기 연결 생성은 쉽습니다. 우리는 방금 생성 한 VPC에서 다른 VPC를 참조하여 경로 표 등을 채 웁니다. 문제는 방금 피어링 한 VPC 때문입니다. 우리는 이제 수동으로 다른 네트워킹 스택으로 가서 CIDR/PCX ID를 수동으로 변수로 추가해야합니다. 나는이 스크립트를 좀 더 쉽게 처리 할 수있는 스크립트를 작성했지만 기존 VPC에 대해 AWS에 대한 조회를 동적으로 수행하고 기존 PCX를 자동으로 VPC의 라우팅 테이블에 추가하는지 묻고 싶습니다.Terraform 및 VPC 피어링

OPS VPC에서 유용하게 활용할 수있는 예는 다음과 같습니다. 우리는 OPS와 dev, prod, qa, stg, uat, cte 등을 가지고 있습니다. 그래서 우리가 CTE vpc를 만들면 자동으로 pcx를 만들고 그것을 ops에 연결하고 ops에 연결합니다. 그러나 작전은이 새로운 pcx에 대해 모른다. 그래서 수동으로 추가해야합니다. ops가 리소스 조회를 할 수있게하고 싶습니다. 새로운 VPC/PCX에 대한 자체 리소스를 제공합니다.

TLDR; 양방향 VPC 피어링이보다 동적 인 방법

답변

0

우리는이 문제를 해결하기 위해 래퍼 스크립트를 작성했습니다. 새로운 VPC를 추가 할 때마다 ops VPC 디렉토리로 이동하여이 스크립트를 실행하면 variables.tf 파일에 OPS vpc 피어링 연결/라우트를 설정하는 데 필요한 모든 변수가 동적으로 채워집니다.

스크립트 예 :

#!/bin/bash 
region=$(find . -name "*vars.tf"|cut -d/ -f2|cut -d- -f1-3) 
profile=$(find . -name "*vars.tf" -exec grep 'variable "profile"' {} \; |awk '{print $6}'|tr -d '"') 
account=$(pwd|cut -d/ -f5|cut -d- -f1) 

getData(){ 
    for id in ${ids[@]}; do 
     output=$(aws ec2 describe-vpc-peering-connections --region $region --profile $account --vpc-peering-connection-ids $id) 
     cidr=$(echo "$output"|jq '.VpcPeeringConnections[].RequesterVpcInfo.CidrBlock'|tr -d '"') 
     if [[ $1 == cidr ]]; then 
      echo $cidr 
     elif [[ $1 == id ]]; then 
      echo $id 
     fi 
    done 
} 
checkOps() { 
    pwd|grep 'ops' &>/dev/null 
} 
populateRoutes() { 
    if ! checkOps; then 
     echo "Must be run from the ops directory" 
     exit 1 
    fi 
    ids=($(aws ec2 describe-vpc-peering-connections --region $region --profile $account --filters "Name=status-code,Values=active"|jq '.VpcPeeringConnections[].VpcPeeringConnectionId'|tr -d '"')) 
    if ((${#ids[@]} == 0)); then 
     echo "No update necessary" 
     exit 0 
    fi 

    cidr_list=($(getData cidr)) 
    cidr_format=$(echo "${cidr_list[@]}"|tr ' ' ',') 
    echo $cidr_format 

    id_list=($(getData id)) 
    id_format=$(echo "${id_list[@]}"|tr ' ' ',') 
    echo $id_format 

    if ((${#cidr_list[@]} != ${#id_list[@]})); then 
     echo "CIDR List and ID List do not match" 
     exit 1 
    fi 

    sed -i "/pcx_count/c\variable\ \"pcx_count\"\ \{\ default \=\ \"${#ids[@]}\" \}" ./variables.tf 
    sed -i "/ops_cidrs/c\variable\ \"ops_cidrs\"\ \{\ default\ \=\ \"$cidr_format\"\ \}" ./variables.tf 
    sed -i "/pcx_ids/c\variable\ \"pcx_ids\"\ \{\ default\ \=\ \"$id_format\"\ \}" ./variables.tf 
} 

populateRoutes 
0

당신이 remote state backend를 사용하는 가정, 당신은 remote state data source로 OPS 네트워크 스택을 끌어하고 당신이 원하는 어느 덧 스택에서의 라우팅 테이블을 변경할 수 있습니다 에 연결할 수 있습니다.

시도하고 (보일러 플레이트의 많은 실종 명백하게) 최소한의 예를 수행합니다

# my_ops_stack.tf 

provider "aws" { 
    region = "eu-west-1" 
} 

module "ops_stack" { 
    source = "/my/modules/ops_stack" 
    cidr = "10.1.0.0/16" 
    // other vars probably 
} 

// the outputs which will be accessible 
// via the remote state data source: 
output "routing_table_id" { 
    value = "${module.ops_stack.routing_table_id}" 
} 
output "vpc_id" { 
    value = "${module.ops_stack.vpc_id}" 
} 
output "vpc_cidr" { 
    value = "10.1.0.0/16" 
} 

을 거 야 지금 configure terraform의 CLI (this will soon be possible in config)를 사용하여이 스택에 대한 원격 상태 백엔드 :

# Run in the same folder as my_ops_stack.tf 
terraform remote config \ 
    -backend=s3 \ 
    -backend-config="bucket=my-state-bucket" \ 
    -backend-config="key=ops-stack/terraform.tfstate" \ 
    -backend-config="region=eu-west-1" 

terraform apply 
# the usual stuff... but now synced with s3! 
: 당신은 스택에 적용

지금 상태 백엔드 구성, 변경 사항은 백엔드에 동기화됩니다 이제

, 새 임시 스택의 템플릿 (dev에, 자극, 품질 보증, STG, UAT 등 CTE) :

당신이 임시 스택이 완료되면
# my_dev_stack.tf 

provider "aws" { 
    region = "eu-west-1" 
} 

// Pull in your ops stack from the remote backend: 
data "terraform_remote_state" "ops_stack" { 
    backend = "s3" 
    config { 
     bucket = "my-state-bucket" 
     key = "ops-stack/terraform.tfstate" 
     region = "eu-west-1" 
    } 
} 

// Create your dev stack 
module "dev_stack" { 
    source   = "/my/modules/dev_stack" 
    cidr    = "10.2.0.0/16" 
    // The ops_stack vpc id for creating the peering connection: 
    ops_vpc_id  = "${data.terraform_remote_state.ops_stack.vpc_id}" 
    // Maybe some security group rules you wanna setup 
    allow_access_from = "${data.terraform_remote_state.ops_stack.vpc_cidr}" 
    // other vars probably 
} 

// And use its outputs to add a route to the 
// ops vpc routing table from the dev stack! 
resource "aws_route" "ops_to_dev" { 
    route_table_id = "${data.terraform_remote_state.ops_stack.routing_table_id}" 
    destination_cidr_block = "10.2.0.0/16" // dev_stack's cidr 
    vpc_peering_connection_id = "${module.dev_stack.vpcx_id}" 
} 

, 안전하게 파괴 할 수있다 그것도 ops 스택에서 그 경로를 정리할 것입니다.

희망은 다음과 같습니다.