Search code examples
jsonamazon-web-servicesansibleaws-secrets-manager

Extract secret value only from SecretString using Ansible amazon.aws.aws_secret


I am trying to get a secret value to a var from AWS Secret Manager using Ansible. My original attempt was as follows:

mySecret: "{{ lookup('amazon.aws.aws_secret', 'my/awesome/secret', region='eu-west-2')}}"

This returns a value like:

{"password" : "mypassword"}

All I want is the mypassword value

I have tried numerous ways using json_query including:

mySecret: "{{ lookup('amazon.aws.aws_secret', 'my/awesome/secret', region='eu-west-2') | from_json | json_query('SecretString.password') }}"

But this does not return a value.

What is the correct way of extracting the value only when using json_query with Ansible?


Solution

  • Ansible is very much JSON capable, it can read properly a JSON object and get you properties of the said JSON document by the dot . notation.

    Given the JSON

    { 
      "secret": { 
        "password" : "mypassword" 
      } 
    }
    

    You can access it simply via secret.password, in Ansible.

    Now, what it seems, from your comments, is that the lookup amazon.aws.aws_secret is not returning a JSON but a string, representing a JSON. So, in order to access it, you will have to use the to_json filter first, as you tried it, already.

    But, beside that, the explanation here above still applies, so, this is what you are looking for:

    secret: >-
      {{ 
        (lookup(
          'amazon.aws.aws_secret', 
          'my/awesome/secret', 
          region='eu-west-2'
        ) | from_json).password 
      }}