Ben Ben - 1 year ago 129
JSON Question

How do I register a variable in Ansible, pulled from JSON Output?

I'm trying to automate the configuration of an Amazon Cloudfront distribution with Ansible. Currently, I need to look up Amazon Certificate Manager for the ARN (Amazon Resource Name) of my certificate, and store the ARN as a variable to use later on in my Cloudfront distribution config.

My lookup for this is as follows:

- 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
this_project_arn: # I want to set this from the output of list-certficates

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

The output from that debug is currently as follows:

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

I have two aims:

  1. Pull out the value of
    from the JSON returned there;

  2. Make it resilient by looking specifically for '' in the results (I have the domain as an Ansible var ready for comparison), and storing only the ARN for that domain's cert, in case there's more than one cert returned by

Is there some way to record my
from a traverse of the JSON output from
and only return the ARN value where the
value contains


Answer Source

You need with_items on the parsed data to loop over the certificate summaries, then you can filter using when in order to selectively set_fact:

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