簡體   English   中英

CloudFormation - 根據 vpc 標簽值將安全組動態分配給 vpc

[英]CloudFormation - Assign a security group to a vpc dynamically based on a vpc tag value

我有一個組織帳戶,下面有幾個托管帳戶。 每個托管帳戶中都有多個 VPC。 每個托管賬戶中的一個 VPC 將有一個標簽“ServiceName”:“True”,而該賬戶中的其他 VPC 將有一個“ServiceName”:“False”標簽。

我正在嘗試創建一個堆棧集,其中的堆棧專用於創建一個附加了入口規則的安全組,我需要將該安全組的“VpcId”屬性動態分配為具有“ServiceName”的 VPC 的“VpcId” ":"True" 標簽在該帳戶中。

顯然,如果我沒有在 VpcId 字段中指定 VPC ID,它會創建安全組,但將其附加到該賬戶的默認 VPC。 我也無法手動指定 VPC,因為它將在多個賬戶中運行。 通過運行某種 function 來提取“VpcId”,給我留下唯一可用於搜索和分配 VPC 的選項。

當我在指定 VPC ID 的同時在測試環境中運行它時,堆棧本身工作正常。 所以,這只是動態獲取“VpcId”的問題。

最后,我希望做一些類似這樣的事情:

{
"Parameters": {
    "MyValidVPCID": {
        "Description": "My Valid VPC ID where ServiceName tag equals true. Do some Lambda Kung Fu to get the VPC ID using something that would let me parse the equivalent of aws ec2 describe-vpcs command.",
        "Type": "String"
    }
},
"Resources": {
    "SG": {
        "Type": "AWS::EC2::SecurityGroup",
        "Properties": {
            "GroupDescription": "Security Group Desc.",
            "Tags": [
                {
                    "Key": "Key1",
                    "Value": "ABC"
                },
                {
                    "Key": "Key2",
                    "Value": "DEF"
                }
            ],
    "VpcId" : { "Ref" : "MyValidVPCID" }
        }
    },
    "SGIngressRule01":
    {
        "Type": "AWS::EC2::SecurityGroupIngress",
        "DependsOn": "SG",
        "Properties": {
            "GroupId" : { "Fn::GetAtt": [ "SG", "GroupId" ] },
            "Description": "Rule 1 description",
            "IpProtocol": "tcp",
            "FromPort": 123,
            "ToPort": 456,
            "CidrIp": "0.0.0.0/0"
        }
    }
}

我真的不知道這是否是一種可行的方法,或者根據標簽恢復該 VpcId 所需的額外步驟是什么。 這就是為什么如果我能從曾經使用 CloudFormation 的人那里得到一些意見,那會對我有很大幫助。

動態獲取“VpcId”。

您必須為此使用自定義資源 您必須將其創建為lambda function ,它將采用您想要的任何輸入 arguments,並使用 AWS SDK 查詢或修改堆棧中的 VPC/安全組。

感謝 Marcin 使用自定義資源為我指明了正確的方向。 對於那些想知道使其工作的基本代碼是什么樣子的人,它看起來像這樣:

Resources:

  FunctionNameLambdaFunctionRole:
    Type: "AWS::IAM::Role"
    Properties:
      RoleName: FunctionNameLambdaFunctionRole
      Path: "/"
      AssumeRolePolicyDocument:
          Version: "2012-10-17"
          Statement:
              - Effect: Allow
                Principal:
                  Service: lambda.amazonaws.com
                Action: sts:AssumeRole
  
  FunctionNameLambdaFunctionRolePolicy:
    Type: "AWS::IAM::Policy"
    Properties:
        PolicyName: admin3cx
        PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action: "*"
                Resource: "*"
        Roles:
          - Ref: FunctionNameLambdaFunctionRole

  FunctionNameLambdaFunctionCode:
    Type: "AWS::Lambda::Function"
    DeletionPolicy: Delete
    DependsOn:
      - FunctionNameLambdaFunctionRole
    Properties:
        FunctionName: FunctionNameLambdaFunctionCode
        Role: !GetAtt FunctionNameLambdaFunctionRole.Arn
        Runtime: python3.7
        Handler: index.handler
        MemorySize: 128
        Timeout: 30
        Code:
          ZipFile: |
            import boto3
            import cfnresponse
            ec2 = boto3.resource('ec2')
            client = boto3.client('ec2')
            def handler(event, context):
              responseData = {}
              filters =[{'Name':'tag:ServiceName', 'Values':['True']}]
              vpcs = list(ec2.vpcs.filter(Filters=filters))
              for vpc in vpcs:
                responseVPC = vpc.id
              responseData['ServiceName'] = responseVPC
              cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")

  FunctionNameLambdaFunctionInvocationCode:
    Type: "Custom::FunctionNameLambdaFunctionInvocationCode"
    Properties:
      ServiceToken: !GetAtt FunctionNameLambdaFunctionCode.Arn

  SGFunctionName:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: Description
      VpcId: !GetAtt FunctionNameLambdaFunctionInvocationCode.ServiceName
      
   ...

一些東西已經被編輯,我切換到 YAML。代碼將被明顯地細化。 關鍵只是為了確保我能夠根據 CloudFormation 堆棧中 Lambda function 中的過濾器獲得返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM