I've tried looking online but could not find an answer as the documentation (and the API) for Azure Python SDK is just horrible.
I have a Container Registery on Azure with a list of allowed IPs for public access. I'd like to modify that list by adding a new IP using Python.
I'm not sure the API supports it or how to achieve this using ContainerRegistryManagementClient.
Can't agree more that documentation (and the API) for Azure Python SDK is just horrible :)
If you want to add a list of allowed IPs for public access to your Container Registery on Azure, just try the code below using REST API:
from azure.identity import ClientSecretCredential
import requests
TENANT_ID= ""
CLIENT_ID = ""
CLIENT_SECRET = ""
SUBSCRIPTION_ID = ""
GROUP_NAME = ""
REGISTRIES = ""
#your public ip list here
ALLOWED_IPS = [{
"value": "167.220.255.1"
},
{
"value": "167.220.255.2"
}
]
clientCred = ClientSecretCredential(TENANT_ID,CLIENT_ID,CLIENT_SECRET)
authResp = clientCred.get_token("https://management.azure.com/.default")
requestURL = 'https://management.azure.com/subscriptions/'+SUBSCRIPTION_ID+'/resourceGroups/'+GROUP_NAME+'/providers/Microsoft.ContainerRegistry/registries/'+REGISTRIES+'?api-version=2020-11-01-preview'
requestBody = {
"properties": {
"publicNetworkAccess": "Enabled",
"networkRuleSet": {
"defaultAction": "Deny",
"virtualNetworkRules": [],
"ipRules": ALLOWED_IPS
},
"networkRuleBypassOptions": "AzureServices"
}
}
r = requests.patch(url=requestURL,json=requestBody,headers={"Authorization":"Bearer "+ authResp.token})
print(r.text)
Result:
Before you run this, pls make sure that your client app has been granted the required permissions(Azure subscription roles, such as contributor).
Related
I'm trying to communicate with rancher API, tried different combinations, getting the same result every time:Unauthorized 401: must authenticate
steps to reproduce:
1)Create Rancher API key and secret
2)Create a simple script that uses them to deploy a test workload.
import requests
api_url = "https://myrancherurl.com/v3/project/c-m-qh7tkqn4/jobs"
access_key = "token-zmdpqs"
secret_key = "fr9v6z9xxfqdgmjv2k9z44zvx6mlrandomtoke"
token=access_key+":"+secret_key
# Set the API token
headers = { "Authorization": "Bearer "+token }
# Set the payload for the API request
payload = {
"name": "my-job",
"jobConfig": {
"image": "nginx:latest",
"command": ["nginx", "-g", "daemon off;"],
"restartPolicy": {
"name": "Never"
}
}
}
# Send the API request to create the job
response = requests.post(api_url, json=payload, headers=headers)
# Print the API response
print(response.json())
I'm not 100% sure what exaclty is "Project id", so I tried different combinations, results are the same. I have the impression, that additional config has to be done on rancher side, but can't find any info.
Any ideas?
I've tried also using the official python library, but it seems outdated(and also returns the same erro)
Every object in the Rancher API has an id. Project is a like a group used to organize various namespaces, and workloads.
There are three types of clients that are used to interact with the Rancher API.
Management (Used to interact with general objects not tied to any cluster/project)
Cluster (Used to interact with objects that are tied to a specific cluster)
Project (Used to interact with objects that are tied to a specific project)
Sample code:
pip install git+https://github.com/rancher/client-python.git#master
import rancher
rancher_url = 'https://rancher.example.com/v3'
rancher_token = 'token-abcde:abcdefghijklmnopqrstuvwxyz0123456789'
rancher_verify_ssl_certs = True
management_client = rancher.Client(
url=rancher_url,
token=rancher_token,
verify=rancher_verify_ssl_certs
)
clusters_info = management_client.list_cluster(name='leo-downstream')
my_cluster = clusters_info.data[0]
projects_info = management_client.list_project(name='Default')
default_project = projects_info.data[0]
default_project_url = default_project.links['self'] + '/schemas'
default_project_client = rancher.Client(url=default_project_url, token=rancher_token, verify=False)
containers = [
{
'name': 'one',
'image': 'nginx',
}
]
default_project_client.create_workload(
name='test-workload-creation',
namespaceId='default',
scale=1,
containers=containers
)
TLDR: azurerm_function_app_function will work fine on Terraform Apply, but disappears from Azure Portal afterwards.
I am trying to deploy an Azure Function via Terraform for months now and have not had any luck with it.
The Terraform apply will run fine. I will then go into the Azure Portal and look at the function app functions and this function will be there. However when I refresh the blade the function will disappear. I have made the same function and deployed it via VS Code no issues, but with Terraform there is no luck.
resource "azurerm_linux_function_app" "main" {
name = "tf-linux-app"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
service_plan_id = azurerm_service_plan.main.id
storage_account_name = azurerm_storage_account.main.name
storage_account_access_key = azurerm_storage_account.main.primary_access_key
site_config {
app_scale_limit = 200
elastic_instance_minimum = 0
application_stack {
python_version = "3.9"
}
}
app_settings = {
"${azurerm_storage_account.main.name}_STORAGE" = azurerm_storage_account.main.primary_connection_string
}
client_certificate_mode = "Required"
identity {
type = "SystemAssigned"
}
}
resource "azurerm_function_app_function" "main" {
name = "tf-BlobTrigger"
function_app_id = azurerm_linux_function_app.main.id
language = "Python"
file {
name = "__init__.py"
content = file("__init__.py")
}
test_data = "${azurerm_storage_container.container1.name}/{name}"
config_json = jsonencode({
"scriptFile" : "__init__.py",
"disabled": false,
"bindings" : [
{
"name" : "myblob",
"type" : "blobTrigger",
"direction" : "in",
"path" : "${azurerm_storage_container.container1.name}/{name}",
"connection" : "${azurerm_storage_container.container1.name}_STORAGE"
}
]
})
}
As far as the Python script, I'm literally just trying
the demo found here
that Azure provides.
__init__.py:
import logging
import azure.functions as func
def main(myblob: func.InputStream):
logging.info('Python Blob trigger function processed %s', myblob.name)
I tried running Terraform apply, I expected the function app to appear and stay there, but it appears and then disappears. I also tried deploying a C# function to a Windows app. This worked as expected, but I now need the script in Python.
I would like to set the rules tab of my firebase object to read only.
When I take off the write parcel I got an error on my python when trying to add files to my storage.
Below is my code
import firebase_admin
config={
"apiKey": "xxx",
"authDomain": "xxx",
"databaseURL": "xxx",
"projectId": "xxx",
"storageBucket": "xxx",
"messagingSenderId": "xxx",
"appId": "xxx",
"measurementId": "xxx"
}
# Initialize connection to firebase_admin
firebase = firebase_admin.initialize_app(config)
storage = firebase.storage()
path_on_cloud ="Data quality report/Data quality report.py"
path_local = "Data_quality_report.py"
storage.child(path_on_cloud).put(path_local)
My rules tab is
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read;
allow write: if request.auth != null;
}
}
}
Do you guys know how to fix this problem?
Thank you in advance
Don't initialize it that way!
You are using the firebase_admin package which using the Firebase Admin SDK. To initialize it create a new service account key file which is then used for initializing.
Admin does what it sounds like it would do. It has all privileges.
Refer the official docs for proper explanation on setup. (I am really bad at explaining things).
https://firebase.google.com/docs/storage/admin/start#python
Trying to deploy an App Engine instance from Python by using service account. The goal is to spin up a lot of instances, do some heavy network task (download and upload files) and shut them down afterwords.
I'm trying to do it with service account from Python runtime, but getting the following error
TypeError: Missing required parameter "servicesId"
What could be wrong or is there a better solution for such task? Thanks and the code is below:
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'service.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
gcp = build('appengine', 'v1', credentials=credentials)
res = gcp.apps().create(body={"id":"251499913983"})
app_json = {
"deployment": {
"files": {
"my-resource-file1": {
"sourceUrl": "https://storage.googleapis.com/downloader_sources/hello-world/main.py"
}
}
},
"handlers": [
{
"script": {
"scriptPath": "main.app"
},
"urlRegex": "/.*"
}
],
"runtime": "python27",
"threadsafe": True
}
res2 = gcp.apps().services().versions().create(body=app_json)
I guess you need to specify the service you want to deploy to. You could use default:
gcp.apps().services().versions().create(serviceID=default, body=app_json)
See doc for more details.
I am looking for a python program which will run the URL. Simple, it just needs to run the URL produced from the application with provided credentials to access the application. I will schedule to run the python script every night.
I have an application that produces the URL. If I run that URL, it will produce the JSON file.
I am trying to pre-cache the output of the application so I want to run the URL every morning.
Below are the information:
USERNAME = "test"
PASSWORD = "test5"
HOST = 'appl.xyz.net'
PORT = 8080
Sample URL is:
http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1¶mid=4221
JSON:
{
"queryInfo":{
"totalRows":"3"
},
"resultset":[
[
4215,
null,
"AAA"
],
[
4215,
null,
"BBB"
]
],
"metadata":[
{
"colIndex":0,
"colType":"Numeric",
"colName":"id"
},
{
"colIndex":1,
"colType":"String",
"colName":"Name"
},
{
"colIndex":2,
"colType":"String",
"colName":"City"
}
]
}
Thanks
Use the python-requests library.
Then all you need to do is:
import requests
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1¶mid=4221'
user = 'test'
password = 'test5'
# Takes care of the HTTP authentication
data = requests.get(url, auth=(user, password))
json_data = data.json()
StvnW has provided a link in the comments to CURL alternative in Python if you do not wish to install any other libraries.