Ansible - Get key pair value from file on remote machine and populate a variable

Viewed 246

Trying to extract a key pair value from a .yaml file and populate it into a variable:

/etc/puppetlabs/puppet/csr_attributes.yaml

File Example:

extension_requests:
  pp_service: 'private'
  pp_instance_id:  'blah'
  pp_image_name:  'RedHat 7.7 Base'
  pp_project:  'TBT'
  pp_application:  'xxxxx'
  pp_environment: 'dev'
  pp_role: 'base_stuff'
  pp_software_version: '2020-04-30'
  pp_provisioner: 'Ansible Tower'
  pp_datacenter: 'DC2'
  pp_zone: 'C6600_NPE_RS'
  pp_cloudplatform: 'esx'
  pp_apptier: 'dev'
  pp_securitypolicy: 'Stuff'
  1.3.6.1.4.1.34380.1.2.1:  ''
  1.3.6.1.4.1.34380.1.2.2:  '8'
  1.3.6.1.4.1.34380.1.2.3:  '77504'

I can do it via the line number, but I need it to be more dynamic as the lines are different from server to server:

Current individual line code:

- name: cat file
  shell: cat /etc/puppetlabs/puppet/csr_attributes.yaml
  register: cat_content_file

- set_fact:
    pp_service: "pp_service: {{ cat_content_file.stdout_lines[2].split()[1] }}"
    pp_application: "pp_application: {{ cat_content_file.stdout_lines[6].split()[1] }}"

- debug:
    msg:
    - "{{ pp_service }}"
    - "{{ pp_application }}"

I think I need to convert the output into a dict, but I'm completely stuck on how to do it. Any advice would be appreciated.

1 Answers

You could use a combination of file and from_yaml:

  - set_fact:
      your_variable: "{{ lookup('file','/etc/puppetlabs/puppet/csr_attributes.yaml') | from_yaml }}"
  - debug: var=your_variable.extension_requests.pp_service
Related