创建Github Actions

这里我们将设置三个 GitHub Actions:

  • Compliance:对存储库的所有推送运行合规性检查
  • Build:在所有推送到存储库时对模板运行构建验证
  • Deploy:仅在主分支上的推送事件上部署我们的 cloudformation 模板

切换到本地开发环境,由于我们不想将任何新代码推送到主分支,因此先创建一个新功能分支:

git checkout -b "feat-init"

image-20231111221148311

创建Compliance Github Action

我们的合规性验证将根据 FedRAMP 中等合规性指南中的一些规则运行预定义的 cfn-guard 规则集。 每次有人推送到存储库上的任何分支时,规则都会检查,确保所有代码在集成时都经过测试。 通过此操作,不需要访问我们的 AWS 环境,因为该工具会执行简单的静态代码分析。

在代码库中创建workflows目录和compliance.yml

mkdir -p ./.github/workflows
touch ./.github/workflows/compliance.yml

compliance.yml内容如下:

---
name: 'compliance'
## run ci testing on all push events
on: [push]
jobs:
  ## Guard rule set
  sast-guard:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - uses: grolston/guard-action@main
      with:
        data_directory: './cloudformation/'
        rule_set: 'FedRAMP-Moderate'
        show_summary: 'all'
        output_format: 'single-line-summary'

创建Build Github Action

构建验证操作将确保能够部署 cloudformation 模板,它运行类似于可以在本地运行的 aws cloudformation validate-template 命令的测试。 构建操作将在存储库上任何分支的所有推送事件上运行。 此操作也不需要访问我们的 AWS 环境。

在仓库下创建build.yaml:

touch ./.github/workflows/build.yml

内容如下:

---
name: 'build'

on: [push]

jobs:
  build-validation:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Testing with CFN Lint Command
        uses: scottbrenner/cfn-lint-action@v2
        with:
          command: cfn-lint -t ./cloudformation/ec2-bastion.yml --region us-east-1 --ignore-checks W

创建Deploy Action

在仓库下创建deploy.yml:

touch ./.github/workflows/deploy.yml

内容如下:

---
name: deploy

on:
  push:
    branches:
      - main

env:
  AWS_DEFAULT_REGION: us-east-1
  AWS_DEFAULT_OUTPUT: json

jobs:
  deploy-cfn:
    name: deploy
    runs-on: ubuntu-latest
    # These permissions are needed to interact with GitHub’s OIDC Token endpoint.
    permissions:
      id-token: write
      contents: read
    steps:
    - name: Checkout
      uses: actions/checkout@v2
    - name: Configure AWS Credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-region: us-east-1
        ## the following creates an ARN based on the values entered into github secrets
        role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ secrets.AWS_DEPLOY_ROLE }} # 将使用之前的AWS_ACCOUNT_ID、AWS_DEPLOY_ROLE secret进行替换
        role-session-name: myGitHubActions
    - name: Deploy EC2 Bastion
      uses: aws-actions/aws-cloudformation-github-deploy@v1.0.3
      with:
        name: myEC2bastion
        template: cloudformation/ec2-bastion.yml
        capabilities: CAPABILITY_IAM, CAPABILITY_NAMED_IAM
        no-fail-on-empty-changeset: "1"
        parameter-overrides: "pVpc=${{ secrets.VPC_ID }},pSubnet=${{ secrets.SUBNET_ID }}"  # 将使用之前设置的VPC_ID和SUBNET_ID进行替换