简体   繁体   中英

How to run python script from Ansible and pass variable from the python script to Ansible to use later?

I am trying to fetch my keyvalue (myP@ssw0rd) from AWS SSM Parameter store using python boto3. Doing it in an Ansible playbook.yml file. This is the python script that I am using:

 import boto3
 ssm = boto3.client(‘ssm’, region_name=‘us-east-1’)
 response=ssm.get_parameters(Names=[‘MyKeyName’])
 var_value= response[‘Parameters’][0][‘Value’]

I want to use this var_value inside my ansible play book like below: Creating the DD agent

shell: DOCKER_CONTENT_TRUST=1 \
    docker run -d --name ddagent --network my-network -v /var/run/docker.sock:/var/run/docker.sock:ro \
    -v /proc/:/host/proc/:ro \
    -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro \
    -e DD_API_KEY=$var_value \
    datadog/agent:latest

Here I am trying to fetch the value from SSM parameter store(using python boto3) and pass it to Ansible to use in “DD_API_KEY” in above command. Can anyone please let me know what is best way to do it for this usecase?

Add this line to the python script

print (var_value)

Run the python script using command module or script module (if you need to copy the script to remote machine) and register the output.

- name: run python script
  command: '/path/to/python-executable /home/centos/conf.d/ssmread/ddkeyreadssm.py'
  register: result

- name: creating DD agent
  shell: |
    DOCKER_CONTENT_TRUST=1 \
    docker run -d --name ddagent --network my-network -v /var/run/docker.sock:/var/run/docker.sock:ro \
    -v /proc/:/host/proc/:ro \
    -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro \
    -e DD_API_KEY="{{ result.stdout }}" \
    datadog/agent:latest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM