1

recently i started to look up Ansible to automate server provisioning, but i cant seem to import a specific variable in my yml file to my .py script for it to be used. Example of what im looking for:

.yml
var:
server_name: ml-apitest-t1

then import that variable server_name to my variable in python, so it would kinda look like this:

self.server_name = .yml server_name

2 Answers 2

1

if your .yml. file looks somewhat like this:

- server:
    var:
    server_name: ml-apitest-t1

then you should use PyYaml, try this

import yaml
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

with open('test.yml', 'r') as f:
    cont = yaml.load(f.read(), Loader=Loader)

print (cont)

in the case of my example it would output this

[{'server': {'var': None, 'server_name': 'ml-apitest-t1'}}]

to get the server_name from my test .yml file i would need to do this, but i your case it would look different because your .yml file structure is different

import yaml
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

with open('test.yml', 'r') as f:
    cont = yaml.load(f.read(), Loader=Loader)

print (cont[0]['server']['server_name'])

and this is the output

ml-apitest-t1

Also here is the PyYaml documentation

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, but how would i go about returning a value that has been processed in a running ansible playbook?
put cont[0]['server']['server_name'] in a var and use it as you wish
1

You could assign these variables as environment variable using ansible task, then access it through python.
To set environment variable in ansible:

- hosts: dev
  tasks:
    - name: Set server_name
      environment:
        SERVER_NAME: server_name

To access environment variable in python, use something like this:

import os
self.server_name = os.environ['SERVER_NAME']

Remember that the ENV above are only temporary in play level, so your python script must be called in the same play.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.