【问题标题】:AWS SSM Run command : use the current account number from a Cloudformation TemplateAWS SSM 运行命令:使用 Cloudformation 模板中的当前帐号
【发布时间】:2020-01-07 11:29:30
【问题描述】:

我有一个 CloudFormation 模板,它创建一组 SSM 命令来管理我的 Linux EC2 实例。此命令必须有权访问我的 AWS 帐号才能执行某些任务。

在我的 CloudFormation 模板上,我做了:

AWSTemplateFormatVersion: '2010-09-09'
Description: Sample SSM commands

MyCommand1:
  Type: AWS::SSM::Document
  Properties: 
    DocumentType: Command
      Content: 
        schemaVersion: "2.2"
        parameters: {}
        mainSteps: 
          - action: aws:runShellScript 
            name : command1
            inputs: 
              runCommand:
                - echo "this command run on the selected EC2 instance" && echo "You are running this on account {{global:ACCOUNT_ID}}"

Outputs:
    Command1ID:
        Description: MyCommand1
        Value: !Ref  MyCommand1

此模板安装功能,我可以从 SSM Web 控制台运行它。

但是 {{global:ACCOUNT_ID}} 对我的帐号不重要。它的值是字符串“{{global:ACCOUNT_ID}}”。所以我认为这不是在 SSM 命令中使用 global var 的好语法。

因此,在阅读此处https://docs.aws.amazon.com/systems-manager/latest/userguide/walkthrough-cli.html 的文档后,我尝试仅通过 CLI 进行测试(以快速测试其他语法):

$> sh_command_id=$(aws ssm send-command --instance-ids "i-0cb0c0ea8ef7339f1" --document-name "AWS-RunShellScript" --parameters commands='echo You are running this on account {{global:ACCOUNT_ID}}' --output text --query "Command.CommandId")

但该命令失败并出现解析错误Error parsing parameter '--parameters': Expected: ',', received: '}' for input

在 SSM“runCommand”操作中使用 {{global:*}} 的正确语法是什么?

【问题讨论】:

    标签: amazon-web-services ssm


    【解决方案1】:

    您可以使用Fn::Sub 函数实现此目的:

    - !Sub 'echo "this command run on the selected EC2 instance" && echo "You are running this on account ${AWS::AccountId}"'
    

    【讨论】:

    • 很好的答案!要完成 Yogesh_D 的答案:不可能在 SSM 命令中使用 {{..}},但您的技巧是在 SSM 之前在 CloudFormation 级别替换 account_id。
    • 今天学到了新东西! @JayMore Def 使用这个而不是我提到的:)
    【解决方案2】:

    ACCOUNT_ID 的内置变量对您不可用。使用 SSM,您正在实例上运行命令,而此命令不理解 ACCOUNT_ID。基于云形成模板,我假设您在基于 *ix 的系统上运行它。

    一种方法是在您的实际命令中使用它:

    ACCOUNT_ID=`curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep accountId| awk '{print $3}'|sed 's/"//g'|sed 's/,//g'` && echo "this command run on the selected EC2 instance" && echo "You are running this on account ${ACCOUNT_ID}"

    这使用ec2 instance metadata 来计算帐户ID。

    【讨论】:

    • 感谢您的回答,它解决了运行级别的问题。改进:如果您使用的是标准 AmazonLinux,您可以使用:curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .accountId 而不是 awk | sed。
    • 是的,您可以使用 jq,但不想假设您在 ec2 实例上安装了 jq,因此坚持使用 awk 和 sed。
    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2016-11-04
    • 1970-01-01
    • 2020-05-01
    • 2020-03-16
    • 2021-03-01
    相关资源
    最近更新 更多