Getting attribute value using ansible filters
<p>I am new to ansible. I am trying to get my attribute value from JSON data. Here is my JSON data:</p>

<pre><code>{
   "user1": "{\n \"data\":[\n    {\n     \"secure\": [\n       {\n              \"key\": \"-----BEGIN  KEY-----\nMIIEowIBAAKCAQEAgOh+Afb0oQEnvHifHuzBwhCP3\n-----END KEY-----\"\n       }\n      ],\n     \"owner\": \"shallake\",\n     \"position\": \"gl\"\n    }\n   ]\n}"
}
</code></pre>

<p>I had invalid JSON data, so I converted it into valid JSON using <code>to_json</code> and <code>from_json</code>. The above JSON data is the result that I get.</p>

<p>code:</p>

<pre><code> - set_fact:
      user: "{{ lookup('file','filepath/myfile.json') | to_json }}"

 - set_fact:
      user1: "{{ user | from_json}}"

 - set_fact:
      user3: "{{ item }}"
   with_items: "{{ user1['data'] | map(attribute='position') | list }}"
</code></pre>

<p>In a third set_fact, I am trying to get position attribute value. But it shows an error like this:</p>

<blockquote>
  <p>the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'item' is undefined</p>
</blockquote>

<p>"\"{\n \\"data\\":[\n    {\n     \\"secure\\": [\n       {\n         \\"key\\": \\"-----BEGINPRIVATE KEY-----\nMIIEowIBAAKCAQEAgOh+Afb0oQEnvHifHuzBwl+Tiu8LXoJXb/ii/eh\ngYEP3\n-----END PRIVATE KEY-----\\"\n       }\n      ],\n     \\"owner\\": \\"shalloke\\",\n     \\"position\\": \\"gl\\"\n    }\n   ]\n}\n\n\""</p>

<p>So how can I get a position value from the above JSON data result using ansible loop?</p>

<p>Would you please check if the key in <code>filepath/myfile.json</code> spans multiple lines? We need to escape line breaks in JSON. Use <code>\n</code> to replace line breaks.</p>

<p>The <code>user1</code> is supported to be a map parsed from JSON. However, the JSON in <code>filepath/myfile.json</code> might be invalid. So in the second <code>set_fact</code>, this invalid JSON couldn't be parsed. Thus, <code>user1</code> is just a string. And it doesn't contains an entry <code>data</code>.</p>

<pre><code>{
  "data":[
      {
      "secure": [
        {
                "key": "-----BEGIN  KEY-----\nMIIEowIBAAKCAQEAgOh+Afb0oQEnvHifHuzBwhCP3\n-----END KEY-----"
        }
        ],
      "owner": "shallake",
      "position": "gl"
      }
    ]
}
</code></pre>

<p><a href="http://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json">How do I handle newlines in JSON?</a></p>

python json ansible ansible-playbook ansible-2.x