如何在Ansible中注册变量,从JSON输出中提取?

时间:2016-10-09 17:12:18

标签: json amazon-web-services ansible ansible-2.x

我正在尝试使用Ansible自动配置Amazon Cloudfront分发版。目前,我需要查找Amazon Certificate Manager以获取我的证书的ARN(Amazon资源名称),并将ARN存储为变量,以便稍后在我的Cloudfront分发配置中使用。

我对此的查询如下:

- name: Check for existence of a certificate for this project in Amazon Certificate Manager
  command: >
    aws acm list-certificates 
      --profile "{{ project_name }}"-deploy
      --region us-east-1 
  register: cert_list
  ignore_errors: True

- name: Record list-certificates output to Json  
  set_fact: 
    this_project_arn: # I want to set this from the output of list-certficates

- debug: msg="{{ cert_list.stdout | from_json }}"

该调试的输出目前如下:

TASK [configure-cloudfront : debug] ********************************************
ok: [localhost] => {
    "msg": {
        "CertificateSummaryList": [
            {
                "CertificateArn": "arn:aws:acm:us-east-1:123456789101:certificate/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", 
                "DomainName": "*.foo.com"
            }
        ]
    }
}

我有两个目标:

  1. 从那里返回的JSON中拉出CertificateArn的值;
  2. 通过在结果中专门查找“foo.com”(我将域名作为Ansible var准备进行比较)使其具有弹性,并且仅存储该域证书的ARN,以防返回多个证书list-certificates
  3. 是否有某种方法可以从set_fact的JSON输出的遍历中记录我的cert_list.stdout,并且仅返回DomainName值包含foo.com的ARN值?

    谢谢!

1 个答案:

答案 0 :(得分:4)

您需要对解析后的数据with_items循环遍历证书摘要,然后您可以使用when进行过滤,以便有选择地set_fact

- name: Set ARN for passed in domain
  set_fact:
    project_arn: "{{ item.CertificateArn }}"
  when: item.DomainName == "*.foo.com"
  with_items: "{{ (cert_list.stdout|from_json).CertificateSummaryList }}"