Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using gitlab-ci vars inside an ansible playbook

I want to set a remote environment inside a docker container using an Ansible playbook. This playbook will run from gitlab-ci with variables I set in in the Gitlab CI/CD confituration. How can I acheive that?

Here is the template I want to use. How do I set the user_id and password from the CI/CD variables?

tasks:
  - name: Run XYZ Container
    docker_container:
      name: XYZ
      restart_policy: on-failure
      image: xxxxxxxxxxx
      container_default_behavior: "compatibility"
      env:
        USER_ID= $USER_ID
        PASSWORD= $PASSWORD
like image 581
Rushita Thakkar Avatar asked Oct 18 '25 11:10

Rushita Thakkar


1 Answers

Since gitlab-ci variables are just environment variables inside your job, and since your ansible controller runs inside that job, you can use the env lookup to read them from the controller.

Please note that:

  1. the docker_container module's env parameter expects a dict and not a new line separated string of bash like env vars definition like in your example.
  2. as a security measure, you should either check that the vars are defined prior to using them (with an assert or fail task) or use a default value in case they're not. My example uses a default value. For more on providing default value, you can see the ansible documentation (and the original jinja2 documentation to understand that d is a an alias to default)
tasks:
  - name: Run XYZ Container
    docker_container:
      name: XYZ
      restart_policy: on-failure
      image: xxxxxxxxxxx
      container_default_behavior: "compatibility"
      env:
        USER_ID: "{{ lookup('env', 'USER_ID') | d('defaultuser', true) }}"
        PASSWORD: "{{ lookup('env', 'PASSWORD') | d('defaultpass', true) }}"
like image 109
Zeitounator Avatar answered Oct 21 '25 04:10

Zeitounator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!