我想要使用 AWSUtility::CloudFormation::CommandRunner,在我的 AWS CloudFormation 堆疊中的資源之前或之後執行命令。
解決方法
注意: 如果您在執行 AWS Command Line Interface (AWS CLI) 命令時收到錯誤訊息,則請參閱對 AWS CLI 進行錯誤疑難排解。此外,請確定您使用的是最新的 AWS CLI 版本。
註冊 AWSUtility::CloudFormation::CommandRunner
如果您尚未註冊 AWSUtility::CloudFormation::CommandRunner 資源,請執行下列命令進行註冊:
git clone https://github.com/aws-cloudformation/aws-cloudformation-resource-providers-awsutilities-commandrunner.git
cd aws-cloudformation-resource-providers-awsutilities-commandrunner
curl -LO https://github.com/aws-cloudformation/aws-cloudformation-resource-providers-awsutilities-commandrunner/releases/latest/download/awsutility-cloudformation-commandrunner.zip
./scripts/register.sh --set-default
register.sh 指令碼會執行 register-type AWS CLI 命令,並使用 awsutility-cloudformation-commandrunner.zip 在您的預設 AWS 區域中註冊資源類型。若要檢查預設「區域」,請執行 aws configure get region 命令。如需 register.sh 指令碼執行哪些動作的相關資訊,請參閱 AWS GitHub 網站上的使用者安裝步驟。
在 CloudFormation 範本中定義資源
若要在 CloudFormation 堆疊中的資源之前或之後執行命令,請在您的 CloudFormation 範本中定義 AWSUtility::CloudFormation::CommandRunner 資源。
範例範本:
Resources:
CommandRunner:
Type: AWSUtility::CloudFormation::CommandRunner
Properties:
Command: 'aws ssm get-parameter --name BucketName --region us-east-1 --query Parameter.Value --output text > /command-output.txt'
Role: EC2-Role
LogGroup: my-cloudwatch-log-group
您必須在 AWS CLI 命令中包含 --region 選項。然後,將命令的輸出寫入名為 /command-output.txt 的保留檔案。
Role 屬性必須是具有關聯 IAM 角色的 AWS Identity and Access Management (IAM) 執行個體設定檔的名稱。IAM 角色必須與 Amazon Elastic Compute Cloud (Amazon EC2) 服務 ec2.amazonaws.com 具有信任關係。為了執行您的命令,AWSUtility::CloudFormation::CommandRunner 資源將採用 Role 屬性。如果您指定 LogGroup 屬性,則 LogGroup 會將命令執行的日誌寫入 Amazon CloudWatch 日誌群組。
如需進一步了解如何在範本中使用 AWSUtility::CloudFormation::CommandRunner 資源,請參閱 GitHub 網站上的 README.md 和 docs/README.md。
使用 Fn::GetAtt 參考命令的輸出。
範本程式碼片段範例:
S3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !GetAtt CommandRunner.Output
若要在邏輯名稱為 Instance (執行個體) 的資源之後執行命令,請指定 DependsOn: Instance (在 AWSUtility::CloudFormation::CommandRunner 資源的定義中)。
範例範本:
Resources:
CommandRunner:
DependsOn: Instance
Type: AWSUtility::CloudFormation::CommandRunner
Properties:
Command: aws s3 ls | sed -n 1p | cut -d " " -f3 > /command-output.txt
LogGroup: my-cloudwatch-log-group
Role: EC2-Role
Instance:
Type: AWS::EC2::Instance
Properties:
Image: ami-abcd1234
若要在資源之前執行命令,請將 DependsOn 設為該資源定義中的 AWSUtility::CloudFormation::CommandRunner 資源。
範例範本:
Resources:
CommandRunner:
Type: AWSUtility::CloudFormation::CommandRunner
Properties:
Command: aws s3 ls | sed -n 1p | cut -d " " -f3 > /command-output.txt
LogGroup: my-cloudwatch-log-group
Role: EC2-Role
Instance:
DependsOn: CommandRunner
Type: AWS::EC2::Instance
Properties:
Image: ami-abcd1234
**注意:**在前述範例中,sed -n 1p 僅會列印 aws s3 ls 傳回回應的第一行。如需取得儲存貯體名稱,sed -n 1p 會將回應傳送至 cut -d " " -f3。然後,cut -d " " -f3 會選擇分割以空格分隔的行後,所建立陣列中的第三個元素。
相關資訊
在 AWS CloudFormation 範本中執行 bash 命令