Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
  set_fact: 
    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": "*.foo.com"
            }
        ]
    }
}

I have two aims:

  1. Pull out the value of CertificateArn from the JSON returned there;
  2. Make it resilient by looking specifically for 'foo.com' 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 list-certificates.

Is there some way to record my set_fact from a traverse of the JSON output from cert_list.stdout and only return the ARN value where the DomainName value contains foo.com?

Thanks!

like image 395
Ben Avatar asked Mar 10 '23 23:03

Ben


1 Answers

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
  set_fact:
    project_arn: "{{ item.CertificateArn }}"
  when: item.DomainName == "*.foo.com"
  with_items: "{{ (cert_list.stdout|from_json).CertificateSummaryList }}"
like image 61
guido Avatar answered Apr 28 '23 22:04

guido