获取所有 aws 帐号并排除那些在脚本执行期间传递的帐号

get all aws account numbers and exclude those which are passed during the execution of script

我想将某些 SCP(服务控制策略)应用于组织下的所有 AWS 账户,账户所有者指定的账户除外。

为了将 SCP 策略附加到 aws 帐户,我正在使用 terraform 的以下资源:

resource "aws_organizations_policy_attachment" "account" {
  for_each  = toset(var.aws_account_number_restrict_root_scp)
  policy_id = aws_organizations_policy.restrict_root.id
  target_id = each.key
}

#aws_account_number_restrict_root_scp should evaluates to something like this:
#["33333443453","333333333333","444444444444"]

现在我想通过任何脚本语言生成 aws_account_number_restrict_root_scp 变量。 这将是 AWS 组织下的所有 AWS 账号,除了账户所有者指定的账号。 变量应采用上述格式。

我正在使用下面的要求格式获取所有 aws 帐号,但无法删除帐户所有者提供的帐号。

#!/bin/bash
#echo [=11=]
var=$(aws organizations list-accounts --query 'Accounts[*].Id')
echo $var

如何通过删除帐户所有者提供的帐号来过滤$var

简单来说,

var=[
  {
    "Status": "ACTIVE",
    "Name": "XYZ",
    "JoinedMethod": "INVITED",
    "Id": "3234443322122"
  },
  {
    "Status": "ACTIVE",
    "Name": "ABC",
    "JoinedMethod": "CREATED",
    "Id": "12345678901"
  },
  {
    "Status": "ACTIVE",
    "Name": "PQR",
    "JoinedMethod": "CREATED",
    "Id": "3444550998293"
  }
]

exception=["3444550998293"]

#then expected result should be:
echo $expected_output
[
"3234443322122",
 "12345678901"
]

注意:$var 生成了 运行 次并且有超过 200 个元素并且 $exception 是用户期望的数据。

这是一个使用 index/1

的过滤器
map( .Id | select( . as $id | $exception | index($id) | not ) )

要使用它,您需要提供一个 exception 数组。
一种方法是使用 --argjson 例如如果您的过滤器在 filter.jq

jq -Mc --argjson exception '["3444550998293"]' -f filter.jq <<< "${var}"

示例输出

["3234443322122","12345678901"]

Try it online!