Hi I am trying to find out how to get custom environment variable in Ansible.
something that a simple shell command like this:
I created a custom Environment Variable and assigned a value
EXPORT SSH_STATUS=TRUE
who can I access the result from ansible
How can I assign an Ubuntu Environment Variable Value to Ansible Variable
Any clue ?
You can define it as variables or you can pass the variables as extra-vars while running the playbook.
vars:
SSH_STATUS=TRUE
or
--extra-vars "SSH_STATUS=TRUE"
To access the variable use "{{SSH_STATUS}}"
For environment variable use as below
- name: Install cobbler
command: < some command >
environment: "{{SSH_STATUS}}"
#Anish Varghese, From what I have understood, I have written the below code which can extract the value of a custom environment variable in ansible playbook, without even updating the ansible.
- name: show env value
debug:
msg: "{{ lookup('env', 'XV') }}"
Below is the verification of the above task,
Setting the custom environment variable named "XV",
export XV="TRUE"
Running the Ansible script,
TASK [show env value] ***********************************************************************************************************************
ok: [192.168.10.10] => {
"msg": "TRUE"
}
Now, updating the value of the env variable and running the ansible again,
export XV="FALSE"
TASK [show env value] ***********************************************************************************************************************
ok: [192.168.10.10] => {
"msg": "FALSE"
}
Here is the associated documentation.
https://docs.ansible.com/ansible/latest/plugins/lookup/env.html
Ansible has a built in facility for this called environment https://docs.ansible.com/ansible/latest/user_guide/playbooks_environment.html
You probably want set_fact.
- set_fact:
SSH_STATUS: TRUE
If what you need is the value of $somevar, if it gets set by .bashrc then register is your friend.
- name: Expose `$somevar`
shell: echo "$somevar" # must exist
register: tmpvar
- set_fact:
SSH_STATUS: "{{ tmpvar.stdout }}"
The issue is that you have to make sure the variable is set before you access it.
Related
I need to replace a variable value inside a file based gitlab variable like below.
File based variable:
Name: app_service_dev_env
Value:
iam_role_name="xxxx"
lambda_s3_bucket_name = "xxxxx"
lambda_s3_key="xxxxx"
Variable:
Name: ENV
Value: dev
Below is what I am looking to implement
before_script:
-cat ${app_service_${ENV}_env} > dev.txt
Getting error: ERROR: Job failed: exit code 2
Could anyone please let me know how to resolve this?
How could I resolve this?
The file variable type creates a file. They are not environment variables. The key is the path to the file.
before_script:
- cat app_service_dev_env > dev.txt
Though, you could simply make the name of your file variable dev.txt
As for your ENV variable, with your current setup you can do something like this:
before_script:
- cat "app_service_${ENV}_env"
I am calling a GitHub action, and I want to pass it the parameter extra_build_args with the value --build-arg CURRENT_DD_VERSION={$VER} (not in string) where $VER is a shell variable that I set with a specific version. When I check what was passed in I see it took the literal value {$VER} instead of resolving the variable. I set $VER in a different (earlier) step of the Github action. How can pass in the content of the shell variable as a parameter?
- name: Get version
run: |
VER=$(cat ver.txt)
- name: Build docker image
uses: kciter/aws-ecr-action#v3
with:
//some more parameters
extra_build_args: "--build-arg CURRENT_DD_VERSION={$VER}"
Check first the syntax:
${VER}
# not
{$VER}
In your case:
extra_build_args: "--build-arg CURRENT_DD_VERSION=${VER}"
You also have the documentation "Environment variables"
To set custom environment variables, you need to specify the variables in the workflow file.
You can define environment variables for a step, job, or entire workflow using the jobs.<job_id>.steps[*].env, jobs.<job_id>.env, and env keywords.
The examples would use $VER
Or:
extra_build_args: "--build-arg CURRENT_DD_VERSION=${{ env.VER }}"
I'm currently adding GCP to our ansible system as up until now we've done the lengthy process of creating images, instance templates, groups and deploying them all manually with the CLI suite.
I'm getting stuck on an error with network interfaces trying to create a simple Instance Template using the same parameters we used to do manually.
Error:
"msg": "argument network is of type <class 'str'> found in 'properties -> network_interfaces'. and we were unable to convert to dict: dictionary requested, could not parse JSON or key=value"
We don't have a default network for our GCP instances as we have a very specific setup so omitting the network parameter isn't viable either. When I do I get the error The resource 'projects/<PROJECT_NAME>/global/networks/default' was not found\",. As a test when I put the default network as my parameter I again get the <class 'str'> error.
I'm feel like I'm losing my mind. Here is my playbook (with parts changed for company anonymity):
- hosts: localhost
vars_files:
- ../vault/vault.yml
vars:
current_date: "{{ ansible_date_time.year }}{{ ansible_date_time.month }}{{ ansible_date_time.day }}"
site_code: [ eur ]
nat_zone: [ a ]
project_name: "PROJECT_NAME"
network_name: "STG-NET"
image: "haproxy-master-20210219-01"
- name: Create instance template in staging
google.cloud.gcp_compute_instance_template:
name: "ew2-{{ item[1] }}-ig-stg-{{ item[0] }}-haproxy-tpl-{{ current_date }}-test"
properties:
disks:
- auto_delete: true
boot: true
initialize_params:
source_image: "projects/{{ project_name }}/global/images/{{ image }}"
machine_type: n1-standard-1
network_interfaces:
- network: 'projects/{{ project }}/global/networks/{{ network }}'
access_configs:
- name: access_config
type: ONE_TO_ONE_NAT
project: "{{ project_name }}"
auth_kind: "{{ gcp_auth_kind }}"
service_account_file: "{{ gcp_eur_service_account_file }}"
scopes:
- https://www.googleapis.com/auth/compute
state: present
with_nested:
- "{{ site_code }}"
- "{{ nat_zone }}"
I've also tried the network param without using variables. I've tried without quotation marks. I've tried without the hyphen which is syntax incorrect and subtly changes the error to complain about a list not being a dict instead.
Any guidance as to what I'm getting wrong here would be greatly appreciated!
Environment details:
ansible-playbook --version
ansible-playbook 2.10.5
config file = /home/USER/ansible_aws/ansible.cfg
configured module search path = ['/home/USER/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
executable location = /usr/local/bin/ansible-playbook
python version = 3.6.8 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
Disclaimer: I have no experience with GCP and nothing to correctly test this against. Meanwhile I have some experience in reading ansible documentation and testing module usage for correct parameters (at least at pure ansible level...)
As I first did, you probably flew over the documentation and its examples a little to fast ;). Meanwhile the specific parameter description is very clear:
network - dictionary
Hence a str is definitely not what is expected, as explicitely reported by your error message. We get more information in the comment:
[...] This field represents a link to a Network resource in GCP. It can be specified in two ways. First, you can place a dictionary with key selfLink and value of your resource's selfLink Alternatively, you can add register: name-of-resource to a gcp_compute_network task and then set this network field to {{ name-of-resource }}
If you look correctly at the examples, you'll see that they demonstrate the second scenario above (creating/registering a network to use the registered var directly in that parameter).
Taking for granted your own example in your question is using a ressource selfLink (have no clue if your current value looks correct or not...), I guess you should modify your definition as follows (abridged to network interfaces only):
network_interfaces:
- network:
selfLink: 'projects/{{ project }}/global/networks/{{ network }}'
access_configs:
- name: access_config
type: ONE_TO_ONE_NAT
I am currently using a .env file to get environment variables in FASTFILE, but now I am trying to automate the fastlane using GitLab CI/CD.
Since the .env file which has all the keys can not be pushed to the branch I have to declare all the .env or the environment variables in the GitLab runner's environment variable.
I want to know how can I use the GitLab runners's environment variable in my fastfile.
lane :build_staging do |options|
environment_variable(set: { 'ENVFILE' => '.env.staging' }) // I want to use the GitLab environment variable
clean
gradle(task: options[:task], build_type: 'Staging', project_dir: 'android/')
end
In Settings > Variables, you can define the whole file as a variable with a specified scope :
In your gitlab-ci, you would use it by specifying the variable name (in my example $ENV_FILE) and the scope using stage keyword in your job :
build:
stage: staging
script:
# do your work here
You can find more info in the documentation for variable file type and scope.
I am using the Azure DevOps server pipeline shell script task when I passed the "$(Build.SourcesDirectory)" variable as a shell script arguments, I found the path is not getting "/" while printing the variable.
Here is the Azure DevOps Pipeline Task:
Here is my shell script:
!/bin/bash
echo $1
Here is the output of the pipeline:
please give some idea how I can get actual path (with "/") while printing the variable?
I found the solution.
I have added Azure DevOps Server 2019 predefine variable as extra vars in azure-pipelines.yml like this:
- task: Ansible#0
inputs:
ansibleInterface: 'agentMachine'
playbookPathOnAgentMachine: 'ansible/tfs_playbooks/install_agent.yml'
inventoriesAgentMachine: 'file'
inventoryFileOnAgentMachine: 'hosts.yml'
args: '--extra-vars "build_source_dir=$(Build.SourcesDirectory)"'
Then I can access the variable in my playbook using this:
---
- hosts: localhost
tasks:
- name: show debug
debug:
msg: "Dir {{ build_source_dir }}"
If I am not guess wrong, the agent this pipeline is using located in Windows?
Please try with the pass the variable as $BUILD_SOURCESDIRECTORY without any double or single quote(s).