在一个ansible playbook中,我希望能够动态地提取所有可用aws区域的列表并迭代它们以在任何地方执行相同的aws任务。可以使用aws cli命令aws ec2 describe-regions
获取此信息。我正在寻找可以生成列表的ansible任务或者将这个json转换为可以使用with_items
轻松循环的列表的方法
$ aws ec2 describe-regions
{
"Regions": [
{
"Endpoint": "ec2.ap-south-1.amazonaws.com",
"RegionName": "ap-south-1"
},
{
"Endpoint": "ec2.eu-west-2.amazonaws.com",
"RegionName": "eu-west-2"
},
{
"Endpoint": "ec2.eu-west-1.amazonaws.com",
"RegionName": "eu-west-1"
},
{
"Endpoint": "ec2.ap-northeast-2.amazonaws.com",
"RegionName": "ap-northeast-2"
},
{
"Endpoint": "ec2.ap-northeast-1.amazonaws.com",
"RegionName": "ap-northeast-1"
},
{
"Endpoint": "ec2.sa-east-1.amazonaws.com",
"RegionName": "sa-east-1"
},
{
"Endpoint": "ec2.ca-central-1.amazonaws.com",
"RegionName": "ca-central-1"
},
{
"Endpoint": "ec2.ap-southeast-1.amazonaws.com",
"RegionName": "ap-southeast-1"
},
{
"Endpoint": "ec2.ap-southeast-2.amazonaws.com",
"RegionName": "ap-southeast-2"
},
{
"Endpoint": "ec2.eu-central-1.amazonaws.com",
"RegionName": "eu-central-1"
},
{
"Endpoint": "ec2.us-east-1.amazonaws.com",
"RegionName": "us-east-1"
},
{
"Endpoint": "ec2.us-east-2.amazonaws.com",
"RegionName": "us-east-2"
},
{
"Endpoint": "ec2.us-west-1.amazonaws.com",
"RegionName": "us-west-1"
},
{
"Endpoint": "ec2.us-west-2.amazonaws.com",
"RegionName": "us-west-2"
}
]
}
答案 0 :(得分:2)
使用@Jordi's解决方案我可以使用类似于以下示例的内容转换aws命令输出的json:
---
- hosts: localhost
gather_facts: no
tasks:
- command: "aws ec2 describe-regions"
register: json_out
- set_fact:
region_json: "{{json_out.stdout | from_json}}"
region_list: []
# example of itteration over the converted json
- debug:
msg: "{{item.RegionName}}"
with_items: "{{region_json.Regions|default([], true)|list}}"
# Creates actual list of only region names
- set_fact:
region_list: "{{region_list + [item.RegionName] }}"
with_items: "{{region_json.Regions|default([], true)|list}}"
- debug:
var: region_list
答案 1 :(得分:1)
您可以使用命令模块执行命令并注册输出。
然后变量将具有带输出的.stdout属性。输出是JSON对象。哪个可以通过jinja过滤器 from_json (检查http://docs.ansible.com/ansible/latest/playbooks_filters.html)
问候