2

코드 파이프 라인을 사용하여 인프라를 배포하고 있으며 다른 환경 (dev, staging, prod ...)에 배포 할 수 있기를 원합니다.CodePipeline에서 여러 환경을 처리하는 방법은 무엇입니까?

현재 "pip install"지침과 "aws cloudformation package"명령이 포함 된 buildspec.yml 파일이 있습니다. 또한 프로덕션 용 파이프 라인 2 개와 github에서 2 개의 다른 브랜치를 가리키는 개발 용 파이프 라인 2 개를 만들었습니다. 내가 가진 문제는 두 가지 분기에서 파일에 유사한 리소스가 포함되어 있기 때문에 S3 버킷에 이름 충돌이 발생했기 때문입니다.

AWS CLI 및 cloudform을 사용하여 스택을 생성하거나 업데이트 할 때 --parameters 옵션을 사용하여 매개 변수를 전달할 수 있습니다. 내가 만든 2 개의 파이프 라인에서 비슷한 것을하고 싶습니다.

이 문제를 해결하는 가장 좋은 해결책은 무엇입니까?

마지막 목표는 인프라 구축을 자동화하는 것입니다. 우리의 인프라는 사용자, KMS 키, Lamdbas (파이썬에서), 그룹 및 버킷으로 구성됩니다.

내가 자습서 다음과 같은 두 개의 파이프 라인을 만들었습니다 http://docs.aws.amazon.com/lambda/latest/dg/automating-deployment.html

첫 번째 파이프 라인은 코드와 준비 지점에 두 번째를 포함하는 REPO의 마스터 지점에 연결되어 있습니다. 필자의 목표는 두 번째 파이프 라인을 사용하는 준비 환경의 첫 번째 파이프 라인과 준비 지점을 사용하여 프로덕션 환경에서 마스터 분기의 배포를 자동화하는 것입니다.

같은 내 buildspec.yml 파일보기 :

version: 0.1 
phases: 
    install: 
     commands: 
      - pip install requests -t . 
      - pip install simplejson -t . 
      - pip install Image -t . 
      - aws cloudformation package --template-file image_processing_sam.yml --s3-bucket package-bucket --output-template-file new_image_processing_sam.yml 
artifacts: 
    type: zip 
    files: 
     - new_image_processing_sam.yml 

처럼 image_processing_sam.yml 파일보기 :

AWSTemplateFormatVersion: "2010-09-09" 
Transform: "AWS::Serverless-2016-10-31" 
Description: Create a thumbnail for an image uploaded to S3 
Resources: 

    ThumbnailFunction: 
    Type: "AWS::Serverless::Function" 
    Properties: 
     Role: !GetAtt LambdaExecutionRole.Arn 
     Handler: create_thumbnail.handler 
     Runtime: python2.7 
     Timeout: 30 
     Description: "A function computing the thumbnail for an image." 

    LambdaSecretEncryptionKey: 
    Type: "AWS::KMS::Key" 
    Properties: 
     Description: "A key used to encrypt secrets used in the Lambda functions" 
     Enabled: True 
     EnableKeyRotation: False 
     KeyPolicy: 
     Version: "2012-10-17" 
     Id: "lambda-secret-encryption-key" 
     Statement: 
      - 
      Sid: "Allow administration of the key" 
      Effect: "Allow" 
      Principal: 
       AWS: "arn:aws:iam::xxxxxxxxxxxxx:role/cloudformation-lambda-execution-role" 
      Action: 
       - "kms:Create*" 
       - "kms:Describe*" 
       - "kms:Enable*" 
       - "kms:List*" 
       - "kms:Put*" 
       - "kms:Update*" 
       - "kms:Revoke*" 
       - "kms:Disable*" 
       - "kms:Get*" 
       - "kms:Delete*" 
       - "kms:ScheduleKeyDeletion" 
       - "kms:CancelKeyDeletion" 
      Resource: "*" 
      - 
      Sid: "Allow use of the key" 
      Effect: "Allow" 
      Principal: 
       AWS: 
       - !GetAtt LambdaExecutionRole.Arn 
      Action: 
       - "kms:Encrypt" 
       - "kms:Decrypt" 
       - "kms:ReEncrypt*" 
       - "kms:GenerateDataKey*" 
       - "kms:DescribeKey" 
      Resource: "*" 

    LambdaExecutionRole: 
    Type: "AWS::IAM::Role" 
    Properties: 
     RoleName: "LambdaExecutionRole" 
     AssumeRolePolicyDocument: 
     Version: "2012-10-17" 
     Statement: 
     - Effect: Allow 
      Principal: 
      Service: 
      - "lambda.amazonaws.com" 
      Action: 
      - "sts:AssumeRole" 
     Policies: 
     - 
      PolicyName: LambdaKMS 
      PolicyDocument: 
      Version: "2012-10-17" 
      Statement: 
       - 
       Effect: "Allow" 
       Action: 
        - "kms:Decrypt" 
       Resource: "*" 
       - 
       Effect: "Allow" 
       Action: 
        - "lambda:InvokeFunction" 
       Resource: "*" 
     ManagedPolicyArns: 
     - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" 

    UserGroup: 
     Type: "AWS::IAM::Group" 

    LambdaTriggerUser: 
    Type: "AWS::IAM::User" 
    Properties: 
     UserName: "LambdaTriggerUser" 

    LambdaTriggerUserKeys: 
    Type: "AWS::IAM::AccessKey" 
    Properties: 
     UserName: 
     Ref: LambdaTriggerUser 

    Users: 
    Type: "AWS::IAM::UserToGroupAddition" 
    Properties: 
     GroupName: 
     Ref: UserGroup 
     Users: 
     - Ref: LambdaTriggerUser 

    Policies: 
    Type: "AWS::IAM::Policy" 
    Properties: 
     PolicyName: UserPolicy 
     PolicyDocument: 
     Statement: 
      - 
      Effect: "Allow" 
      Action: 
       - "lambda:InvokeFunction" 
      Resource: 
       - !GetAtt DispatcherFunction.Arn 
     Groups: 
     - Ref: UserGroup 

    PackageBucket: 
    Type: "AWS::S3::Bucket" 
    Properties: 
     BucketName: "package-bucket" 
     VersioningConfiguration: 
     Status: "Enabled" 

Outputs: 
    LambdaTriggerUserAccessKey: 
    Value: 
     Ref: "LambdaTriggerUserKeys" 
    Description: "AWSAccessKeyId of LambdaTriggerUser" 

    LambdaTriggerUserSecretKey: 
    Value: !GetAtt LambdaTriggerUserKeys.SecretAccessKey 
    Description: "AWSSecretKey of LambdaTriggerUser" 

내가 계산 변경 세트를 실행하는 두 파이프 라인에 배포 작업을 추가 한 베타 조치 중.

첫 번째 파이프 라인은 매력처럼 작동하며 기대하는 모든 작업을 수행합니다. 마스터 브랜치에서 코드를 푸시 할 때마다 배포됩니다.

내가 직면 한 문제는 준비 분기에 코드를 푸시하면 배포 작업에 도달 할 때까지 모든 것이 파이프 라인에서 작동한다는 것입니다. deploy 액션은 새로운 스택을 만들려고 시도하지만, 똑같은 buildspec.yml과 처리 된 image_processing_sam.yml이기 때문에 아래와 같이 이름 충돌이 발생합니다.

package-bucket already exists in stack arn:aws:cloudformation:eu-west-1:xxxxxxxxxxxx:stack/master/xxxxxx-xxxx-xxx-xxxx 
LambdaTriggerUser already exists in stack arn:aws:cloudformation:eu-west-1:xxxxxxxxxxxx:stack/master/xxxxxx-xxxx-xxx-xxxx 
LambdaExecutionRole already exists in stack arn:aws:cloudformation:eu-west-1:xxxxxxxxxxxx:stack/master/xxxxxx-xxxx-xxx-xxxx 
... 

buildspec.yml image_processing_sam.yml에있는 자원의 이름에 접미사를 추가 할 수 있도록 매개 변수화 할 수있는 방법이 있습니까? 이를 달성하기위한 다른 아이디어는 환영합니다.

감사합니다.

답변

2

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-basic-walkthrough.html

템플릿 구성 파일은 다음과 같이 매개 변수 파일을 통해 CodePipeline의 CloudFormation에 적용됩니다 적어도 2 가지 방법.당신의 CodePipeline CloudFormation에서

:

Configuration: 
    ActionMode: REPLACE_ON_FAILURE 
    RoleArn: !GetAtt [CFNRole, Arn] 
    StackName: !Ref TestStackName 
    TemplateConfiguration: !Sub "TemplateSource::${TestStackConfig}" 
    TemplatePath: !Sub "TemplateSource::${TemplateFileName}" 

또는 템플릿 구성 필드에 콘솔에서

: enter image description here

그것은 설정 파일 형식을 주목할 필요가있다 CLI를 통해 CloudFormation 다른는

를 사용하여
-- parameters 

- 매개 변수는 다음 형식을 사용합니다.

,210
[ 
    { 
    "ParameterKey": "team", 
    "ParameterValue": "AD-Student Life Applications" 
    }, 
    { 
    "ParameterKey": "env", 
    "ParameterValue": "dev" 
    }, 
    { 
    "ParameterKey": "dataSensitivity", 
    "ParameterValue": "public" 
    }, 
    { 
    "ParameterKey": "app", 
    "ParameterValue": "events-list-test" 
    } 
] 

CodePipeline Cloudformation 템플릿 구성 파일이 형식을 사용

{ 
    "Parameters" : { 
    "DBName" : "TestWordPressDB", 
    "DBPassword" : "TestDBRootPassword", 
    "DBRootPassword" : "TestDBRootPassword", 
    "DBUser" : "TestDBuser",  
    "KeyName" : "TestEC2KeyName" 
    } 
} 
+1

안녕하세요,이 이번 주에 테스트 할 시간이 없어하지만 난 그것을 시도하고 최대한 빨리 답변을 받아 들일 수 있는지 확인합니다. 시간과 자세한 답변을 보내 주셔서 감사합니다. – JonathanGailliez

+0

시험 된 어제 전체 코드 예제는 여기에서 볼 수 있습니다. 271 라인 : https://github.com/byu-oit-appdev/iac/blob/master/cloudformation/codepipeline/lambda-pipeline-cf.yaml –

+1

안녕하세요. 솔루션을 검증하고 검증 할 시간을 가지십시오. 그것은 실제로 진행하는 방법입니다. 자세한 답변과 시간 내 주셔서 다시 한 번 감사드립니다. 친애하는. – JonathanGailliez

1

Eric Nord의 답변을 확인하십시오. 그것은 당신이 찾고있는 것입니다.


AWS 포럼에서도 질문했습니다. here.

안녕,

당신의 목표는 준비하고 마스터를위한 다른 버킷 이름을 가지고 있다면, 다른 옵션은 CloudFormation 매개 변수를 사용하는 것입니다 : 여기

은 AWS에서 제공하는 솔루션입니다.

작업을 편집하는 경우 기존 파이프 라인을 편집 할 때 "고급"패널을 확장하고 매개 변수 재정의를 입력하여 각 스테이지에 다른 버킷 접두사를 지정할 수 있습니다. 이슈에 매개 변수를 별도의 .json 파일로 입력 할 수도 있습니다. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-parameter-override-functions.html

여기 테스트 및 생산을위한 다른 스택 구성을 통해 전체 거리입니다 :

는 여기에 일을 자세히있다 http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-basic-walkthrough.html

  • 팀을.

제공된 설명서를 반드시 따라야합니다. 여기에 제가 생각해 낸 해결책이 있습니다.


다음은 내가 만족하지 못했던 자체 솔루션입니다.

빌드 할 때 스크립트를 추가하고 프로젝트를 빌드하는 CodeBuild 에이전트의 ARN에 따라 템플릿을 수정했습니다.

명명 충돌이 발생할 수있는 곳에 "BRANCH_NAME"을 (를) 추가했습니다. image_processing_sam.yml는 지금 :

AWSTemplateFormatVersion: "2010-09-09" 
Transform: "AWS::Serverless-2016-10-31" 
Description: Create a thumbnail for an image uploaded to S3 
Resources: 

    ThumbnailFunction: 
    Type: "AWS::Serverless::Function" 
    Properties: 
     Role: !GetAtt LambdaExecutionRole.Arn 
     Handler: create_thumbnail.handler 
     Runtime: python2.7 
     Timeout: 30 
     Description: "A function computing the thumbnail for an image." 

    LambdaSecretEncryptionKey: 
    Type: "AWS::KMS::Key" 
    Properties: 
     Description: "A key used to encrypt secrets used in the Lambda functions" 
     Enabled: True 
     EnableKeyRotation: False 
     KeyPolicy: 
     Version: "2012-10-17" 
     Id: "lambda-secret-encryption-keyBRANCH_NAME" 
     Statement: 
      - 
      Sid: "Allow administration of the key" 
      Effect: "Allow" 
      Principal: 
       AWS: "arn:aws:iam::xxxxxxxxxxxxx:role/cloudformation-lambda-execution-role" 
      Action: 
       - "kms:Create*" 
       - "kms:Describe*" 
       - "kms:Enable*" 
       - "kms:List*" 
       - "kms:Put*" 
       - "kms:Update*" 
       - "kms:Revoke*" 
       - "kms:Disable*" 
       - "kms:Get*" 
       - "kms:Delete*" 
       - "kms:ScheduleKeyDeletion" 
       - "kms:CancelKeyDeletion" 
      Resource: "*" 
      - 
      Sid: "Allow use of the key" 
      Effect: "Allow" 
      Principal: 
       AWS: 
       - !GetAtt LambdaExecutionRole.Arn 
      Action: 
       - "kms:Encrypt" 
       - "kms:Decrypt" 
       - "kms:ReEncrypt*" 
       - "kms:GenerateDataKey*" 
       - "kms:DescribeKey" 
      Resource: "*" 

    LambdaExecutionRole: 
    Type: "AWS::IAM::Role" 
    Properties: 
     RoleName: "LambdaExecutionRoleBRANCH_NAME" 
     AssumeRolePolicyDocument: 
     Version: "2012-10-17" 
     Statement: 
     - Effect: Allow 
      Principal: 
      Service: 
      - "lambda.amazonaws.com" 
      Action: 
      - "sts:AssumeRole" 
     Policies: 
     - 
      PolicyName: LambdaKMSBRANCH_NAME 
      PolicyDocument: 
      Version: "2012-10-17" 
      Statement: 
       - 
       Effect: "Allow" 
       Action: 
        - "kms:Decrypt" 
       Resource: "*" 
       - 
       Effect: "Allow" 
       Action: 
        - "lambda:InvokeFunction" 
       Resource: "*" 
     ManagedPolicyArns: 
     - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" 

    UserGroup: 
     Type: "AWS::IAM::Group" 

    LambdaTriggerUser: 
    Type: "AWS::IAM::User" 
    Properties: 
     UserName: "LambdaTriggerUserBRANCH_NAME" 

    LambdaTriggerUserKeys: 
    Type: "AWS::IAM::AccessKey" 
    Properties: 
     UserName: 
     Ref: LambdaTriggerUser 

    Users: 
    Type: "AWS::IAM::UserToGroupAddition" 
    Properties: 
     GroupName: 
     Ref: UserGroup 
     Users: 
     - Ref: LambdaTriggerUser 

    Policies: 
    Type: "AWS::IAM::Policy" 
    Properties: 
     PolicyName: UserPolicyBRANCH_NAME 
     PolicyDocument: 
     Statement: 
      - 
      Effect: "Allow" 
      Action: 
       - "lambda:InvokeFunction" 
      Resource: 
       - !GetAtt DispatcherFunction.Arn 
     Groups: 
     - Ref: UserGroup 

    PackageBucket: 
    Type: "AWS::S3::Bucket" 
    Properties: 
     BucketName: "package-bucketBRANCH_NAME" 
     VersioningConfiguration: 
     Status: "Enabled" 

Outputs: 
    LambdaTriggerUserAccessKey: 
    Value: 
     Ref: "LambdaTriggerUserKeys" 
    Description: "AWSAccessKeyId of LambdaTriggerUser" 

    LambdaTriggerUserSecretKey: 
    Value: !GetAtt LambdaTriggerUserKeys.SecretAccessKey 
    Description: "AWSSecretKey of LambdaTriggerUser" 

템플릿에서 "BRANCH_NAME"를 교체 script.sh은 다음과 같습니다

#!/bin/bash 
echo $CODEBUILD_AGENT_ENV_CODEBUILD_BUILD_ARN 
if [[ "$CODEBUILD_AGENT_ENV_CODEBUILD_BUILD_ARN" == *"master"* ]]; then 
    sed "s/BRANCH_NAME//g" image_processing_sam.yml > generated_image_processing_sam.yml; 
fi 
if [[ "$CODEBUILD_AGENT_ENV_CODEBUILD_BUILD_ARN" == *"staging"* ]]; then 
    sed "s/BRANCH_NAME/staging/g" image_processing_sam.yml > generated_image_processing_sam.yml; 
fi 

buildspec.yml는 지금 :

version: 0.1 
phases: 
    install: 
     commands: 
      # Install required module for python 
      - pip install requests -t . 
      - pip install simplejson -t . 
      - pip install Image -t . 
      - bash ./script.sh 
      # To be able to see any issue in the generated template 
      - cat generated_image_processing_sam.yml 
      # Package the generated cloudformation template in order to deploy 
      - aws cloudformation package --template-file generated_image_processing_sam.yml --s3-bucket piximate-package-bucket --output-template-file new_image_processing_sam.yml 
artifacts: 
    type: zip 
    files: 
     - new_image_processing_sam.yml 

I 어떻게 든 당신을 도울 수 있기를 바랍니다. 누군가가 도움이 될 수있는 개선이나 문서를 제공 할 수 있다면 기쁠 것입니다. 당신의 repo의 루트에

{ 
    "Parameters" : { 
    "DBName" : "TestWordPressDB", 
    "DBPassword" : "TestDBRootPassword", 
    "DBRootPassword" : "TestDBRootPassword", 
    "DBUser" : "TestDBuser",  
    "KeyName" : "TestEC2KeyName" 
    } 
} 

장소 이러한 파일을 그들은에서에서 참조 할 수 있습니다 :

관련 문제