2

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?

Molenpad
  • 833
  • 2
  • 14
  • 34
  • `mypassword` is the secret value though so how would I know it? – Molenpad Apr 21 '22 at 10:45
  • `fatal: [default]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: {{ lookup('amazon.aws.aws_secret', 'my/awesome/secret', region='eu-west-2').password }}: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'password'"}` – Molenpad Apr 21 '22 at 11:02
  • I have done a debug, and as I said in the question `{"password" : "mypassword"}` is returned, literally Thanks for your solutions, I will try them – Molenpad Apr 21 '22 at 11:11
  • Your suggestion above led me to the right solution; `(lookup('amazon.aws.aws_secret', 'my/awesome/secret', region='eu-west-2') | from_json).password` You should put this as an answer so I can mark it as accepted for you. Thank you. – Molenpad Apr 21 '22 at 12:28

2 Answers2

3

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 
  }}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
0

You can use nested parameter:

https://docs.ansible.com/ansible/latest/collections/amazon/aws/aws_secret_lookup.html#parameter-nested

For example:

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